我有以下代碼結構(Resource
和Parameter
是空班):如何爲模板類調用非默認構造函數?
Solver.cpp
#include "Solver.h"
#include "ValueFunction.h"
using namespace std;
template<typename T>
Solver<T>::Solver(vector<vector<Resource> >& resources, const Parameter& params) :
states(resources.size()) {
for (int i=0; i<resources.size(); i++) {
states[i] = State<T>(resources[i], params);
}
}
// Explicit class declaration
template class Solver<ValueFunction>;
Solver.h
#ifndef SOLVER_H_
#define SOLVER_H_
#include <vector>
#include "Resource.h"
#include "Parameter.h"
#include "State.h"
template<typename T>
class Solver {
public:
Solver(
std::vector<std::vector<Resource> >& resources,
const Parameter& params
);
private:
std::vector<State<T> > states;
};
#endif /* SOLVER_H_ */
State.cpp
#include "State.h"
#include "ValueFunction.h"
using namespace std;
template<typename T>
State<T>::State(vector<Resource>& _resources, const Parameter& params) :
resources(_resources), valfuncs(_resources.size(), T(params)) {
}
template class State<ValueFunction>;
State.h
#ifndef STATE_H_
#define STATE_H_
#include <vector>
#include "Parameter.h"
#include "Resource.h"
template<typename T>
class State {
public:
State() {};
State(std::vector<Resource>& _resources, const Parameter& params);
~State() {};
private:
std::vector<Resource> resources;
std::vector<T> valfuncs;
};
#endif /* STATE_H_ */
ValueFunction.cpp
#include "ValueFunction.h"
ValueFunction::ValueFunction(const Parameter& _params) : params(_params) {
}
ValueFunction.h
#ifndef VALUEFUNCTION_H_
#define VALUEFUNCTION_H_
#include "Parameter.h"
class ValueFunction {
public:
ValueFunction(const Parameter& _params);
private:
const Parameter& params;
};
#endif /* VALUEFUNCTION_H_ */
通過以下調用:
#include "Solver.h"
#include "State.h"
#include "ValueFunction.h"
#include "Parameter.h"
using namespace std;
int main(int argc, char *argv[]) {
Parameter params;
vector<vector<Resource> > resources(4);
Solver<ValueFunction> sol(resources, params);
return 0;
}
而且我得到以下錯誤:
Solver.cpp:18:16: instantiated from here
ValueFunction.h:6:21: error: non-static reference member ‘const Parameter& ValueFunction::params’, can't use default assignment operator
如何正確調用ValueFunction
的非默認構造函數,或者是否有其他方式用非默認構造函數(傳遞常量引用)初始化std::vector
?
更新
的誤差在此post解釋。但是,我的問題的解決方法並不清楚。有什麼建議麼?
錯誤的發生是因爲我想'初始化與類''ValueFunction' _params' params'(不知道爲什麼這會導致錯誤)。 – Reza
您必須將模板類的定義放在頭文件中。模板定義需要在實例化處可見。在你的情況下,他們不是,所以你的編譯器很困惑。參見[這個問題](http://stackoverflow.com/questions/3749099/why-應該 - 實現 - 和 - 聲明 - 模板 - 類 - 在 - 在 - )。我把你的代碼放在一個源文件中並編譯。 – jrok
@jrok它不是一個instatiation問題,據我所知隱式實例化被編譯器接受爲explicite(參見[here](http://www.cplusplus.com/forum/articles/14272/) )。 – Reza