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

前端 未结 9 1744
猫巷女王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:18

    TypeID is never a good idea. It relies on RTTI. By the way here is your answer :http://www.parashift.com/c++-faq-lite/templates.html#faq-35.7

    0 讨论(0)
  • 2020-12-13 20:18

    One more solution is:

    if(std::is_same<T, int>::value)
         //It is int
    if (std::is_same<T, double>::value)
         //It is double
    if (std::is_same<T, long double>::value)
         //It is long double
    
    0 讨论(0)
  • 2020-12-13 20:20

    This way.

    ostream & operator << (ostream &out, Vector<int> const & vec)
    {
        // ...
    }
    

    The compiler will choose this function over the function template if you pass Vector<int>.

    Edit: I found this article, which attempts to explain why to prefer overloading to template specialization.

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