0

Simple question - why do I have to #include "listType.cpp" or get linker errors here? Why can't I just include the header?

stockListType.h:

#ifndef stockListType_H
#define stockListType_H

#include "listType.h"
#include "stockType.h"
#include "listType.cpp"

using namespace std;

class stockListType : public listType<stockType>
{
private:
    unique_ptr<int[]> sortIndicesByGainLoss;

public:
    void sortByStockSymbol();
    void sortByGainLoss();

    stockListType(int maxSize);
};

#endif
Steve M
  • 9,296
  • 11
  • 49
  • 98

1 Answers1

2

This happens because in a traditional C++ compiler approach template code "doesn't exist" as a "material execution entity" until it's instantiated for some "real" types (stockType in your case). There're however techniques called explicit instantiation which allows to to specify during processing of "listType.cpp" that later you will need an instance of the code for e.g. stockType, otherType and int. Read from this: http://msdn.microsoft.com/en-us/library/by56e477.aspx or this: http://www.cplusplus.com/forum/articles/14272/ or this: How do I explicitly instantiate a template function?

Also another reason for using a source, not pre-compiled code of template classes and functions is that it's possible to override later an implementation of a given template class, method or function for a particular template argument (recall the famous std::cout << "Hello, World " << 1 << MyClassObject << std::endl, that's the classical case when operator<<(ostream&, T&) is defined for each particular type separately.

Besides, if you take a look into standard C++ STL library (e.g. <vector> or <string>) you will see that the whole code of the classes is right in header files, or files included from header files (.tcc) even a rather complex one (see Boost.Spirit, well, if you're brave enough :) ). That's because it's not possible to create an executable code for vector until vector elements (stockType etc) are defined.

Community
  • 1
  • 1
user3159253
  • 16,836
  • 3
  • 30
  • 56