views:

396

answers:

3

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?

+7  A: 

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;").

Johannes Schaub - litb
+1, looking forward to this feature in C++0x
GRB
Please read my answer.Is this what you meant by "using A::A" ?Or is it something different?
Łukasz Lew
+2  A: 

I've dig through STL and based on what I found there, I settled on this code:

template <class Data>
class Node : public Data {
public:

  template<typename... _Args>
  Node (_Args&&... __args) : Data (std::forward<_Args>(__args)...) {
  }

  // ...
};

It works with a command:

g++ --std=c++x00 -c code.cpp

Łukasz Lew
It would help to mention what version of g++ you used.
Zan Lynx
g++-4.4 Avaliable in current Ubuntu in gcc-snapshot package.
Łukasz Lew
+1  A: 

Have a look at the lately released article

Use C++0x's Inheriting Constructors to Reduce Boilerplate Code in Class Hierarchies

on http://www.devx.com.

It probably describes a future solution for your problem.

RED SOFT ADAIR