Search code examples
c++classgenericstypedef

C++ generic class, why do I need .cpp file?


I'm looking to write a generic class (like this: template <Class T>) in C++11 but I was told that the implementation could only be written in the .h file.

on the other side I am supposed to submit some .cpp file. May someone explain the contradiction? If all definitions and implementations need to be in the .h file why I need .cpp at all?


Solution

  • You actually don't need a .cpp file at all and there are plenty of header-only library examples.

    However, it can be beneficial to provide .cpp files for some template instantiations since this give the opportunity to ship a binary another project can link against. This can save compile-time.

    An example:

    Your header Foo.h

    template<typename T>
    class Foo {
      // some functions
    };
    

    If Foo will be usually instantiated with floating point types you could provide a Foo.cpp containing e.g.

    template class Foo<float>;
    template class Foo<double>;
    template class Foo<long double>;