I have the following bit of code that uses the "deduce this" pattern:
#include <print>
struct base
{
template <typename Self>
void invoke(this Self& self)
{
self.foo();
}
};
struct derived : base
{
void foo() { std::println("derived::foo()"); }
};
int main()
{
derived d;
d.invoke(); // ok
base& bref = d;
bref.invoke(); // error
base* bptr = &d;
bptr->invoke(); // error
return 0;
}
The compiler generates the following error:
<source>:8:12: error: no member named 'foo' in 'base'
8 | self.foo();
| ~~~~ ^
<source>:23:6: note: in instantiation of function template specialization 'base::invoke<base>' requested here
23 | bref.invoke(); // error
| ^
Given this error, is the base type used for the "deduced this" not the same kind of type one would expect when using normal runtime polymorphism?
Given the error generated by the compiler, is the base type used for the deduce this not the same kind of type one would expect when using normal runtime polymorphism?
Deduced this
is compile-time polymorphism, just like templates in general.
For any given use of invoke
in the program, the type of Self
will be deduced (at compile-time) from the object expression of the call, the function foo
will be looked up in that type and only that function can be called. There is no runtime polymorphism involved. For runtime polymorphism you need virtual
functions.
When you call invoke
on an expression of type base
rather than derived
, then Self
and the type of self
in invoke
will also be base
. Looking up foo
in base
will not find anything, because you never declared a foo
function in it.
For runtime polymorphism you need to declare foo
as virtual
in base
and then it will work as you seem to expect regardless of whether invoke
is called on a base or derived type. However, in that case the function doesn't need to use deduced-this
at all. A normal non-static member function will do just fine, as would calling foo
directly, instead of going through invoke
.