Const-Konstruktor
Ist es in C ++ möglich, so etwas wie einen Konstruktor zu erreichen, der nur @ erstellen darconst
Objekte?
Ich denke darüber nach, eine Decorator-Klasse für eine Schnittstelle mit @ zu erstelleconst
und nonconst
Methoden. Decorator von einem @ aus initialisierconst
as Basisobjekt @ sollte nur const-Dekoratoren erzeugen können, aber das Initialisieren von einem Nicht-const-Dekorator sollte einen voll funktionsfähigen Dekorator ergeben.
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
}
Wie kann ich einen ähnlichen Effekt erzielen?