考虑以下代码(工作正常):
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::apple
或 language::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/