c++ - 字符到类型的非 constexpr 转换

标签 c++ templates traits

我想知道我想要实现的目标是否可以在 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/

相关文章:

c++ - 如何在 operator[] 的声明中将 decltype 应用于成员函数

c++ - 什么样的C++模板编程可以调用 "meta programming"?

c++ - 在成员函数中创建对象

c++ - 如何为类生成字典(vector<vector<short>>)

c++ - 禁用模板类中的函数

c++ - 推导参数失败,适用于返回值

c++ - iterator_trait 的典型用例是什么

reference - 为什么特征实现不针对结构进行编译,而是针对结构的引用进行编译?

c++ - 如何利用模板复制和移动构造函数和赋值运算符?

c++ - 如何抑制由 Boost.Log 和 GCC 4.4 引起的 "warning: missing initializer"?