ritter
ritter

Reputation: 7699

Overloaded constructor of template member not called

Ok, this one drives me mad. I can't figure out why a constructor is not called.

Here is the code:

template<class T>
struct JV {
  JV() {}
  JV(const T& t0) : F{{t0}} {
    std::cout << __PRETTY_FUNCTION__ << "\n";
  }
  std::array<T,1> F;
};


template<class T>
struct RS : public JV<T>
{
  RS(): JV<T>() {}

  RS(const T& rhs) : JV<T>(rhs) {
    std::cout << __PRETTY_FUNCTION__ << "\n";
  }
};



template<class T>
struct PS : public JV<T>
{
  PS(): JV<T>() {}

  PS(const T& rhs) : JV<T>(rhs) {
    std::cout << __PRETTY_FUNCTION__ << "\n";
  }
};


template<class T>
struct WJ
{
  WJ() {
    std::cout << "WJ::WJ()\n";
  }
};


int main() {
  PS<RS<WJ<float> > > wj;
  std::cout << "go for it\n";
  PS<PS<RS<WJ<float> > > > copy(wj);
}

If compiled with GCC g++ 4.7.2 -std=c++0x and run the output is:

WJ::WJ()
go for it
JV<T>::JV(const T&) [with T = PS<RS<WJ<float> > >]
PS<T>::PS(const T1&) [with T1 = PS<RS<WJ<float> > >; T = PS<RS<WJ<float> > >]

Why does JV<T>::JV(const T&) [with T = PS<RS<WJ<float> > >] not call the overloaded constructor of PS<RS<WJ<float> > >::PS<RS<WJ<float> > >(const RS<WJ<float> >&)?

Edit:

Also, it doesn't call it when restricting the overloaded constructor, see above.

Upvotes: 0

Views: 168

Answers (1)

Templated constructors are never copy constructors. The compiler is using the copy constructor to construct PS<RS<WJ<float>>> inside the std::array in JV. You are not tracking in your code copy construcotrs so no other message is shown after JV<T>::JV(T const&).

Upvotes: 3

Related Questions