반응형
클래스 템플릿안에 friend 함수를 선언하는 방법
-
friend 함수 선언시에 함수 자체를 템플릿 모양으로 선언
-
friend 관계: N:N
#include <iostream>
using namespace std;
template<typename T>
class Point
{
T x, y;
public:
Point(T a = { 0 }, T b = { 0 }) : x(a), y(b) {}
template<typename U>
friend ostream& operator<<(ostream& os, const Point<U>& p);
};
template<typename T>
ostream& operator<<(ostream& os, const Point<T>& p)
{
return os << p.x << ", " << p.y;
}
int main()
{
Point<int> p(1, 2);
cout << p << endl;
Point<double> p2(1.2, 2.3);
cout << p2 << endl;
}
-
friend 함수를 일반 함수로 구현하고 구현부를 클래스 템플릿 내부에 포함
-
friend 관계: 1:1
#include <iostream>
using namespace std;
template<typename T>
class Point
{
T x, y;
public:
Point(T a = { 0 }, T b = { 0 }) : x(a), y(b) {}
friend ostream& operator<<(ostream& os, const Point<T>& p)
{
return os << p.x << ", " << p.y;
}
};
int main()
{
Point<int> p(1, 2);
cout << p << endl;
Point<double> p2(1.2, 2.3);
cout << p2 << endl;
}
반응형
'프로그래밍 언어 > C++' 카테고리의 다른 글
C++ 템플릿 value_type (0) | 2021.01.01 |
---|---|
c++ 템플릿 typename (0) | 2020.12.31 |
C++ 템플릿 일반화된 복사 생성자(Generic copy constructor) (0) | 2020.12.31 |
C++ 템플릿 클래스 템플릿(Class template) (0) | 2020.12.31 |
C++ 템플릿 타입 추론(Argument Decay) (0) | 2019.07.14 |