Search code examples
c++templatesc++14sfinaeenable-if

How to seperate declaration and implementation of a templated class with a default template parameter?


I like to separate the declaration and implementation of my classes. I know that the implementation of class templates and function also has to go into the header file, that's not the problem.

I'm having trouble implementing this class:

template <size_t S, std::enable_if_t<(S > 0), int> = 0>
class Foo {
public:
    Foo();
}

So far I have tried:

template<size_t S>
Foo<S>::Foo() {}

which failed with

error C3860: template argument list following class template name must list parameters in the order used in template parameter list

error C2976: 'Foo<S,<__formal>>' : too few template arguments

and

template<size_t S, int i>
Foo<S, i>::Foo() {}

which failed with

error C3860: template argument list following class template name must list parameters in the order used in template parameter list

error C3855: 'Foo<S,<unnamed-symbol>>' : template parameter '__formal' is incompatible with the declaration

I have also tried changing the template declaration to

template <size_t S, typename = std::enable_if_t<(S > 0)>>

which also failed with the first error message.

What is the correct way of doing this?


Solution

  • You cannot partially specialize template functions (that's what you're doing in the first snippet). If you're asking about how to define it outside the class, try this:

    template <size_t S, std::enable_if_t<(S > 0), int> j>
    Foo<S, j>::Foo(){}
    

    You cannot just replace std::enable_if_t<(S > 0), int> by int, as the definitions are not equivalent (the enable_if one SFINAEs out the S == 0 case).

    Live snippet