【问题标题】:Friend function defined inside class template. Function template redefinition error在类模板中定义的朋友函数。函数模板重定义错误
【发布时间】:2015-05-23 13:44:50
【问题描述】:

以下是两个代码示例。第一个为类模板Vector 定义operator+(),而第二个只是声明函数但将函数定义移到类主体之外。第一个示例导致以下错误:

main.cpp(4): error C2995:
'Vector<L,T> operator +(const Vector<L,T> &,const Vector<L,T> &)' :
function template has already been defined

这是我的问题:

  1. 为什么 main() 中的两个模板实例化会导致函数模板重定义错误?根据我的理解,由于模板参数不同,它们应该会产生唯一的实例。
  2. 将函数定义移到类主体之外如何解决错误?

错误示例:

template<int L, typename T>
class Vector {

  template<int L, typename T> friend
  Vector<L, T> operator+(const Vector<L, T>& lhs, const Vector<L, T>& rhs) {
    return Vector<L, T>();
  }

private:
  T data[L];
};

int main() {
  Vector<42, double> v42d;
  Vector<24, int> v24i;

  return 0;
}

工作样本:

template<int L, typename T>
class Vector {

  template<int L, typename T> friend
  Vector<L, T> operator+(const Vector<L, T>& lhs, const Vector<L, T>& rhs);

private:
  T data[L];
};

template<int L, typename T>
Vector<L, T> operator+(const Vector<L, T>& lhs, const Vector<L, T>& rhs) {
  return Vector<L, T>();
}

int main() {
  Vector<42, double> v42d;
  Vector<24, int> v24i;

  return 0;
}

【问题讨论】:

  • 您在两个示例中都隐藏了模板参数。这是你的真实代码吗?
  • 顺便说一句,阴影已修复,clang 接受代码而 g++ 拒绝它Demo
  • @Jarod42 只要参数模板变量和返回类型的模板变量都明确指定,错误在MSVC2013上是一样的。
  • @Columbo 是的。这是一个基于我的实际代码的示例,它也隐藏了参数,并且花了我 4 个小时来找到根本原因:/

标签: c++ templates


【解决方案1】:

模板类型 L 和 T 是已知的,所以不需要重新引入。事实上,对朋友函数这样做会导致它们掩盖为类定义的函数。

这解决了它:

template<int L, typename T>
class Vector {

    friend
    Vector<L, T> operator+(const Vector<L, T>& lhs, const Vector<L, T>& rhs) {
        return Vector<L, T>();
    }

private:
    T data[L];
};

相当于:

template<int L, typename T>
class Vector {

    friend
    Vector operator+(const Vector& lhs, const Vector& rhs) {
        return Vector();
    }

private:
    T data[L];
};

【讨论】:

  • 你甚至可以省略&lt;L, T&gt;
猜你喜欢
  • 1970-01-01
  • 2016-10-19
  • 1970-01-01
  • 2023-03-25
  • 2016-06-23
  • 2011-05-16
  • 2016-07-14
  • 2012-03-08
  • 1970-01-01
相关资源
最近更新 更多