【发布时间】:2019-12-29 00:44:06
【问题描述】:
我在处理模板专业化时遇到了一个问题。我想要一个以枚举作为参数的方法,并根据它调用专门的模板化方法。这是演示文稿:
#include <iostream>
enum EnumType
{
ENUM1,
ENUM2,
ENUM3
};
class Test
{
public:
template <EnumType enumType>
bool enumFunc(const int i )
{
std::cout << i << " default\n";
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;
}
【问题讨论】:
-
请编辑问题以包含您遇到的问题。
-
在
func中,您需要一个带有每个枚举值大小写的switch 语句,调用相应的特化。e仅在运行时已知,但模板参数必须在编译时已知。 -
@IgorTandetnik 这行得通。我还尝试了 constexpr 开关功能。似乎它也在工作 - 它可以是带有枚举参数的编译时方法的解决方法还是我错了?
标签: c++ templates c++17 template-specialization