템플릿 정의에서 친구 함수
-
21-09-2019 - |
문제
내 질문은 약간 관련이 있습니다 이것 하나.
일부 클래스의 경우 연산자에 과부하를주고 싶습니다.
template <class T>
class A{
T t;
public:
A(T init) : t(init){}
friend ostream& operator<< <> (ostream &os, const A<T> &a); //need forward declaration
//template <class U> friend ostream& operator<< (ostream &os, const A<U> &a);
};
다른 표기법으로 동일한 것을 정의합니까? 아니면 첫 번째 버전이 <<의 <<의 인스턴스 (이 경우 내 클래스 A와 동일한 t)가 A의 친구 인 인스턴스가 더 제한적입니까?
해결책
첫 번째 버전은 우정을 operator<<
특정 유형의 경우 A<T>
두 번째는 하나를 만듭니다 operator<<
그것은 필요합니다 A<SomeType>
친구.
예, 첫 번째는 더 제한적입니다.
template<class T>
ostream& operator<< (ostream& os, const A<T>& a) {
A<double> b(0.0);
b.t; // compile error with version 1, fine with version 2
return os;
}
int main() {
A<int> a(0);
cout << a << endl;
}
다른 팁
친구 함수의 정의는 템플릿에 대한 예외가 있습니다. 이를 쓸 수 있습니다.
template <class T>
class A{
T t;
public:
A(T init) : t(init){}
friend ostream& operator<<(ostream &os, const A &a)
{ // Implementation in the class
}
};
그리고 각 인스턴스에 대해 자동으로 생성 된 일반 기능을 만드는 이점이 있습니다. A<T>
당신은 창조합니다.
참조 : http://www.parashift.com/c++-faq-lite/templates.html#faq-35.16
제휴하지 않습니다 StackOverflow