【发布时间】:2012-01-26 15:16:29
【问题描述】:
如何允许非常量引用在包装模板复制构造函数中转换为 const 引用?请注意,我的复制构造函数是一个逻辑移动构造函数(C++11 之前的版本)——init 成员跟踪哪个包装器当前有效。
template<typename T>
class wrap
{
T & object;
bool init;
public:
wrap( T& object ) : object(object), init( true ) { }
//attempt which fails since "init" is private in other type
template<typename O>
wrap( wrap<O> const & o )
: object( o.object )
, init( true )
{
const_cast<wrap<O>&>(o).init = false;
}
};
如果其他类型完全相同,这将正常工作,因为访问规则允许访问私有 init 变量。基本上,以下应该有效:
//adding const
wrap<Type> a( get() );
wrap<Type const> b = a;
//base type would also be nice
wrap<BaseType> c = a;
【问题讨论】:
-
“如果另一种类型完全相同,这可以正常工作” - 实际上,它没有。这将使用隐式复制构造函数,而不是模板,因此两者都将以
init结束。