Can Template Specializations go in my .cpp?

Viewed 2222

Lets say that I have this:

struct foo {
    template <typename T>
    void bar(const T param) { cout << param << endl; }
};

Now I want to add the specialization:

template <>
void bar<char>(const char param) { cout << static_cast<int>(param) << endl; }

Can I just add the declaration to the header that foo is declared in and defince bar<char> in the implementation file foo is implemented in?


The reason that I'm asking is that locally I'm seeing it work both ways. I think the difference is: Specialized template methods that I'm only using internally to the defining class can be defined in the implementation. Specialized template methods I'm using externally seem to need to be defined in the header. I haven't been able to find anything conclusive on this though so I thought I'd ask.

1 Answers

The one thing thy shan't do is to declare specialization in .cpp file. There are good reasons for it, discussed in Explicit specialization of member function template in source file

However, if you put declaration in header file (as I understand you intend to do), the specialization can go into .cpp file, as long as it is called from there at least once - and than you can have calls to the specialization outside of the translation units.

The reason for at least one requirement is that compiler is only going to instantiate the template if it is called and the definition is available, but once template is instantiated, it can be used from any translation units.

Related