我有一个类似的访客类:

struct Visitor
{
    template <typename T>
    void operator()(T t)
    {
        ...
    }

    void operator()(bool b)
    {
        ...
    }
};

显然, operator()(bool b) 旨在作为前面的模板功能的特殊化。

但是,它没有我以前经常看到的 template<> 语法,因此将其声明为模板专用化。但是它确实可以编译。

这样安全吗?这样对吗?

最佳答案

您的代码不是模板专门化,而是非模板函数。那里有些区别。非模板的operator()将优先于模板版本(进行完全匹配,但此处不会进行类型转换),但是您仍然可以强制调用模板函数:

class Visitor
{
public: // corrected as pointed by stefanB, thanks
   template <typename T>
   void operator()( T data ) {
      std::cout << "generic template" << std::endl;
   }
   void operator()( bool data ) {
      std::cout << "regular member function" << std::endl;
   }
};
template <> // Corrected: specialization is a new definition, not a declaration, thanks again stefanB
void Visitor::operator()( int data ) {
   std::cout << "specialization" << std::endl;
}
int main()
{
   Visitor v;
   v( 5 ); // specialization
   v( true ); // regular member function
   v.operator()<bool>( true ); // generic template even if there is a non-templated overload
   // operator() must be specified there (signature of the method) for the compiler to
   //    detect what part is a template. You cannot use <> right after a variable name
}

在您的代码中没有太大的区别,但是如果您的代码需要传递模板参数类型,它将变得更有趣:
template <typename T>
T g() {
   return T();
}
template <>
int g() {
   return 0;
}
int g() {
   return 1;
}
int main()
{
   g<double>(); // return 0.0
   g<int>(); // return 0
   g(); // return 1 -- non-templated functions take precedence over templated ones
}

关于c++ - 模板特化是否需要template <>语法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/937107/

10-11 23:00
查看更多