【问题标题】:Using enum as template parameter C++使用枚举作为模板参数 C++
【发布时间】:2023-03-14 19:25:01
【问题描述】:

这是我要编译的代码。我有一个 .cpp 文件,我在其中执行以下操作:

typedef enum enumtags {
    ONE,
    TWO
} enumType;

template <class T> 
class example {
  public:
    example(int key, T value):
        key_(key),
        value_(value) {}
  public:
    int key_;
    T value_;
};

//Explicit instantiation since I have the template in a cpp file
template class example<enumType>;

//Now a template function in the same cpp file
template<typename T>
void examplefunc(int key, T value) {
     somefunction(example<enumType>(key, value));
}

//instantiation of the function for the types i want
template void examplefunc<enumType>(int key, enumType value);
template void examplefunc<int>(int key, int value);

这会在 clang++ 上引发编译错误。错误是“没有匹配的初始化构造函数”。 如果我用 int 或 double 替换“somefunction”行中的 enumType,一切都很好而且很花哨。非常感谢您的帮助!

【问题讨论】:

  • 无范围枚举可以隐式转换为int,但int 不能隐式转换为无范围枚举类型。
  • 您可能希望在examplefunc 中使用example&lt;T&gt;(否则,您需要显式转换)。此外,在类模板example 之后缺少;
  • @T.C.你能详细说明一下吗..请
  • @Rama In examplefunc&lt;int&gt;。在其中,您将T = int 作为值传递给example&lt;enumType&gt;,它需要T = enumType(注意这是一个不同的T)。因此,您要求将 int 转换为 enumType,这是不可能的(隐式)。 dyp 在他的评论中建议用example&lt;T&gt; 代替那个电话。我们不确切知道您要做什么,但这看起来是一个合理的解决方案,可以满足您的意图。根据您想要做什么,显式转换也可能是一种解决方案:example&lt;enumType&gt;(key, static_cast&lt;enumType&gt;(value))
  • @leemes 感谢您的解释。 dyp 的建议奏效了。这正是我想要的。

标签: c++ templates constructor enums instantiation


【解决方案1】:

从 unsigned int 继承枚举。将此枚举用于模板参数。

enum FooEnum : unsigned int
{ FOO1,FOO2};
template<typename EnumType> 
void FooUser(EnumType t){}
int main(){ 
FooUser<FooEnum>(FooEnum::FOO2); 
return 0;
}

不寻常的技巧,但有效!

【讨论】:

    猜你喜欢
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-16
    相关资源
    最近更新 更多