Suppose I have
class A final {
int& ir;
public:
A(int& x) : ir(x) { }
void set(int y) { ir = y; } // non-const method!
int get() const { return ir; }
};
and
const int i;
Obviously I can't have
A a(i);
since that would breaks constness. But I also cannot have
const A a(i);
despite the fact that this will not break constness de-facto. C++ doesn't support "const-only" ctors, e.g. in this case one which would take a const int&
. Is there a way to get const A a
wrapping a reference to i
- other than
A a(const_cast<int &>(i))
?
a.ir
. I would say that's pretty unsafe. – Masoreticclass A { variant<int&, int const&> v; A(const int&a):a(a) { } A(int &a):a(a) { } };
. not sure whether this works as-is, but could be a start. Then visita.v
with a[](auto &&a){}
– Masoreticconst A
, you can settle forA<const_>
orA<>
. And modifyir
adequately depending on the template parameter. – Masoreticiterator
s andconst_iterator
s. There are workarounds, but no language feature to solve that problem. – Barberconst A
with aconst int&
, factory or no. – DromousA
, use whatever mutators are needed to fully configure it, then give you it as aconst
(be it via copying/moving, or reference, or whatever). I thought that was fairly typical usage of factories. – Vicennialconst int &
.... – Dromous