c++ - 防止模板偏特化错误

标签 c++ templates

有一个代码:

#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);
}

关于c++ - 防止模板偏特化错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40130179/

相关文章:

c++ - 有人可以解释为什么这个 vector 删除操作不能正常工作吗?

C++ Builder XE,传递和处理用户定义的消息

c++ - 构造一个包含变量类型索引中第 n 类型值的 boost 变量?

c++ - 如何通过类模板专门化运算符函数类型

c++ - 基于策略的设计决策

c++ - 在通过网络文件系统共享的HOME下安装C C++库

c++ - 为什么 std::forward 有两个签名?

c++ - 在函数参数中使用模板参数不起作用 gcc4.8

c++ - 使用 C++11 类型特征提供替代的内联实现

c++ - 如何在 C++ 中使用可变参数模板同时保持我的实现类私有(private)?