7

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.

Andreas Loanjoe
  • 2,205
  • 10
  • 26

1 Answers1

15

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>> { };
Holt
  • 36,600
  • 7
  • 92
  • 139
  • 5
    Do you *really* need to specialize for `!is_fundamental`? You can just use the primary template. – Rakete1111 Jul 21 '17 at 18:52
  • I am using the primary template for shared_ptrs, I'm building a pattern for storing lockfree values. – Andreas Loanjoe Jul 21 '17 at 18:56
  • @Rakete1111 No, it makes no sense here, I just went on with OP's code. I have updated the answer, thanks. – Holt Jul 21 '17 at 18:57
  • 3
    @AndreasLoanjoe What Rakete1111 means is that you can use a non-specialized template for non-fundamental types, and a specialized one for fundamental ones. You don't need to specialize for both, see my updated answer. – Holt Jul 21 '17 at 18:57