I want to be able to supply functions which take an existing object of a given type by const reference.
i.e. I want by-const-ref-but-no-temporaries-created. [edited this phrase to clarify it!]
I can't think of any way to express that in C++ directly:
1 void fn(const T & t)
will create a temporary T
from an S
if a (non-explicit) T(S)
exists.
2 void fn(T & t)
will only allow a non-const t
as an argument (I need this to work for const t
's as well).
3 void fn(T && t)
requires a non-const rvalue
.
4 void fn(const T && t)
requires a const rvalue
Is there any way to do this - accept any argument by reference, const, without allowing a temp to be created?
Failed thoughts:
Supplying #2 and #4 without supply the other two, and now we have an unambiguous fn
that takes a reference to any existing T
(but won't silently generate a temporary)?
Nope, that isn't adequate either, because I need to also be able to bind to a const T &
- Where the target object is itself been passed in by const reference to our caller...
I guess I see no way to achieve this except in the case where I can control T
to ensure it doesn't supply an implicit T(S)
.
Am I right, or am I overlooking some solution?