【发布时间】: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<T>(否则,您需要显式转换)。此外,在类模板example之后缺少;。 -
@T.C.你能详细说明一下吗..请
-
@Rama In
examplefunc<int>。在其中,您将T = int作为值传递给example<enumType>,它需要T = enumType(注意这是一个不同的T)。因此,您要求将int转换为enumType,这是不可能的(隐式)。 dyp 在他的评论中建议用example<T>代替那个电话。我们不确切知道您要做什么,但这看起来是一个合理的解决方案,可以满足您的意图。根据您想要做什么,显式转换也可能是一种解决方案:example<enumType>(key, static_cast<enumType>(value)) -
@leemes 感谢您的解释。 dyp 的建议奏效了。这正是我想要的。
标签: c++ templates constructor enums instantiation