Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ convert string to typename

So I've found a variety of articles and posts saying that there is no way to convert typename to string but I haven't found one about the opposite. I have a template of a function with specializations:

template <typename T>
void foo(T sth) {}

template <>
void foo<int>(int sth) {}
...

and I'm reading from a file constructed like this:

int 20
double 12.492
string word

Is there a way to call the correct specialization of foo() depending on the content of the file?

like image 504
Elgirhath Avatar asked Jul 01 '18 21:07

Elgirhath


1 Answers

Yes there is, but it requires manual code and that you know all the types that are going to appear in the file. That's because templates are compile time constructs and they cannot be instantiated at runtime.

You can always use the preprocessor or other tricks to try and reduce the boilerplate if you want to.

void callFoo(std::string type, std::any arg) {
  if (type == "int")
      foo<int>(std::any_cast<int>(arg));
  else if (type == "double")
      foo<double>(std::any_cast<double>(arg));
  else if (type == "string")
      foo<std::string>(std::any_cast<std::string>(arg));
}

Of course, this requires that you pass in the correct type (no implicit conversions!). I don't see any way to avoid that.

like image 131
Rakete1111 Avatar answered Sep 28 '22 21:09

Rakete1111