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?
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;").
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With