Comparing typenames in C++

前端 未结 5 1406
孤独总比滥情好
孤独总比滥情好 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: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 
    #include 
    
    template 
    class AClass {
    public:
        static bool compare() {
            return (typeid(T) == typeid(int));
        }
    };
    
    void main() {
        std::cout << AClass::compare() << std::endl;
        std::cout << AClass::compare() << std::endl;
    }
    

    So in stdout you'll probably get:

    0
    1
    

提交回复
热议问题