gpt4 book ai didi

c++ - 如何将类链接到枚举?

转载 作者:太空宇宙 更新时间:2023-11-04 15:16:28 27 4
gpt4 key购买 nike

我有以下代码:

#include <string>

enum class Hobbit {
// typedef HobbitHelper helper;
UNKNOWN = -1, Bilbo, Frodo, Samwise
};

struct HobbitHelper {
static Hobbit decode(std::string const& s) {
if (s == "Bilbo") {
return Hobbit::Bilbo;
}
else if (s == "Frodo") {
return Hobbit::Frodo;
}
else if (s == "Samwise") {
return Hobbit::Samwise;
}
else {
return Hobbit::UNKNOWN;
}
}
};

enum class Wizard {
// typedef Apprentice helper;
UNKNOWN = -1, Gandalf, Radagast, Saruman
};

struct Apprentice { // WizardHelper :)
static Wizard decode(std::string const& s) {
if (s == "Gandalf") {
return Wizard::Gandalf;
}
else if (s == "Radagast") {
return Wizard::Radagast;
}
else if (s == "Saruman") {
return Wizard::Saruman;
}
else {
return Wizard::UNKNOWN;
}
}
};

template <typename T>
T
decoder(std::string s)
{
return ??::decode(s);
// if the typedefs were allowed, I could use T::helper::decode()
}

int main()
{
std::string s{ "Rincewind" };

auto h = decoder<Hobbit>(s);
auto w = decoder<Wizard>(s);
}

如何安排在decoder 中调用适当的助手类(HobbitHelper 或 Apprentice)?我不能在枚举中声明嵌套类型,就好像它是一个类一样。我还尝试从枚举派生助手(因为助手本身没有数据),但这也是不允许的。

有什么想法吗?

最佳答案

你可以让 helper 类型特征是外部的,并在枚举类型上模板化,为每个 enum 明确特化:

template <typename T> struct type_is { using type = T; };

template <typename > struct helper;

template <> struct helper<Hobbit> : type_is<HobbitHelper> { };
template <> struct helper<Wizard> : type_is<Apprentice> { };

template <typename T>
using helper_t = typename helper<T>::type;

然后 decode 将访问它:

template <typename T>
T decoder(std::string s)
{
return helper_t<T>::decode(s);
}

关于c++ - 如何将类链接到枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32012519/

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