【发布时间】:2014-09-26 07:13:51
【问题描述】:
假设我有以下使用经典继承的简单类层次结构:
struct A_classic {};
struct B_classic : A_classic {};
我想实现一个从A_classic 到B_classic 的转换运算符。为了尽可能多地重用代码,我这样做了
A_classic a; // Given as input argument
B_classic b;
static_cast<A_classic&>(b) = a; // Copy A_classic's members
// Now set up B_classic's members
问题是我实际上使用 CRTP 进行继承:
template<class Derived> struct A_crtp_base {};
struct A_crtp : A_crtp_base<A_crtp> {};
template<class Derived> struct B_crtp_base : A_crtp_base<B_crtp_base<Derived>> {};
struct B_crtp : B_crtp_base<B_crtp> {};
上述技巧不再有效,因为A_crtp、B_crtp 的“通用”基类分别为A_crtp_base<A_crtp> 和A_crtp_base<B_crtp>。
A_crtp a;
B_crtp b;
static_cast<A_crtp_base<???>&>(b) = a;
// No matter what I put here, either the cast or the assignment will fail
一个明显的解决方案是将A_crtp_base的复制构造函数模板化:
template<class Derived>
struct A_crt_base {
template<class OtherDerived>
A_crtp_base(const A_crtp_base<OtherDerived>& other);
}
但是我必须编写自己的复制构造函数,我想避免这种情况。
有什么建议可以减少这里的编码量吗?
【问题讨论】:
标签: c++ inheritance crtp