自动创建构造函数,基于父类的构造函数(C ++) [英] Automatic creation of constructor, based on parent class' constructor (C++)

查看:191
本文介绍了自动创建构造函数,基于父类的构造函数(C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是我想要工作的代码:

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?

推荐答案

目前不可能在C ++中实现。它被称为完美转发,并允许在C ++ 0x。你可以通过产生你的构造函数的重载到一个固定的最大值(比如说,8个参数),无论是对于const和非const引用,都可以模拟它。这仍然不完美(临时不会作为临时性转发),但通常在实践中工作:

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
}

// ...

代码可以使用Boost.Preprocessor或一些脚本自动化, ,因为重载量增长很快。

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

简而言之,不要自己写你的构造函数,直到C ++ 0x可用,它支持 >完美转发任何函数,以及特殊构造函数转发(使用A :: A;)。

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

这篇关于自动创建构造函数,基于父类的构造函数(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆