how to query if(T==int) with template class

前端 未结 9 1758
猫巷女王i
猫巷女王i 2020-12-13 19:43

When I\'m writing a function in a template class how can I find out what my T is?

e.g.

template 
ostream& operator << (os         


        
9条回答
  •  暖寄归人
    2020-12-13 20:07

    C++ templates don't work this way. The general idea of templates is express somethings which is common for a lot of different types. And in your case you should use template specialization.

    template ostream& operator<< (ostream& out, const vector& v)
    {
        // your general code for all type
    }
    // specialized template
    template<> ostream& operator<< (ostream& out, const vector& vec)
    {
        // your specific to iny type code goes here
    }
    

    Then C++ compiler will call this function when you use int type and general implementation for any other type

    std::vector f(5, 5);
    std::cout << f;
    

提交回复
热议问题