vendredi 22 juillet 2022

Provide definition of constructor template outside a class template [duplicate]

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)

  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.

Aucun commentaire:

Enregistrer un commentaire