我有以下代码:
#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);
}
我是一名优秀的程序员,十分优秀!