RectからRectへの変換、およびその逆の変換を可能にする変換コンストラクターを備えたテンプレートクラスRectがあります。ただし、コードをコンパイルすると、コンパイラーは、コンストラクターがクラスの保護されたメンバーにアクセスできないことを示すエラーを出します。コードは次のとおりです。
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
template< typename T >
class Rect{
protected:
T width, height;
public:
Rect(T a, T b){
width = a;
height = b;
}
template< typename U >
Rect(Rect<U> const &r){
width = r.width;
height = r.height;
}
int area(){
return width*height;
}
};
int main(){
Rect<int> a(3,4);
Rect<float> b(a);
cout<<b.area()<<endl;
}
そして、これがコンパイルエラーです:
test.cpp: In constructor ‘Rect<T>::Rect(const Rect<U>&) [with U = int, T = float]’:
test.cpp:28:18: instantiated from here
test.cpp:10:7: error: ‘int Rect<int>::width’ is protected
test.cpp:18:5: error: within this context
test.cpp:10:14: error: ‘int Rect<int>::height’ is protected
test.cpp:19:5: error: within this context
テンプレートの特殊化を使用せず、フレンドクラスを作成せずに、この問題を解決したいと思います。私の知る限り、コンストラクターを友達として宣言することはできません。何か案は?
編集:セマンティクスを修正しました。したがって、私が構築しようとしているコンストラクターは、実際には変換コンストラクターです。
Edit2:プログラムを修正しました。