C ++将字符串转换为类型名 [英] C++ convert string to typename
问题描述
因此,我找到了许多文章和帖子,说无法将 typename
转换为 string
,但是我没有找到相反的方法.我有一个具有专业化功能的 template
:
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
是否有一种方法可以根据文件的内容来调用 foo()
的正确专业化?
Is there a way to call the correct specialization of foo()
depending on the content of the file?
推荐答案
是的,但是需要手动代码,并且您知道文件中将出现的所有类型.这是因为模板是编译时构造,无法在运行时实例化.
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.
这篇关于C ++将字符串转换为类型名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!