Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Provide definition of constructor template outside a class template

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

template <typename T>
C<T>::C(const std::string& str) : str_(str) {};

which also does not work (and probably defeats the purpose of S)

  1. How can I correctly define this constructor outside the class.
  2. 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading