jeudi 28 juillet 2016

forcing templatized constructor over compiler generated copy-constructor

Take the following,

template<class T>
struct Foo {
    Foo(){}

    // a template constructor "generalized" over related types
    template<class U>
    Foo(Foo<U> const&) {
        std::cout << 1;
    }

    // copy constructor
    Foo(Foo const&) {
        std::cout << 2;
    }
};

and its user:

void main() {
   Foo<int> f1;
   Foo<const int> f2(f1); // prints 1
   Foo<const int> f3(f2); // prints 2
}

Even without the explicit copy constructor, compiler generates one and uses that for f3(f2).

Is there a way to force the template overload? For example, can the copy-constructor be SFINAE'd out? This is in order to avoid code duplication, as, interestingly enough, there doesn't seem to be a way to use delegating constructors either (delegating from the copy constructor to the template one).

Aucun commentaire:

Enregistrer un commentaire