メンバーがpData
であり、AxB
の任意のタイプの配列T
であるクラステンプレートがあるとします。if文からクラステンプレートのインスタンスを取得する方法は? (C++)
template <class T> class X{
public:
int A;
int B;
T** pData;
X(int a,int b);
~X();
void print(); //function which prints pData to screen
};
template<class T>X<T>::X(int a, int b){ //constructor
A = a;
B = b;
pData = new T*[A];
for(int i=0;i<A;i++)
pData[i]= new T[B];
//Fill pData with something of type T
}
int main(){
//...
std::cout<<"Give the primitive type of the array"<<std::endl;
std::cin>>type;
if(type=="int"){
X<int> XArray(a,b);
} else if(type=="char"){
X<char> Xarray(a,b);
} else {
std::cout<<"Not a valid primitive type!";
} // can be many more if statements.
Xarray.print() //this doesn't work, as Xarray is out of scope.
}
例として、Xarrayはif文の内部で構築されるため、他の場所では使用できません。 if文の前にポインタを作成しようとしましたが、その時点でポインタの型が不明なため、成功しませんでした。
この種の問題に対処する適切な方法は何でしょうか?
C++が静的に型付けされているため、「明白な」答えはありません。あるタイプのユーザにプロンプトを出すことはできません。そのタイプを作成して他の場所で使用することはできません。コンパイル時にタイプを知る必要があります!この状況に一般的に対処する1つの手法は「タイプ消去」ですが、そのためには、すべてのタイプに共通の要素を指定し、その共通要素(「印刷可能」など)を介してのみインタフェースする必要があります。 –
ここで、[this](http://stackoverflow.com/questions/1984492/runtime-determine-type-for-c)が役立つかもしれません。 –