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

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

For example:

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

Expected output:

int
21条回答
  •  甜味超标
    2020-11-22 02:25

    #include 
    #include 
    using namespace std;
    #define show_type_name(_t) \
        system(("echo " + string(typeid(_t).name()) + " | c++filt -t").c_str())
    
    int main() {
        auto a = {"one", "two", "three"};
        cout << "Type of a: " << typeid(a).name() << endl;
        cout << "Real type of a:\n";
        show_type_name(a);
        for (auto s : a) {
            if (string(s) == "one") {
                cout << "Type of s: " << typeid(s).name() << endl;
                cout << "Real type of s:\n";
                show_type_name(s);
            }
            cout << s << endl;
        }
    
        int i = 5;
        cout << "Type of i: " << typeid(i).name() << endl;
        cout << "Real type of i:\n";
        show_type_name(i);
        return 0;
    }
    

    Output:

    Type of a: St16initializer_listIPKcE
    Real type of a:
    std::initializer_list
    Type of s: PKc
    Real type of s:
    char const*
    one
    two
    three
    Type of i: i
    Real type of i:
    int
    

提交回复
热议问题