How do I check my template class is of a specific classtype?

后端 未结 8 2568
小蘑菇
小蘑菇 2020-12-16 11:04

In my template-ized function, I\'m trying to check the type T is of a specific type. How would I do that?

p/s I knew the template specification way but I don\'t want

相关标签:
8条回答
  • 2020-12-16 12:00

    You can perform static checks on the type that you have received (look at the boost type traits library), but unless you use specialization (or overloads, as @litb correctly points out) at one point or another, you will not be able to provide different specific implementations depending on the argument type.

    Unless you have a particular reason (which you could add to the question) not to use the specialization in the interface just do specialize.

    template <> int subtract( std::string const & str );
    
    0 讨论(0)
  • 2020-12-16 12:01

    Instead of checking for the type use specializations. Otherwise, don't use templates.

    template<class T> int foo(T a) {
          // generic implementation
    }
    template<> int foo(SpecialType a) {
      // will be selected by compiler 
    }
    
    SpecialType x;
    OtherType y;
    foo(x); // calls second, specialized version
    foo(y); // calls generic version
    
    0 讨论(0)
提交回复
热议问题