[英]Using enum as template parameter C++
這是我要編譯的代碼。 我有一個.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 ++上引發編譯錯誤。 錯誤是“沒有匹配的初始化構造函數”。 如果我將“ somefunction”行中的enumType替換為int或double,那么一切都很好。 非常感謝您的幫助!
從unsigned int繼承枚舉。 使用此枚舉作為模板參數。
enum FooEnum : unsigned int
{ FOO1,FOO2};
template<typename EnumType>
void FooUser(EnumType t){}
int main(){
FooUser<FooEnum>(FooEnum::FOO2);
return 0;
}
不尋常的把戲,但有效!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.