gpt4 book ai didi

c++ - 装饰方法时减少样板

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:45:39 24 4
gpt4 key购买 nike

我有大量的类,用来装饰几个具体的方法。

是否有一种干净的方法来减少需要添加到每个类中的样板代码(主要是所有构造函数参数和保存它们的成员)的数量?或者,更好的是,有没有更好的方法来做到这一点?

我不能使用虚拟方法,只能使用 gcc 4.6 和 vs2010 支持的 c++11 功能的子集。

我相信 c++11 继承构造函数在这里会有所帮助,但两个编译器都不支持它们,而且我不知道有什么解决方法。

以下是这些类当前的示例:

template<class Underlying, class T1>
struct A : Base<A<Underlying, T1> >
{
typedef AImpl<decltype(declval<Underlying>().foo()), T1> impl;
A(Underlying u, T1 t1) :
u_(u),
t1_(t1)
{}

impl foo() const { return impl(u_.foo(), t1_); }
impl bar() const { return impl(u_.bar(), t1_); }

const Underlying u_;
T1 t1_;
};


template<class Underlying, class T1, class T2>
struct B : Base<B<Underlying, T1, T2> >
{
typedef BImpl<decltype(declval<Underlying>().bar()), T1, T2> impl;
B(Underlying u, T1 t1, T2 t2) :
u_(u),
t1_(t1),
t2_(t2)
{}

impl foo() const { return impl(u_.bar(), 999, t2_); }
impl bar() const { return impl(u_.foo(), t1_, t2_); }

const Underlying u_;
T1 t1_;
T2 t2;
};

最佳答案

您可以在 GCC 4.6 中使用可变参数模板。

template<class Underlying, class... T>
struct B : Base<B<Underlying, T...>>
{
typedef BImpl<decltype(declval<Underlying>().bar()), T...> impl;

template<typename V...>
B(Underlying u, V... v) :
u_(u),
t_(std::forward<V>(v)...)
{}

impl foo() const { return impl(u_.bar(), 999, std::get<1>(t_)); } // Not sure what the 999 is?
impl bar() const { return impl(u_.foo(), std::get<0>(t_), std::get<1>(t_)); }

const Underlying u_;
std::tuple<T...> t_;
};

关于c++ - 装饰方法时减少样板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8318715/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com