Reputation: 337
I know that it's possible to declare a template in the header and its definition in a source file as long as I declare in advance the parameters it will be instantiated with. My question is: will putting the explicit instantiations in the .h file create problems? It seems to work but I've always seen people putting them in the source file, not in the .h
What I have in mind is the following
.h file
class foo
{
public:
template <typename T>
void do(const T& t);
};
template<> void foo::do<int>(const int&);
template<> void foo::do<std::string>(const std::string&);
.cpp file
template <int>
void foo::do(const int& t)
{
// Do something with t
}
template <std::string>
void foo::do(const std::string& t)
{
// Do something with t
}
Upvotes: 2
Views: 1121
Reputation: 72271
These are called explicit specializations. Explicit instantiation is something else.
Putting those declarations in the header file is fine, and a very good idea. When compiling other source files, you want the compiler to know not to generate those specializations using the primary template.
Your syntax in the *.cpp file is wrong, though. The definitions should be more like the declarations:
template <>
void foo::do<int>(const int& t)
{
// Do something with t
}
Upvotes: 2