vendredi 23 décembre 2016

Avoiding duplication when defining specialised template class constructors

Suppose I have a template class:

template<typename T>
class Widget {
public:
    Widget(const std::string& name, int i) : t_(name),  cf_(name), ci_(i) {}
private:
    T t_;
    const Foo cf_;
    const int ci_;
}

And suppose, in this context, T will only be Foo or int. Anything other than Widget<Foo> and Widget<int> is nonsense in this context.

The constructor declared above works fine for Widget<Foo>. Is there a way I can define a specialised constructor for Widget<int>, which assigns to t_ differently, but without copy-pasting the initialisation of cf_ and ci_?

Something similar in spirit to the call to Base(a) in Derived::Derived(int a, int b) : Base(a), b_(b) {} perhaps?

Aucun commentaire:

Enregistrer un commentaire