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?

Łukasz Lew
  • 48,526
  • 41
  • 139
  • 208

3 Answers3

8

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
  • 496,577
  • 130
  • 894
  • 1,212
2

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++0x -c code.cpp

Mankarse
  • 39,818
  • 11
  • 97
  • 141
Łukasz Lew
  • 48,526
  • 41
  • 139
  • 208
  • It would help to mention what version of g++ you used. – Zan Lynx Sep 22 '09 at 14:32
  • g++-4.4 Avaliable in current Ubuntu in gcc-snapshot package. – Łukasz Lew Sep 22 '09 at 14:34
  • [Those identifiers aren't meant to be used by you](http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier). You probably should have mentioned C++0x was an option for you in the question, by the way. This is the closest thing to constructor inheritance, yes. – GManNickG Nov 29 '11 at 04:27
1

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
  • 12,032
  • 10
  • 54
  • 92