I have a class with a member template function:
// writer.h
class Writer {
public:
...
template <typename T, typename V>
void addField(const std::string& name, V v)
{
// write something
}
};
And in Writer's source file, I added explicit specializations for some_type
:
// writer.cpp
template <>
void Writer::addField<some_type, int>(const std::string& name, int v)
{
// specific some_type writing logic
}
This works... sometimes. Even if I definitely make sure that I have the right types:
writer.addField<some_type>("name", static_cast<int>(some_value));
Sometimes the explicit specialization gets called, and sometimes the primary gets called. What gives?
Declaring specializations in a source file and can cause all sorts of subtle issues that are very difficult to diagnose. The compiler isn't obligated to help you in any regard here either. The standard strongly encourages you not to do this, with the help of a limerick, in [temp.expl.spec]/6-7:
It's likely that in some translation units, the specialization happened to be declared before the first use - and in some translation units it hasn't been. It's better to avoid all such issues entirely by simply declaring your specialization in your header:
You can also just declare it in the header (no longer needs to be inline), and still define it in the source.