Home > Mobile >  Conditionally enable member function depending on template parameter
Conditionally enable member function depending on template parameter

Time:05-28

I'm struggling to get the below code to compile. I want to enable foo function for class A only when N=3.

#include <iostream>

template <size_t N>
class A
{
public:
    template <size_t n = N, std::enable_if_t<(n == 3)>* = nullptr> int foo(int a);
};

template<size_t N> 
template <size_t n = N, std::enable_if_t<(n == 3)>* = nullptr>
int A<N>::foo(int a)
{
    return a * 4;
}

int main()
{
    A<3> a1;
    std::cout << a1.foo(10) << std::endl;

    // the below should fail to compile
    // A<4> a2;
    // std::cout << a2.foo(7) << std::endl;
}

Output

<source>:12:20: error: default argument for template parameter for class enclosing 'int A<N>::foo(int)'
   12 | int A<N>::foo(int a)
      |                    ^

CodePudding user response:

Whenever you separate a function's declaration and definition, whether it is a template function or not, default argument values can only be in the declaration, not in the definition. So, simply remove the default values from foo's definition, eg:

#include <iostream>

template <size_t N>
class A
{
public:
    template <size_t n = N, std::enable_if_t<(n == 3)>* = nullptr> int foo(int a);
};

template<size_t N> 
template <size_t n, std::enable_if_t<(n == 3)>*>
int A<N>::foo(int a)
{
    return a * 4;
}

Online Demo

  • Related