Reputation: 753
I am writing a caching library as a node-addon to be used as a universal cache across node clusters, and am using boost::message_queue
to pass data from one process to another, but I want to support transfer of types, so I have managed to serialize and get typenames of the data being transferred using std::is_same
so now on the receiving end I have values: "int"
"char"
"double"
. I need to somehow transform this string into a typename to pass to the template struct to correctly read data into the structure from the message queue. I tried using template metaprogramming like shown here but not sure if this is the correct way to go about things.
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
Upvotes: 0
Views: 218
Reputation: 66371
You can't determine a compile-time type at runtime, and a template parameter must be known at compile-time.
(Note that the example you found does not involve any runtime information.)
The best you can get is pretty much the reverse of the serialization, dispatching to an explicitly instantiated function template for reading.
Something along these lines:
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);
Upvotes: 2