Is it possible to print a variable's type in standard C++?

前端 未结 21 2059
南笙
南笙 2020-11-22 01:41

For example:

int a = 12;
cout << typeof(a) << endl;

Expected output:

int
21条回答
  •  情书的邮戳
    2020-11-22 02:26

    As explained by Scott Meyers in Effective Modern C++,

    Calls to std::type_info::name are not guaranteed to return anythong sensible.

    The best solution is to let the compiler generate an error message during the type deduction, for example,

    template
    class TD;
    
    int main(){
        const int theAnswer = 32;
        auto x = theAnswer;
        auto y = &theAnswer;
        TD xType;
        TD yType;
        return 0;
    }
    

    The result will be something like this, depending on the compilers,

    test4.cpp:10:21: error: aggregate ‘TD xType’ has incomplete type and cannot be defined TD xType;
    
    test4.cpp:11:21: error: aggregate ‘TD yType’ has incomplete type and cannot be defined TD yType;
    

    Hence, we get to know that x's type is int, y's type is const int*

提交回复
热议问题