【发布时间】:2012-06-04 08:35:57
【问题描述】:
我有以下代码结构(Resource 和 Parameter 是空类):
求解器.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>;
求解器.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_ */
状态.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>;
状态.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_ */
值函数.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(不知道为什么会导致错误)。 -
您必须将模板类的定义放在头文件中。模板定义需要在实例化时可见。在你的情况下,它们不是,所以你的编译器很困惑。见this question。我将您的代码放在一个源文件中并编译。
-
@jrok 这不是实例化问题,据我所知,隐式实例化被编译器接受为显式实例化(参见here)。
-
当我添加 user315052 建议的更改时,我的代码编译正常。没有必要将它们放在一个文件中吗?你读过关于隐式实例化的文章吗?
标签: c++ templates constructor