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)
- How can I correctly define this constructor outside the class.
- Does such a pattern (where class template parameters differ from constructor template parameters) serve any practical purpose? An example would be very helpful.
>Solution :
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: https://quuxplusone.github.io/blog/2019/03/18/what-is-type-erasure/ (search for "templated constructor").
Or this 10 minutes clip that demonstrates it: https://www.youtube.com/watch?v=ZPk8HuyrKXU.