Andreas Loanjoe
Andreas Loanjoe

Reputation: 2399

Template specialization for fundamental types

Is there any way to make a template specialization for fundamental types only? I have tried to do the following:

template<typename T, typename = typename std::enable_if<!std::is_fundamental<T>::value>::type>
class foo
{
}

template<typename T, typename = typename std::enable_if<std::is_fundamental<T>::value>::type>
class foo
{
}

But I'm getting an error that the template is already defined.

Upvotes: 7

Views: 1134

Answers (1)

Holt
Holt

Reputation: 37606

Here you are creating two templated classes with the same name, not specializations.

You need to create a generic one and then specialize it:

// not specialized template (for non-fundamental types), Enabler will 
// be used to specialize for fundamental types
template <class T, class Enabler = void>
class foo { };

// specialization for fundamental types
template <class T>
class foo<T, std::enable_if_t<std::is_fundamental<T>::value>> { };

Upvotes: 15

Related Questions