c++ - How to subclass a superclass chosen by traits? -
i have template of class (let's call a) should subclass 1 of other classes (b or c), depending on compile time conditional in custom trait struct. i'm attaching snippet reproduces behaviour.
#include <type_traits> template<typename t> class cls_template { public: using method_arg_type = t; virtual void method(method_arg_type) = 0; }; using = cls_template<float>; using b = cls_template<int>; template<typename t> struct traits { using cls = std::conditional<std::is_floating_point<t>::value, a, b>; }; //class c : public traits<float>::cls { class c : public { public: virtual void method(method_arg_type arg) {}; }; int main() { *a = new c(); }
if leave (hardcoding superclass) works fine. however, once replace class definition commented out line i'm getting following error messages:
test.cpp:21:27: error: unknown type name 'method_arg_type' virtual void method(method_arg_type arg) {}; ^ test.cpp:25:10: error: cannot initialize variable of type 'a *' (aka 'cls_template<float> *') rvalue of type 'c *' *a = new c(); ^ ~~~~~~~
why method_arg_type
no longer defined? why c
no longer recognised subclass of a
? i've found out if traits
aren't template (if hardcode type struct), works fine.
you're trying derive traits<float>::cls
of type std::conditional<std::is_floating_point<t>::value, a, b>
. it's neither a
nor b
, it's specialization of conditional
template. either derive ::type
of it, work expected, or use conditional_t
(c++14).
class c : public traits<float>::cls::type { // ok ^^^^^^ public: virtual void method(method_arg_type arg) {}; };
template<typename t> struct traits { using cls = std::conditional_t<std::is_floating_point<t>::value, a, b>; ^^ // above c++14, in c++11 you'd have write // using cls = typename std::conditional<std::is_floating_point<t>::value, a, b>::type; }; class c : public traits<float>::cls { // ok public: virtual void method(method_arg_type arg) {}; };
Comments
Post a Comment