2

Say I have a template class

template<typename T>
class Foo {
    template<typename U>
        Foo(const Foo<U> &foo) {
            ...
        }
}

Obviously, Foo<T>(const Foo<T>&) is an instance of that template member, but for some reason C++ chooses to use the implicit copy constructor instead of instantiating this copy constructor from the template.

Is there a way to force the copy constructor to be instantiated from the template?

Usually, something like

template<> template<> Foo<int>::Foo(const Foo<int>&);

would work if I want a specific instance, but I want every Foo<T> that gets instantiated to also have Foo(const Foo<T>&) be instantiated as well.

How can I achieve this?

Without actually writing out Foo::Foo(const Foo&); separately, using the same exact code, of course. That would be silly.

  • You mean, the copy ctor is not executed (not even generated, that is) although you do copy-construct objects, like `Fooj; Foo i{j}`? – Peter - Reinstate Monica Mar 26 '14 at 02:59
  • Well the implicit one is generated, which just copies all the members directly. –  Mar 26 '14 at 03:04
  • This will probably solve your problem: http://stackoverflow.com/questions/15264252/how-delegate-from-copy-constructor-to-universal-copy-constructor-template – Mikael Persson Mar 26 '14 at 05:59
  • That does solve my problem (in fact, it's what I already did). I'm just asking if there's a specific way to force an instantiation. –  Mar 26 '14 at 07:15

0 Answers0