【问题标题】:Templates linker error on friend function [duplicate]朋友功能上的模板链接器错误[重复]
【发布时间】:2019-06-27 07:27:57
【问题描述】:

我在学习模板时遇到过以下练习:

#include <iostream>
using namespace std;
template <class T>
class A {
    T _v;
public:
    A() {}
    A(T v) : _v(v) {}
    friend ostream & operator<<(ostream & c, const A<T> & v);
};

template <class T>
ostream & operator<<(ostream & c, const A<T> & v){
    c << v._v; return c;
}

int main()
{
    A<int>a(10);
    cout << a << endl;
    return 0;
}

这段代码 sn-p 在编译过程中应该会产生错误,它确实会产生错误。这是一个链接器错误,但我无法理解。

我尝试更改几行代码,错误似乎是由模板operator&lt;&lt; 的安装引起的,因为删除该模板并编写特定的运算符会使代码正常工作。我也觉得模板被多次实例化,不仅仅是int

但是,据我所知,模板定义似乎还不错。我错过了什么?

确切的错误(VS 2017)是: 错误 LNK2019:无法解析的外部符号“class std::basic_ostream > & __cdecl operator &,class A const &)” (??6@YAAEAV?$basic_ostream@DU?$char_traits@D@ std@@@std@@AEAV01@AEBV?$A@H@@@Z) 在 main 函数中引用

【问题讨论】:

  • 错误是什么?
  • 模板参数没有“继承”到友元函数声明。我会尝试找到一个重复的。

标签: c++ templates


【解决方案1】:

你需要声明友元函数为模板:

class A {
   ...
   template <class U>  // <-- NOTICE ---------------v
   friend ostream & operator<<(ostream & c, const A<U> & v);
   ...

或者更好的是,使用更安全的方法,尽管有点冗长:

#include <iostream>
using namespace std;

template <class T>
class A;

template <class T>
ostream& operator<<(ostream& c, const A<T>& v);

template <class T>
class A {
    T _v;

    public:
    A() {}
    A(T v) : _v(v) {}
    friend ostream& operator<< <T>(ostream& c, const A<T>& v);
};

template <class T>
ostream& operator<<(ostream& c, const A<T>& v) {
    c << v._v;
    return c;
}

int main() {
    A<int> a(10);
    cout << a << endl;
    return 0;
}

更多详情请见this page

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-12
    • 1970-01-01
    • 1970-01-01
    • 2016-10-21
    • 1970-01-01
    • 2016-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多