7

Say I have some class template:

template<typename T>
class {
// ....
}

I can partially specialize this template for ALL pointers by:

template<typename T>
class<T *> {
// ....
}

Can I somehow specialize the template for ALL enums? i.e., do something like: (this doesn't work, though)

template<typename T>
class<enum T> {
// ....
}
svick
  • 236,525
  • 50
  • 385
  • 514
qwer1304
  • 183
  • 1
  • 7

1 Answers1

20

use C++11 and SFINAE.

#include <type_traits>

template<typename T, typename = void>
struct Specialize
{
};

template<typename T>
struct Specialize<T, typename std::enable_if<std::is_enum<T>::value>::type>
{
   void convert() { }
};

enum E
{
};

int main()
{
   Specialize<E> spec;
   spec.convert();
}

Without C++11 use boost::enable_if and boost::is_enum

ForEveR
  • 55,233
  • 2
  • 119
  • 133
  • @qwer1304 function template specializations is not good idea. You cannot partial specialize function templates, only explicit specializations. – ForEveR Oct 05 '12 at 08:11
  • 1
    This scheme works fine for classes, but I have trouble using it with function templates, e.g.: template U f(int i); template::value, U>::type> U f(int i) { ...; } enum myenum {A,B,C,D}; main () { myenum xx; xx = f(1); // [1] xx = f(2); // [2] } With gcc 4.7.2 and using -std=c++11, [1] results in undefined reference to 'myenum f(int)' and [2] in undefined reference to 'myenum f(int)'. Ideas? – qwer1304 Oct 05 '12 at 08:19
  • @qwer1304 use some kind of overload. Like this for example http://liveworkspace.org/code/84c8a46e254f91599261dd6068821e0d – ForEveR Oct 05 '12 at 08:28
  • The liveworkspace.org thing is gone. How does the overload look like? – B3ret Mar 10 '16 at 03:48
  • @B3ret Same here.. link doesnt work, that's why is important to copy the code also in stackoverflow. Did you find out how to do it for functions? – Paolo Vigori Mar 02 '17 at 21:39
  • I think that's "tag dispatch" (in case the new link dies later) – Speed8ump Nov 08 '17 at 15:40
  • If I add the same `convert` function to the generic class `Specialize`, the program still compiles, which I expected is an "ambiguous error", as the generic version and the specialized version both match the initialization `Specialize spec`. May anyone please explain this behavior? – Kelvin Hu Feb 28 '19 at 10:09
  • Sorry, I finally noticed there is **no second parameter** of `std::enable_if`, so for enum types, it should be `Specialize`, but not what I thought `Specialize` before, and it's the specialization of the generic version. And for non-enum types, this specialization does not exist. – Kelvin Hu Mar 01 '19 at 03:20