I am creating a function like such:
void SetItem(const Key &key, const Value &value)
{
...
}
Where Key and Value are some type.
Internally, I want to store the pair like this:
std::pair<const Key &, Value>
So here is my problem:
I need to enforce that Key is actually an l-value so that it doesn’t get cleaned up when the function exits (Unsafe with r-values)
I could make the signature to the function:
void SetItem(Key &key, const Value &value)
Which would prevent the use of r-values, but it then doesn’t allow a const key to be used, which I don’t like either.
Is there a way for me to force Key to be an l-value while preserving the constness?
I am fine with creating an r-value overload to prevent it:
void SetItem(Key &&key, const Value &value)
{
[What do I put here?]
}
Thanks
With the improvements from the comments incorporated, it should look like this in a fully conformant C++11 compiler:
The private overload will catch all
Keyrvalues. Access checking isn’t done during overload resolution, as such we can put it underprivate, and so that possiblefriends also get a nice error message at compile time, we= deleteit.For compilers that don’t support explicitly deleted functions yet, you can leave it simply undefined, but that will only show up as a linker error for possible
friends. However, the general audience will get the nice “`SetItem’ is inaccessible” compiler error message. 🙂