Consider the following class template with a constructor template:
template <class T>
class C{
public:
T val_;
std::string str_;
template <typename S>
C(const S& str);
// C(const S& str) : str_(str) {}; // Valid definition of constructor within class body
void print(){std::cout << str_;}
};
I'm, however, trying to define the constructor outside of the class, but I can't seem to figure out a way to account for the type S
.
template <typename T, typename S> // incorrect as too many parameters
C<T>::C(const S& str) : str_(str) {};
Alternatively, I tried
template <typename T>
C<T>::C(const std::string& str) : str_(str) {};
which also does not work (and probably defeats the purpose of S
)
The correct syntax is:
template <class T>
template <class S>
C<T>::C(const S& str)
{
// ...
}
Regarding your second question:
One example of using this pattern (of templating a ctor) is the way to achieve type-erasure in C++ using templates.
This article has some examples: What is type erasure - Arthur O'Dwyer (search for "templated constructor").
Or this 10 minutes clip that demonstrates it: Type Erasure (YouTube).