Automatically creating a constructor based on the constructor of the parent class (C ++)

Here is the 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 the behavior described by the above example?

+3
source share
3 answers

In C ++, this is not possible. It is called "perfect forwarding" and is allowed in C ++ 0x. You can simulate it by creating overloads of your constructor to a fixed maximum (for example, 8 parameters), for both constant and non-constant links. This is still not ideal (temporary files will not be redirected as temporary), but usually work 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
}

// ...

Boost.Preprocessor script, , .

, , ++ 0x, , ("using A::A;").

+8

STL , , :

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

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

  // ...
};

:

g++ -std = ++ 0x -c code.cpp

+2

++ 0x Inheriting

on http://www.devx.com .

This is probably a description of a future solution to your problem.

+1
source

Source: https://habr.com/ru/post/1718035/


All Articles