【发布时间】:2015-07-24 11:09:53
【问题描述】:
是否有可能在 C++ 中实现类似构造函数的功能,它只允许创建 const 对象?
我正在考虑使用const 和非const 方法为接口创建一个装饰器类。从const 基础对象初始化装饰器应该只能产生 const 装饰器,但从非 const 初始化应该会产生一个功能齐全的装饰器。
struct A
{
virtual void foo(); // requires non-const A
virtual void bar() const; // const method
};
class decorator : public A
{
private:
std::shared_ptr<A> p_impl;
public:
virtual void foo() { p_impl->foo(); }
virtual void bar() const { p_impl->bar(); }
// regular constructor
decorator(std::shared_ptr<A> const & p) : p_impl(p) {}
// hypothetical constructor that makes a const
decorator(std::shared_ptr<A const> const & p) const : p_impl(p) {}
};
void F(std::shared_ptr<A> const & regular_a
, std::shared_ptr<A const> const & const_a )
{
decorator regular_decorator(regular_a);
regular_decorator.foo(); // all good
regular_decorator.bar(); // all good
decorator bad_decorator(const_a); // compiler error
// trying to use a const constructor to init a non-const object
const decorator const_decorator(const_a); // all good
const_decorator.foo(); // compiler error, foo is not const
const_decorator.bar(); // all good
// I have a lot of these in code that is beyond my control
decorator bad_practice(const_cast<decorator&>(const_decorator));
bad_practice.foo(); // all good
}
我怎样才能达到类似的效果?
【问题讨论】: