在C++中出现“template redeclaration中的模板参数太多”错误。

huangapple go评论83阅读模式
英文:

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&lt;MyEnum E&gt;
class ClassA {

    // function
    template &lt;MyEnum EN = E, typename = std::enable_if_t&lt;EN != MyEnum::some_value&gt;&gt;
    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 &lt;MyEnum E, typename = std::enable_if_t&lt;E != MyEnum::some_value&gt;&gt;
void ClassA&lt;EN&gt;::customFunction(double v) {}

gives me the error &quot;Too many template parameters in template redeclaration&quot;. 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&lt;MyEnum E&gt;
class ClassA {

template &lt;MyEnum EN = E, typename = std::enable_if_t&lt;EN != MyEnum::some_value&gt;&gt;
void customFunction(double v);
};

//this is the correct syntax to define the member template outside the class template
template &lt;MyEnum E&gt;
template&lt;MyEnum EN, typename&gt; //added this parameter clause
void ClassA&lt;E&gt;::customFunction(double v) {}

Working demo

huangapple
  • 本文由 发表于 2023年3月23日 12:32:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75819282.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定