基于枚举参数调用专用模板方法

Call specialized template method basing on enum argument

本文关键字:参数 调用 专用 模板方法 枚举 于枚举      更新时间:2023-10-16

我在处理模板专用化时遇到了问题。我想要一个以枚举作为参数的方法,并依靠它调用专门的模板化方法。以下是演示文稿:

#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)
}