gpt4 book ai didi

c++ - 基于枚举参数调用专门的模板方法

转载 作者:太空宇宙 更新时间:2023-11-03 17:25:13 25 4
gpt4 key购买 nike

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

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

最佳答案

如评论中所述,参数 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)
}

关于c++ - 基于枚举参数调用专门的模板方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59516082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com