c++ - Metaprogramming with std::is_same -
is possible following compiles without template specialization?
template <class t> class { public: #if std::is_same<t,int> void has_int() {} #elif std::is_same<t,char> void has_char() {} #endif }; a<int> a; a.has_int(); a<char> b; b.has_char();
yes. make function templates , conditionaly enable them using std::enable_if
:
#include <type_traits> template <class t> class { public: template<typename u = t> typename std::enable_if<std::is_same<u,int>::value>::type has_int() {} template<typename u = t> typename std::enable_if<std::is_same<u,char>::value>::type has_char() {} }; int main() { a<int> a; a.has_int(); // ok // a.has_char(); // error }
the solution the other answer might not feasible if class big , has got many functions need regardless of t
. can solve inheriting class used these special methods. then, can specialize base class only.
in c++14, there convenient type aliases syntax can become:
std::enable_if_t<std::is_same<u, int>::value>
and c++17, shorter:
std::enable_if_t<std::is_same_v<u, int>>
Comments
Post a Comment