C++ でテンプレートを使用してからしばらく経ちましたが、今では本当に必要になっています。
発生している問題を再現しましたが、実際にどのように解決したか覚えていません。
#include <iostream>
#include <vector>
namespace problem {
template <typename T>
class data {
public:
inline data(T var) {
this->var = var;
}
private:
T var;
};
class storage {
public:
inline void push(problem::data<T> * data) {
this->VData.push_back(data);
}
private:
std::vector<problem::data<T> *> VData;
};
};
int main() {
problem::storage * testStorage = new problem::storage();
problem::data<int> * testData = new problem::data<int>(256);
testStorage->push(testData);
delete testData;
delete testStorage;
return 0;
}
g++ -Wall problem.cpp で次のエラーが表示されます。
problem.cpp:17:35: error: ‘T’ was not declared in this scope
problem.cpp:17:36: error: template argument 1 is invalid
problem.cpp:21:30: error: ‘T’ was not declared in this scope
problem.cpp:21:31: error: template argument 1 is invalid
problem.cpp:21:34: error: template argument 1 is invalid
problem.cpp:21:34: error: template argument 2 is invalid
problem.cpp: In member function ‘void problem::storage::push(int*)’:
problem.cpp:18:17: error: request for member ‘push_back’ in ‘((problem::storage*)this)->problem::storage::VData’, which is of non-class type ‘int’
problem.cpp: In function ‘int main()’:
problem.cpp:29:28: error: no matching function for call to ‘problem::storage::push(problem::data<int>*&)’
problem.cpp:29:28: note: candidate is:
problem.cpp:17:16: note: void problem::storage::push(int*)
problem.cpp:17:16: note: no known conversion for argument 1 from ‘problem::data<int>*’ to ‘int*’
メンバー テンプレートを使用できることはわかっていますが、ベクターをどうするのでしょうか?
template <typename T>
inline void push(problem::data<T> * data) {
this->VData.push_back(data);
}
メンバー テンプレートを使用すると、ベクトル定義でこれらのエラーが残ります。
problem.cpp:22:30: error: ‘T’ was not declared in this scope
problem.cpp:22:31: error: template argument 1 is invalid
problem.cpp:22:34: error: template argument 1 is invalid
problem.cpp:22:34: error: template argument 2 is invalid
problem.cpp: In member function ‘void problem::storage::push(problem::data<T>*)’:
problem.cpp:19:17: error: request for member ‘push_back’ in ‘this->.VData’, which is of non-class type ‘int’