Home > OS >  How to check if a string value is a type?
How to check if a string value is a type?

Time:01-29

Is there a convenient way to check if a string value is a type?

It's possible to have a list of built-in types to compare against, but that wouldn't work for user defined types.

std::string s = "std::vector<int>";

CodePudding user response:

Internally, it is impossible to verify whether a string would be a type, simply because it is impossible to reflect on what types are defined in the program.

And externally, it is impossible to tell whether a given token sequence is a type in C without essentially having a complete C compiler/interpreter at hand. For example:

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();
}

Whether A<some_function()>::X here is a type or an expression depends on whether or not some_function() evaluates to true or false at compile-time and the compile-time language is essentially Turing-complete (if there wasn't an implementation-defined limit on number of operations), requiring evaluating almost unrestricted C itself.

Even worse, the same is required to even parse C expressions, because the meaning of any given < token can also depend on arbitrary compile-time evaluation.

CodePudding user response:

If it's only your computer to run it, then prepare a header to include everything like this in GCC:

bits/stdc  .h

then construct a string like this (pseudo-code):

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>");

otherwise you'd need to make a C compiler yourself.

  • Related