C++ 将字符串转换为类型名

Elg*_*ath 7 c++ templates typename

所以我发现各种文章和帖子都说没有办法转换typename为,string但我还没有找到相反的。我有一个template专业化的功能:

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

template <>
void foo<int>(int sth) {}
...
Run Code Online (Sandbox Code Playgroud)

我正在从一个这样构造的文件中读取:

int 20
double 12.492
string word
Run Code Online (Sandbox Code Playgroud)

有没有办法foo()根据文件的内容调用正确的专业化?

Rak*_*111 5

是的,但它需要手动代码,并且您知道将出现在文件中的所有类型。那是因为模板是编译时构造,不能在运行时实例化。

如果您愿意,您可以随时使用预处理器或其他技巧来尝试减少样板。

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));
}
Run Code Online (Sandbox Code Playgroud)

当然,这要求您传入正确的类型(没有隐式转换!)。我看不出有什么办法可以避免这种情况。