Reading new C++ 23 features , I came up to deducing this Instead of writing the following function signatures to handling rvalue and lvalue
void bar()&&;
void bar()&;
deduce this can be used like the following
void bar(this A &&);
I except that this A&& follow templates rules and using this I can handle both &,&& but this does not happen When I try
#include <iostream>
class A{
public:
void bar(this A &&)&&{
std::cout << "bar &&" << std::endl;
}
};
A foo(){
return A{};
}
int main() {
foo().bar();
auto a = foo();
a.bar();
}
The following error is generated
:15:4: error: rvalue reference to type 'A' cannot bind to lvalue of type 'A' 15 | a.bar(); | ^ :5:23: note: passing argument to parameter here 5 | void bar(this A &&){^
https://godbolt.org/z/7Tvqx9hb8
Using template this works as expected enter link description here
My question is if I cannot use deduce this without template what is the purpose of using deducing without template.For example
void bar(this A & ).
Since I need to define define again more than one overloading functions for handling cv,rvalue,lvalue e.t.c
The purpose is that you can write one member function template for l and r value references.
deduce this can be used like the following
void bar(this A &&);
No. Only when calling a template a type is deduced. Consider this example:
#include <iostream>
class A{
public:
template <typename Self>
void bar(this Self&& s) {
std::forward<Self>(s).foo();
}
void foo() && {
std::cout << "foo &&" << std::endl;
}
void foo() & {
std::cout << "foo &" << std::endl;
}
};
A foo(){
return A{};
}
int main() {
foo().bar();
auto a = foo();
a.bar();
}
foo &&
foo &
foo
in the example is merely to illustrate that Self
is deduced differently in the two calls. The purpose of deducing this is that you need not write two overloads and still can distinguish iniside the function whether the object is a temporary or not.