I want to have a method that can be called only with lvalues so I've done the following:
template <typename T>
MyClass& cache(T&) {}
template <typename T>
MyClass& cache(const T&&) = delete;
And this works fine - I can even pass C string literals since they are also lvalues.
The reason I need lvalues is because I'm caching pointers to the passed objects - and that means they cannot be temporaries.
The following code works:
MyClass a;
a.cache("string literal");
int temp = 6;
a.cache(temp);
And the following code (as desired) does not work:
int getInt(); // fwd decl
a.cache(getInt());
But I also want to be able to pass other literals - but they all seem to be rvalues...
The following code does not work (but I wish it could):
MyClass a;
a.cache(6);
Is there a way to distinguish between such literals and non-literal rvalues?
Is there a way to easily turn such literals into lvalues? I found this answer on Stack Overflow mentioning something like unless you write 1L
but even if I give an L
suffix to a literal it is still a temporary.
Even a macro is OK - something like this: a.cache(TURN_TO_LVALUE(6));
Aucun commentaire:
Enregistrer un commentaire