简体   繁体   中英

Copying “constness” of an argument of a function to its return type in C++

I have a function that takes a set and returns an element of the set. The function does not modify the set or any of its elements. So I want to express it by taking const reference of the set as an argument. The signature of the funciton is like this:

const AType& find(const set<AType>& s, ...);

But in some cases, the caller of the function may want to modify the element

set<AType> s;
AType& a = find(s, ...);
a.bar(); //non-const method

To do this, the find funtion need to take a non-const reference to the set and return non-const reference. I can overload the function so to have two versions of it. One is the const version and the other is non-const version. However, it feels like a meaningless duplication of the same implementation. Can I express a function that does not mutate a container taken as an argument and returns const reference to an element of the container if it is a const container and non-const reference if it is a non-const container in C++?

---- EDIT;

Ok I know the mutation problem of the set pointed in the replies. That's not the point of the question. Let's assume that the ordering of AType is not affected by the bar call or the container type is any other like a vector.

In general you would implement this by writing two functions:

const S& func( const R<S>& arg, ...);
S& func( R<S>& arg, ... );

There's no simpler option.

std::set needs special care though. Any in-place modifications to an element of the set must preserve the sort order, otherwise it causes undefined behaviour. For this reason, set::find returns a const iterator.

Your proposed interface would make it easy for callers to accidentally cause undefined behaviour. In this particular case you might be better offering a more controlled interface for in-place updating of the set items.

One option is to only have the const version, but make members of AType be mutable if they do not affect the sort order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM