c++ - C++11 method template specialization for return type -
i've got next class:
class foo { public: template <typename t> t bar() { cout << "called homecoming type: " << typeid(t).name() << endl; t t = //... (some implementation here) homecoming t; } }
it's invoked in next way:
foo foo; int = foo.bar<int>(); long l = foo.bar<long>();
now i'd have different specialization cases when function invoked shared_ptr<t>
foo foo; foo.bar<shared_ptr<int>>(); foo.bar<shared_ptr<long>>();
but of course of study don't want create total specialization each type. possible implement such behaviour (can trait-based if required)?
since noone proposed yet, 1 can utilize sfinae distinguish between t
, std::shared_ptr<u>
:
template <typename t> struct is_shared_ptr_impl : std::false_type {}; template <typename t> struct is_shared_ptr_impl<std::shared_ptr<t>> : std::true_type {}; template <typename t> using is_shared_ptr = typename is_shared_ptr_impl<typename std::decay<t>::type>::type; class foo { public: template <typename t> auto bar() -> typename std::enable_if<!is_shared_ptr<t>{}, t>::type { std::cout << "t " << typeid(t).name() << std::endl; homecoming {}; } template <typename t> auto bar() -> typename std::enable_if<is_shared_ptr<t>{}, t>::type { using u = typename std::decay<t>::type::element_type; std::cout << "t shared_ptr of " << typeid(u).name() << std::endl; homecoming {}; } };
demo
c++ templates c++11 template-specialization specialization
No comments:
Post a Comment