我想知道我想要实现的目标是否可以在 C++
中实现
假设我有一个模板
template<typename T>
struct Foo {
static void foo();
};
和一个非 constexpr char c
。
现在,我想创建一个 Foo
的实例,并根据我的角色的值对它做一些事情:
if (c == 'i')
Foo<int>::foo();
else if (c == 'f')
Foo<float>::foo();
....
有没有更优雅的方式来做到这一点?我在考虑写一个 char trait
,像这样:
template<char c>
struct char_trait {};
template<>
struct char_trait<'i'> {
using type = int;
};
但是因为 c
是非 constexpr,所以这没有多大意义。
我会很感激一些提示
最佳答案
如 the comment 中所述模板(特征)版本不适用于运行时评估。
要避免长 if() {} else if()
级联,您可以做的是在 map 中组织您的内容:
std::map<char,std::function<void ()>> foo_calls {
{ 'i', Foo<int>::foo } ,
{ 'f', Foo<float>::foo } ,
// ...
};
和使用
auto it = foo_calls.find(c);
if(it != foo_calls.end) {
(it->second)();
}
关于c++ - 字符到类型的非 constexpr 转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40809541/