lundi 3 février 2020

std::enable_if for template method defined in cpp

I work on a templated class whose method definitions are in the cpp file (and works well for its purpose). Now I would like to add another method which will be enabled for certain class template parameter only. I am able to do that if the definition is in the header using std::enable_if.

.h

template <typename T>
class MyClass
{
   template <typename = typename std::enable_if<std::is_same<SpecialType, T>::value>::type>
   T& Foo()
   {
      // Implementation...
   }
}

However, I don’t seem to be able to make it work if the implementation is in the cpp file. My current attempt:

.h

template <typename T>
class MyClass
{
   template <typename = typename std::enable_if<std::is_same<SpecialType, T>::value>::type>
   T& Foo();
}

.cpp

template <
   typename T,
   typename = typename std::enable_if<std::is_same<SpecialType, T>::value>::type>
T& MyClass<T>::Foo()
{
   // Implementation...
}

template class MyClass<SpecialType>; // Explicit instantiation

...compiles with error:

error C2244 : 'MyClass<T>::Foo' : unable to match function definition to an existing declaration
note: see declaration of 'MyClass<T>::Foo'
note: definition
note: 'T& MyClass<T>::Foo(void)'
note: existing declarations
note: 'T& MyClass<T>::Foo(void)'

Which is not very helpful. What am I doing wrong?

Aucun commentaire:

Enregistrer un commentaire