私は C++ の初心者で、テンプレートのしくみを理解したいと思っています。MyList
そのため、組み込みのプリミティブ型とポインターの両方を含む可能性のある汎用リストを実装しました。関数では、remove
ポインターの型と組み込みを区別して、ポインターの背後にあるオブジェクトを削除し、組み込みはそのままにしておくことができるようにしたいと考えています。
ポインターまたは非ポインターのテンプレート タイプを区別するために、次の関数を作成しました。
// distinguish between pointer and non-pointer type of template variable
template<typename T> bool is_pointer(T t) {
return false;
}
template<typename T> bool is_pointer(T* t) {
return true;
}
リスト関数remove
では、ポインターをテストし、必要に応じて削除するというアイデアがありました。ただし、delete ステートメントはコンパイルされません。
template<typename T> void MyList<T>::remove() {
...
if (is_pointer(temp->getContent())) {
// delete object pointer points to
T t = temp->getContent();
cout << t; // prints out address
// delete t; // produces compiler error (see below)
}
さまざまなタイプのリスト クラスをテストするmain.cpp
中で、とりわけ以下を呼び出します。
MyList<int> mylist; // with type int
mylist.remove();
mylist.add(3);
// add and remove elements
MyList<string> mylist2; // with type string
...
MyList<string*> mylist3; // with type string*
mylist.add(new string("three"));
mylist.remove();
ステートメントをコメント アウトdelete t;
すると、制御フローが正しいことを確認できます。if ステートメントはstring*
例としてのみ入力されています。ただし、delete
ステートメントのコメントを外すと、コンパイラは次のように文句を言います。
../mylist.h: In member function ‘void MyList<T>::remove() [with T = int]’:
../main.cpp:36:18: instantiated from here
../mylist.h:124:6: error: type ‘int’ argument given to ‘delete’, expected pointer
../mylist.h: In member function ‘void MyList<T>::remove() [with T = std::basic_string<char>]’:
../main.cpp:71:18: instantiated from here
../mylist.h:124:6: error: type ‘struct std::basic_string<char>’ argument given to ‘delete’, expected pointer
make: *** [main.o] Error 1
見えないって何?ポインターに対してのみステートメントを使用してdelete
いますが、それでもこれらのコンパイラ エラーが発生します。ift
ステートメントで出力すると、それはポインター アドレスです。