![](/img/trans.png)
[英]In VC++ Float data type value, how do you check if string or special characters are not mixed
[英]How to check if a string value is a type?
有没有一种方便的方法来检查字符串值是否是一种类型?
可以有一个内置类型列表来进行比较,但这不适用于用户定义的类型。
std::string s = "std::vector<int>";
在内部,不可能验证字符串是否是一种类型,原因很简单,因为不可能反映程序中定义了哪些类型。
在外部,如果手头没有完整的 C++ 编译器/解释器,就不可能判断给定的标记序列是否是 C++ 中的类型。 例如:
template<bool>
struct A {
using X = int;
};
template<>
struct A<false> {
constexpr static auto X = []{};
};
constexpr bool some_function() { /*...*/ }
int main() {
A<some_function()>::X();
}
这里的A<some_function()>::X
是类型还是表达式取决于some_function()
在编译时的计算结果是true
还是false
,编译时语言本质上是图灵完备的(如果没有' t 一个实现定义的操作数限制),需要评估几乎不受限制的 C++ 本身。
更糟糕的是,甚至解析 C++ 表达式都需要同样的方法,因为任何给定<
标记的含义也可能取决于任意编译时评估。
如果只有你的电脑可以运行它,那么准备一个 header 把像这样的所有东西都包含在 GCC 中:
bits/stdc++.h
然后构造一个这样的字符串(伪代码):
bool isThisType(std::string userType)
{
std::string toCompile = R"(
#include<bits/stdc++.h>
#include<listOfBuiltinTypes>
int main(){
@@yourString@@ var;
std::cout<<"size="<<sizeof(var);
return 0;
}
)";
replace(toCompile,"@@yourString@@",userType);
auto fileName = commandLineWriteToFile(toCompile); // main.cpp
auto errorString = commandLineCompileFile(fileName); // "error.."
bool isType=!commandLineCheckErrorOutput(errorString);
return isType;
}
...
bool tmp = isThisType("std::vector<int>");
否则你需要自己制作一个 C++ 编译器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.