我有结构,其中包含参考
template <class T> struct RefContainer { RefContainer(T& t) : _r(t) {} T& getRef() { return _r; } private: T& _r; };现在,另一个不可变的对象在其自身内部使用此结构,并在其中包含此对象:
RefContainer<char> _c;当我使用那个不可变对象用点转换自己时,我得到一个const引用。 因为我在不可变对象编译器中调用了RefContainer对象的getRef,所以我违反了const的正确性。
RefContainer本身必须保持非const左值引用,但我喜欢链接不可变对象的调用以创建新的类似:
ImmubableObject obj; auto newObj = obj.copyWithSomeAttributes().modifyWithThisString("str"); // I'm on C++11 btw, so I can use everything C++11 has to offer我如何以“正确”的方式解决这个问题(可能避免丑陋的const演员)?
I have structure that contains reference in it
template <class T> struct RefContainer { RefContainer(T& t) : _r(t) {} T& getRef() { return _r; } private: T& _r; };Now, another object, which is immutable uses this structure inside itself and has this object in it like so:
RefContainer<char> _c;When I use that immutable object to transform itself with a dot I get a const reference. Since I call getRef of RefContainer object inside the immutable objects compiler says I violate const correctness.
The RefContainer itself has to hold non-const lvalue reference but I'd love to chain calls on immutable object to create new ones like so:
ImmubableObject obj; auto newObj = obj.copyWithSomeAttributes().modifyWithThisString("str"); // I'm on C++11 btw, so I can use everything C++11 has to offerHow do I work this out the "right" way (possibly avoiding ugly const casts) ?
最满意答案
你应该尝试这样的事情:
template <class T> struct RefContainer { RefContainer(T& t) : _r(t) {} T& getRef() const { // ^^^^^ return _r; } private: T& _r; };这样,无论RefContainer实例是否为const对象, T& reference都可以用作非const。
You should try something like this:
template <class T> struct RefContainer { RefContainer(T& t) : _r(t) {} T& getRef() const { // ^^^^^ return _r; } private: T& _r; };This way, the T& reference can be used as non const, regardless the RefContainer instance is a const object or not.
更多推荐
发布评论