I get linker errors when compiling the following code:
Here the header file:
// Solver.h
#ifndef SOLVER_H_
#define SOLVER_H_
#include <vector>
#include "Resource.h"
#include "ValueFunction.h"
template<typename T>
class Solver {
public:
Solver(std::vector<Resource>& resources);
private:
std::vector<T> valfuncs;
};
#endif /* SOLVER_H_ */
And here the source file:
// Solver.cpp
#include "Solver.h"
template<typename T>
Solver<T>::Solver(std::vector<Resource>& resources) :
valfuncs(resources.size()) {}
// Explicit class declaration
template class Solver<ValueFunction>;
And the call:
// openadp.cpp
#include "Solver.h"
int main(int argc, char *argv[]) {
std::vector<Resource> resources(4);
Solver<ValueFunction> sol(resources);
return 0;
}
The code is compiling fine if I remove valfuncs(resources.size())
from the initialization list. Why is it not possible to initialize the vector with the class passed from my template list?
Thanks in advance, Reza
Update
Sorry, but this mini-example does not reproduce the error! I'm trying to find one which does.
Update 2
The linker error was due to a wrong order of includes in my cmake files.
Remark
This question is not a duplicate of Why can templates only be implemented in the header file? first, because (the most obvious) the code compiles and second, there is an implicite instantiation of the Solver
template: template class Solver<ValueFunction>;
, thus the compiler is aware of an instance of the defined type.