英文:
Getting a "Too many template parameters in template redeclaration" error in C++
问题
以下是代码部分的翻译:
// 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);
};
template <MyEnum E, typename = std::enable_if_t<E != MyEnum::some_value>>
void ClassA<E>::customFunction(double v) {}
请注意,这是代码的翻译,没有其他内容。
英文:
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!
答案1
得分: 2
你需要在类外定义成员模板时添加单独的模板参数子句。同时注意,当定义成员模板时,无需指定默认参数。因此,修正后的程序应该如下所示:
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);
};
// 这是在类模板外定义成员模板的正确语法
template <MyEnum E>
template<MyEnum EN, typename>
void ClassA<E>::customFunction(double v) {}
英文:
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) {}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论