使用函数、模板元编程或任何其他解决方案返回typename



我正在编写一个缓存库作为节点插件,用作跨节点集群的通用缓存,并使用boost::message_queue将数据从一个进程传递到另一个进程,但我希望支持类型传输,因此我已设法使用std::is_same序列化并获取正在传输的数据的类型名,因此现在在接收端我有值:"int""char""double"。我需要以某种方式将这个字符串转换为一个类型名称,以传递给模板结构,从而从消息队列中正确地将数据读取到该结构中。我试着使用这里显示的模板元编程,但不确定这是否是正确的方法。

使用方式:

AccessQueue<get_typename(some_type_string)> data_packet;
// proceed to read data from message_queue

类型名称的序列化:

std::array<char, 16> MemShared::get_cpp_type() {
std::array<char, 16> result{ 0 };
if (std::is_same<T, int>::value) {
safe_copy(result, "int");
}
else if (std::is_same<T, double>::value) {
safe_copy(result, "double");
}
else if (std::is_same<T, char>::value) {
safe_copy(result, "char");
}
return result;
}
// safe_copy copies data into the std::array and ensure NULL termination

您不能在运行时确定编译时类型,并且模板参数必须在编译时已知
(请注意,您找到的示例不涉及任何运行时信息。(

您所能得到的最好的方法几乎是与序列化相反,将其分派给显式实例化的函数模板进行读取
大致如下:

template<typename T>
void read_stuff(SomeType queue)
{
AccessQueue<T> data_packet;
// Read from queue...
}
...
if (the_type == "int")
read_stuff<int>(the_queue);
else if (the_type == "double")
read_stuff<double>(the_queue);
else if (the_type == "char")
read_stuff<char>(the_queue);

相关内容