1

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!

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
SprintKeyz
  • 134
  • 8
  • You're right about both of those. I was translating my code over and trying to simplify it, and that likely just happened accidentally in the process. Thanks! – SprintKeyz Mar 23 '23 at 05:04
  • Provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) – Jason Mar 23 '23 at 05:05
  • The question has been simplified! – SprintKeyz Mar 23 '23 at 05:11
  • @JaMiT I don't. I initially tried to define it in my cpp file with `template ` while keeping my header the same, but that gave the error "Out-of-line definition does not match any declaration" because the templates didn't match at all. edit: if you mean in the header as well, the second part is not actually a template parameter the user needs to pass, it's simply conditional logic in this case. – SprintKeyz Mar 23 '23 at 05:16
  • @SprintKeyz See [working demo](https://godbolt.org/z/Gozbesvb6) in [this answer](https://stackoverflow.com/a/75819487/12002570). – Jason Mar 23 '23 at 05:23
  • "*I seemingly can't define it in my cpp file*" - watch out for this: [Why can templates only be implemented in the header file?](https://stackoverflow.com/questions/495021/) – Remy Lebeau Mar 23 '23 at 05:26

1 Answers1

2

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) {}

Working demo

Jason
  • 36,170
  • 5
  • 26
  • 60