Comparing typenames in C++

前端 未结 5 1417
孤独总比滥情好
孤独总比滥情好 2021-02-13 18:13

I typed this into a template function, just to see if it would work:

if (T==int)

and the intellisense didn\'t complain. Is this valid C++? What

相关标签:
5条回答
  • 2021-02-13 18:44

    No, you can't use if (T == int) and std::cout<<(int)int;

    0 讨论(0)
  • 2021-02-13 18:45

    Just to fit your requirement you should use typeid operator. Then your expression would look like

    if (typeid(T) == typeid(int)) {
        ...
    }
    

    Obvious sample to illustrate that this really works:

    #include <typeinfo>
    #include <iostream>
    
    template <typename T>
    class AClass {
    public:
        static bool compare() {
            return (typeid(T) == typeid(int));
        }
    };
    
    void main() {
        std::cout << AClass<char>::compare() << std::endl;
        std::cout << AClass<int>::compare() << std::endl;
    }
    

    So in stdout you'll probably get:

    0
    1
    
    0 讨论(0)
  • 2021-02-13 18:45

    No, this is not valid C++.

    IntelliSense is not smart enough to find everything that is wrong with code; it would have to fully compile the code to do that, and compiling C++ is very slow (too slow to use for IntelliSense).

    0 讨论(0)
  • 2021-02-13 18:46

    Is this what you're trying to do?

    if(typeid(T) == typeid(int))
    

    and this?

    cout << typeid(int).name();
    
    0 讨论(0)
  • 2021-02-13 19:02

    Your probably didn't even instantiate your template, that's why it compiled.

    0 讨论(0)
提交回复
热议问题