0

In a little project of mine I have situation like this:

// Header file
template <typename T>;
class AClass
{
public:
    virtual void doSomething() const;
private:
    std::vector<T> *v;
};

// separate cpp file
template <typename T>
void AClass<T>::doSomething() const
{
    // use the vector here
}

// main.cpp
#include "AClass.h"

int main()
{
    AClass<int> anObject;
    anObject.doSomething();

    return 0;
}

This piece of code compiles fine but is unable to link because in the main file the linker is unable to find an implementation for AClass unless I add this to the cpp file:

template class AClass<int>;

But that is just stupid, because it takes away the advantage of using templates.

Now the question: Is there a way to solve the linking problem without using the class forwarding in the cpp file or is this just impossible to have something like this in a separate .h file and .cpp file? Putting the forward class declaration is not an option for me.

I'd really like to have some clarification on this.

Thanks

Glenn
  • 140
  • 1
  • 7
  • 1
    If you know what set of template arguments will be used with your class template, use explicit instantiation (as you do it with `int` type argument). If not, put both template declarations and definitions in `*.h` file. – Constructor Mar 10 '14 at 17:22
  • 2
    Not related to your error, but this, `std::vector *v;` looks awfully suspicious. Why not just `std::vector v;`? If you're worried about putting a large vector as a class member, don't worry, the size of `std::vector` remains constant irrespective of the number of elements it contains. The `vector` class dynamically allocates the necessary storage and the instance only contains pointers to this allocated memory. – Praetorian Mar 10 '14 at 17:30
  • std::vector v; did give me compiler errors. I don't know why. I normally wouldn't write something like that, but that was the solution for the compiler to go away. – Glenn Mar 10 '14 at 18:09
  • If you fix your problem with a compiler diagnostic by random code changes, but do not know why it removed the diagnostic, you have moved from a problem with a known diagnostic to an unknown problem that the compiler is not diagnosing. – Yakk - Adam Nevraumont Mar 10 '14 at 18:23
  • Don't get me wrong. I do know why the piece of code gave me compile errors, but I just didn't want to deal with it back then. Like I said earlier posts I wouldn't normally do it like that. – Glenn Mar 11 '14 at 19:18

0 Answers0