防止模板部分专门化错误

Prevent template partial specialization error

本文关键字:专门化 错误 板部      更新时间:2023-10-16

有一个代码:

#include <functional>
template<typename DataType, typename Compare=std::less<DataType>>
class MyClass {
public:
  explicit MyClass(const Compare& f = Compare()) {
    compare = f;
  };
  bool foo(DataType, DataType);
private:
  Compare compare;
};
template<typename DataType>
bool MyClass<DataType>::foo(DataType a, DataType b) {
  return compare(a, b);
}

在编译时得到一个错误:

error: nested name specifier 'MyClass<DataType>::'
      for declaration does not refer into a class, class template or class
      template partial specialization bool MyClass<DataType>::foo(DataType a, DataType b) {

如何防止错误并在类外声明方法?

您必须像在主模板定义中那样提供模板参数:

//        vvvvvvvvvvvvvvvvvvvvvvvvvvvvv
template <typename DataType, typename X>
bool MyClass<DataType, X>::foo(DataType a, DataType b) {
//           ^^^^^^^^^^^
  return compare(a, b);
}