基于枚举参数调用专用模板方法
Call specialized template method basing on enum argument
我在处理模板专用化时遇到了问题。我想要一个以枚举作为参数的方法,并依靠它调用专门的模板化方法。以下是演示文稿:
#include <iostream>
enum EnumType
{
ENUM1,
ENUM2,
ENUM3
};
class Test
{
public:
template <EnumType enumType>
bool enumFunc(const int i )
{
std::cout << i << " defaultn";
return false;
}
bool func(const EnumType e);
};
template<>
bool Test::enumFunc<ENUM2>(const int i )
{
std::cout << i << " ENUM2 n";
return true;
}
//... and other specializations
bool Test::func(const EnumType e)
{
// this one works
// return enumFunc<ENUM2>(3);
// but this:
// error: no matching function for call to 'Test::enumFunc<e>(int)
return enumFunc<e>(3);
}
int main()
{
Test a;
a.enumFunc<ENUM2>(2); // works
a.func(ENUM2); // doesnt even get there due to previous error
return 0;
}
如注释中所述,参数e
的值仅在运行时已知,因此不能使用模板专用化(在编译时计算(。以下也许是Test::func()
最简单的实现:
bool Test::func(const EnumType e)
{
switch (e) {
case ENUM1: return enumFunc<ENUM1>(3);
case ENUM2: return enumFunc<ENUM2>(3);
case ENUM3: return enumFunc<ENUM3>(3);
}
return false; // Handle error condition(s)
}
相关文章:
- 当对话框被接受时,如何用参数调用槽
- 使用用户定义的参数调用future/async并调用类方法
- 我使用向量来创建类对象列表.初始化向量时如何使用参数调用构造函数?
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- 不允许运算符 const 参数调用 const 成员函数
- 为变量模板的每个参数调用模板函数
- 如何在窗口中使用注入的 dll 中的参数调用函数
- 按引用调用与按指针参数调用的差异 前递增和后递增
- 为什么使用不匹配的参数调用重载函数仍然有效
- PowerShell 使用结构类型参数调用 C++ DLL 的导出函数
- 基于枚举参数调用专用模板方法
- C++ 如何根据作为输入传递的参数调用一个构造函数或另一个构造函数?
- 如何使用类模板参数来更改参数调用和函数签名?
- lambda 函数使用其参数作为模板参数调用模板函数
- Android:使用 c++ 中的 byte[] 参数调用 java 方法
- 使用不同的模板参数调用模板类的对象
- C++编译时检查是否可以用某种类型的参数调用重载函数
- 是否可以基于类模板的参数调用类方法和全局方法
- 使用单独的参数调用"boost::process::system()"时,获取"execv
- C++大括号初始值设定项作为参数调用不同的构造函数,然后预期