I'm trying to use std::enable_if
to selectively enable functions on a class based on the value of an enum passed to it. Here's how I'm currently trying to do it:
// class def
template<MyEnum E>
class ClassA {
// function
template <MyEnum EN = E, typename = std::enable_if_t<EN != MyEnum::some_value>>
void customFunction(double v);
};
When I test this without actually creating the function definition, it works fine and the custom function only works if the enum is correct. The problem is I seemingly can't define it in my cpp file, as doing something like:
template <MyEnum E, typename = std::enable_if_t<E != MyEnum::some_value>>
void ClassA<EN>::customFunction(double v) {}
gives me the error "Too many template parameters in template redeclaration"
. I know I could probably just define it in my header file, but I have a feeling there's a better way to do this.
Thanks for any help!
You need to add a separate template parameter clause when defining the member template outside the class. Also note that you don't need to specify the default argument when defining the member template.
Thus, the corrected program should look like:
enum MyEnum{some_value};
template<MyEnum E>
class ClassA {
template <MyEnum EN = E, typename = std::enable_if_t<EN != MyEnum::some_value>>
void customFunction(double v);
};
//this is the correct syntax to define the member template outside the class template
template <MyEnum E>
template<MyEnum EN, typename> //added this parameter clause
void ClassA<E>::customFunction(double v) {}