Jyt*_*tug 1 c++ templates traits
我想知道我想要实现的目标是否可行 C++
假设我有一个模板
template<typename T>
struct Foo {
static void foo();
};
Run Code Online (Sandbox Code Playgroud)
和非constexpr char c.现在,我想创建一个实例Foo并使用它做一些事情,具体取决于我的角色的值:
if (c == 'i')
Foo<int>::foo();
else if (c == 'f')
Foo<float>::foo();
....
Run Code Online (Sandbox Code Playgroud)
有更优雅的方式吗?我想的可能是写一个char trait,像这样:
template<char c>
struct char_trait {};
template<>
struct char_trait<'i'> {
using type = int;
};
Run Code Online (Sandbox Code Playgroud)
但由于c非constexpr,这没有多大意义.
我会很感激一些提示
正如评论中所提到的,模板(traits)版本不适用于运行时评估.
你可以做些什么来避免长时间if() {} else if()级联是在地图中组织你的东西:
std::map<char,std::function<void ()>> foo_calls {
{ 'i', Foo<int>::foo } ,
{ 'f', Foo<float>::foo } ,
// ...
};
Run Code Online (Sandbox Code Playgroud)
并使用
auto it = foo_calls.find(c);
if(it != foo_calls.end) {
(it->second)();
}
Run Code Online (Sandbox Code Playgroud)