c++ - 将 std::type_index 作为模板参数传递给函数模板

标签 c++ templates

考虑以下代码(工作正常):

namespace fruit {
   struct apple{};
}

namespace language{
   struct english{};
}

typedef std::pair<std::string, std::type_index> myPairType;

std::unordered_map<std::string, myPairType> myMap =
{
    {"paul", {"likes", std::type_index(typeid(fruit::apple))} },
    {"jonas",  {"likes", std::type_index(typeid(language::english))} }
};

现在我有以下功能模板:

template <typename T>
void GenerateProfile(void* data) {
    T* data_casted = reinterpret_cast<T*>(data);
     //the data are then set to some database
}

调用 GenerateProfile 函数时如何将 fruit::applelanguage::english 作为模板参数传递?

myPairType myPair = myMap.at("paul");  //This works fine
fruit::apple* ptr = nullptr; //or fruit::apple* ptr = ...
GenerateProfile<?>(ptr); 

//GenerateProfile<myPair.second>(ptr) is not compiling

//GenerateProfile<fruit::apple>(ptr) this one compile but I want to acess fruit::apple from myPair

最佳答案

std::type_index 在运行时存储类型信息。模板是一种编译时结构。因此,您需要一种从运行时世界转换为编译时世界的方法:if/else 语句链起作用。

if(myPair.second == std::type_index(typeid(fruit::apple)))
{
    GenerateProfile<fruit::apple>(...);
}
else if(myPair.second == std::type_index(typeid(language::english)))
{
    GenerateProfile<language::english>(...);
}

这显然可以使用模板元编程为您生成。

但是,您的方法有点代码味道——您真的需要运行时的类型信息吗?您可能需要重新考虑您的设计。

关于c++ - 将 std::type_index 作为模板参数传递给函数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51744947/

相关文章:

c++ - qPrintable 是否容易出现访问冲突?

跨平台项目中的 C# 与 C++

c++ - std::enable_if 跨编译器的不同行为(取决于外部类模板参数)

c++ - 读取不断更新的文件 (C++)

c++ - 从应用程序打开控制台

c++ - 为什么这里要调用拷贝构造函数呢?

c++ - C++ 中的模板引用参数推导失败

c++ - 错误 C2678 : binary '!=' : no operator found which takes a left-hand operand

c++ - C++模板的问题

c++ - 在不使用变量的情况下实例化 ifstream 对象