GHL
GHL

Reputation: 572

C++ template functions and includes

I am writing a class with template functions, and trying to get rid of includes in the .h file by moving them into the .cpp file.

The declaration of my class looks like:

// myclass.h
#include <boost/archive/text_oarchive.hpp>
#include <sstream>

class MyClass{
    ...
    template<class T> void my_function(const T& t){
        std::ostringstream os;
        {
            boost::archive::text_oarchive oa(os);
            oa & t;
        }
        do_something(os);
    }
}

Given that I use a template method, where T could be anything, I have to provide the definition in the header. Is it possible to refactor this code (by defining a helper function I suppose) to enable moving the

#include <boost/archive/text_oarchive.hpp>

into the .cpp file?

Many thanks

Upvotes: 1

Views: 83

Answers (1)

Marco A.
Marco A.

Reputation: 43662

Short story: you can if you know the types you're going to use in advance and explicitly instantiate them into the cpp file.

As Konrad noted, if your T is unbound there's no way that I know to accomplish it.

Notice that moving .h files into the cpp files may be a good practice to avoid long recompilation times if those headers change (and other common issues), but in the case above (a boost header) it's unlikely that it's going to change so it might not be needed at all from a compile time point of view.

Upvotes: 1

Related Questions