使用模板参数的类型作为映射的键<"type", int>

san*_*ica 3 c++ templates c++17

我的意思是设置一个映射,m其中键是变量类型,值是ints (我可以稍后更改它)。然后,在模板化函数(不是类成员)中,使用一个简化的示例

template<typename T>
void foo(vector<T>& v) {
    int type_idx = m[T];   // How to use this?
    const int n = v.size();
    foo2(type_idx, n);
    return;
}

Run Code Online (Sandbox Code Playgroud)

这可以做到吗?定义的步骤是怎样的m,使用步骤如何?

基本形式是


    if constexpr (std::is_same_v<T, int>) {
        foo2(1, n);
    } else if constexpr (std::is_same_v<T, double>) {
        foo2(2, n);
    } else if ...
    } else {
        myprintf("Not implemented for type %s", T);
    }
Run Code Online (Sandbox Code Playgroud)

对应于m[int] = 1,m[double] = 2 , ... 但这比我想要实现的方式(如果可能的话)更麻烦。

至于打印T的正确方法,我可以找到一些。

j6t*_*j6t 9

您可以使用std::type_index。它是一个包装器std::type_info,旨在用作映射中的键。类型的对象std::type_info是使用typeid运算符生成的。

那么你的函数和映射如下所示:

#include <typeinfo>
#include <typeindex>
#include <map>
#include <vector>

void foo2(int, int);

std::map<std::type_index, int> m{
    { typeid(int), 1 },
    { typeid(double), 2 },
};

template<typename T>
void foo(std::vector<T>& v)
{
    int type_idx = m[typeid(T)];

    const int n = v.size();
    foo2(type_idx, n);
}
Run Code Online (Sandbox Code Playgroud)