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

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

For example:

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

Expected output:

int
21条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 02:25

    A more generic solution without function overloading than my previous one:

    template
    std::string TypeOf(T){
        std::string Type="unknown";
        if(std::is_same::value) Type="int";
        if(std::is_same::value) Type="String";
        if(std::is_same::value) Type="MyClass";
    
        return Type;}
    

    Here MyClass is user defined class. More conditions can be added here as well.

    Example:

    #include 
    
    
    
    class MyClass{};
    
    
    template
    std::string TypeOf(T){
        std::string Type="unknown";
        if(std::is_same::value) Type="int";
        if(std::is_same::value) Type="String";
        if(std::is_same::value) Type="MyClass";
        return Type;}
    
    
    int main(){;
        int a=0;
        std::string s="";
        MyClass my;
        std::cout<

    Output:

    int
    String
    MyClass
    

提交回复
热议问题