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

时间:2018-08-08 10:56:24

标签: 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

1 个答案:

答案 0 :(得分:7)

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>(...);
}

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

但是,您的方法是一种代码味道-您实际上在运行时是否需要类型信息?您可能需要重新考虑设计。

相关问题