Why can't enable_if be used on specialized parameter?

I am trying to create a partial specialization for integral types. My idea was to do something similar to:

#include <type_traits>

template <typename T>
struct Class {
};

template <typename T>
struct Class<typename std::enable_if<std::is_integral<T>::value, T>::type> {
};

This however leads to the following error:

error: template parameters not deducible in partial specialization:
struct Class<typename std::enable_if<std::is_integral<T>::value, T>::type> {
       ^
note: 'T'

It does work if I use an extra template parameter:

#include <type_traits>

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

template <typename T>
struct Class<T, typename std::enable_if<std::is_integral<T>::value>::type> {
};

Why do I need the extra template parameter?

Upvotes: 2

Views: 178

Answers (1)

dau_sama
dau_sama

Reputation: 4357

In the first case you are not specializing the class. When you write:

template <typename T>
struct Class<typename std::enable_if<std::is_integral<T>::value, T>::type> {
};

that T is still a generic template type, and your compiler gets confused.

In the second case, when you write

template <typename T>
struct Class<T, typename std::enable_if<std::is_integral<T>::value>::type> {
};

You correctly specialize the template parameter Enable, and everything works fine.

If you want to specialize the first one, you should do it type by type, which is probably not what you want

template <>
struct Class<std::enable_if<std::is_integral<int>::value, int>::type> {
};

Upvotes: 3

Related Questions