![](/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.