且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-23 19:31:04

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

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.