c++ - Template detects if T is pointer or class -
considering following code:
class myclass { ... }; template <typename object> class list { public: void insert(const object & x) { // call when object myclass } void insert(const object & x) { // call when object myclass* } } int main() { myclass a; list<myclass> lst; list<myclass*> plst; lst.insert(a); plst.insert(new myclass); return 0; }
how tell compiler call different methods based on if template class or pointer?
how fix code above?
you can use combination of std::is_pointer
, std::enable_if
:
#include <type_traits> #include <iostream> class myclass { }; template <typename object> class list { public: template<class t=object> void insert(t t, typename std::enable_if<std::is_pointer<t>::value >::type* = 0) { std::cout << "insert pointer" << std::endl; } template<class t=object> void insert(t t, typename std::enable_if<!std::is_pointer<t>::value >::type* = 0) { std::cout << "insert non-pointer" << std::endl; } }; int main() { myclass a; list<myclass> lst; list<myclass*> plst; lst.insert(a); plst.insert(new myclass()); return 0; }
live example: https://ideone.com/ck8zdo
this allow insert both pointers , non-pointers pointer or non-pointer list. if want restrict that, can use this:
#include <type_traits> #include <iostream> class myclass { }; template <typename object> class list { public: template<class t=object> void insert(t t, typename std::enable_if<std::is_same<t,object>::value&&std::is_pointer<t>::value >::type* = 0) { std::cout << "insert pointer" << std::endl; } template<class t=object> void insert(const t& t, typename std::enable_if<std::is_same<t,object>::value&&!std::is_pointer<t>::value >::type* = 0) { std::cout << "insert non-pointer" << std::endl; } }; int main() { myclass a; list<myclass> lst; list<myclass*> plst; lst.insert(a); // plst.insert(a); // compiler error // lst.insert(new myclass()); // compiler error plst.insert(new myclass()); return 0; }
live example: https://ideone.com/3dtbfr
Comments
Post a Comment