为什么g ++需要模板类和其朋友函数的定义? [英] why does g++ need both definitions of template class and its friend function?
本文介绍了为什么g ++需要模板类和其朋友函数的定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想为模板类写一个朋友函数。
在visual studio中,我可以忽略预定义。
但是在g ++中,它是强制性的。
为什么?
#include< iostream>
使用namespace std;
// g ++需要,vs不需要
模板< class T>
class A;
模板< class T>
ostream& (ostream& c,const A< T& v);<
// - g ++的结尾需要
模板< class T>
class A {
T _v;
public:
A(){}
A(T v):_v(v){}
friend ostream& (ostream& c,const A< T& v);< T>
};
模板< class T>
ostream&运算符<<(ostream& c,const A< T& v){
c< v._v;返回c;
解决方案
b
$ b
friend ostream& (ostream& c,const A< T& v);< T>
是一种特殊的功能。 > 模板< class T>
ostream& (ostream& c,const A< T& v);<
您需要首先声明并且
A< T>
部分意味着您必须在运算符声明之前声明
模板< class T>
class A;
所以VS可能是错误的,因为 C ++ 14
14.5 .4朋友[temp.friend]
给出示例
模板< class T>课堂任务;
模板< class T>任务< T> *抢占(任务< T> *);
模板< class T>类任务{
朋友void next_time();
friend void process(task< T> *);
friend task< T> * preempt< T>(task< T> *);
模板< class C>朋友int func(C);
朋友类任务< int>;
模板< class P>朋友课frd;
};
您的示例适用于第三方好友声明。
I want to write a friend function for a template class. In visual studio, I can ignore the pre-definition both. But in g++, it is mandatory. Why?
#include <iostream>
using namespace std;
// g++ needs, vs do not needs
template <class T>
class A;
template <class T>
ostream & operator<<(ostream & c, const A<T> & v);
//- end of g++ needs
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;
}
解决方案
Because
friend ostream & operator<<<T>(ostream & c, const A<T> & v);
is a specialization of
template <class T>
ostream & operator<<(ostream & c, const A<T> & v);
you need to declare that first and the
A<T>
part means you have to declare that too before the operator declaration
template <class T>
class A;
So VS is probably wrong as C++14
14.5.4 Friends [temp.friend]
gives the example
template<class T> class task;
template<class T> task<T>* preempt(task<T>*);
template<class T> class task {
friend void next_time();
friend void process(task<T>*);
friend task<T>* preempt<T>(task<T>*);
template<class C> friend int func(C);
friend class task<int>;
template<class P> friend class frd;
};
Where your example fits the 3rd friend declaration.
这篇关于为什么g ++需要模板类和其朋友函数的定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文