Automatic creation of constructor, based on parent class' constructor (C++)

c++, constructor, templates

Solution

No this is currently not possible in C++. It's called "perfect forwarding", and is allowed in C++0x. You can simulate it by producing overloads of your constructor up to a fixed maximum (like, say, 8 parameters), both for const and non-const references. This is still not perfect (temporaries won't be forwarded as temporaries), but usually works in practice:

template<typename T1>
B(T1 &a1):A(a1) { 
  // do some more stuff
}

template<typename T1>
B(T1 const &a1):A(a1) { 
  // do some more stuff
}

template<typename T1, typename T2>
B(T1 &a1, T2 &a2):A(a1, a2) { 
  // do some more stuff
}

template<typename T1, typename T2>
B(T1 const &a1, T2 const &a2):A(a1, a2) { 
  // do some more stuff
}

template<typename T1, typename T2>
B(T1 const &a1, T2 &a2):A(a1, a2) { 
  // do some more stuff
}

template<typename T1, typename T2>
B(T1 &a1, T2 const &a2):A(a1, a2) { 
  // do some more stuff
}

// ...

The generation can be automated using Boost.Preprocessor or some script, but it's not exactly nice, since the amount of overloads grows fast.

So in short - no write your constructors yourself until C++0x is available, which supports both perfect forwarding for any function, and special constructor forwarding (`"using A::A;"`).

Problem

Here is a code I would like to get to work: ``` template <class A> class B : public A { public: // for a given constructor in A, create constructor with identical parameters, // call constructor of parent class and do some more stuff B(...) : A(...) { // do some more stuff } }; ``` Is it possible to achieve behavior described by above example?

Original source

Related problems