1

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.

Community
  • 1
  • 1
Reza
  • 360
  • 3
  • 17
  • 2
    http://ideone.com/Z9SeH please post full minimal code that exibits the problem. – Luchian Grigore May 31 '12 at 09:11
  • Can you edit your question to include the errors you get? – Some programmer dude May 31 '12 at 09:11
  • 1
    @KerrekSB Completely unrelated. The template is explicitly instantiated in the TU in which it’s defined. – Konrad Rudolph May 31 '12 at 09:37
  • 2
    –1: The code compiles for me once I remove the unnecessary header includes, define all the classes and include ``. **Please post a complete working example.** Furthermore, what compiler are you using, how are you calling the compiler, and what errors do you get? – Konrad Rudolph May 31 '12 at 09:41
  • 1
    @Reza I compiled the code on gcc 4.7, but using empty `ValueFunction` and `Resources` classes. – juanchopanza May 31 '12 at 12:01
  • 1
    This question can be closed but it is **NOT** a duplicate of the mentioned questions. Please refer to this [article](http://www.cplusplus.com/forum/articles/14272/). – Reza Jun 01 '12 at 06:59
  • @Reza - rather than linking to an article, can you explain clearly in your question why this is not a duplicate. If you do that, flag again and I'll re-open. – Kev Jun 04 '12 at 14:23

0 Answers0