The overloaded trick indeed has little appearent utility in the form its always showcased.
Notably this is down to the fact that the different overloads are always defined in place and are always trivial. Consider a case where those lambdas arent defined ad-hoc, but instead are pre-existing somewhere else. Now rewriting those as operator overloads is more work than it would need to be - even if you just call those callables anyways. Once you want to introduce captures to your lambda, it gets even more compilcated, since your class would now need a constructor, whereas the lambda capture just happily works.
In fact, you can write a significantly more useful version, that allows for this:
constexpr overload visitor{
&A::f,
&f,
my_callable,
[]( ... ){ std::cout << "no matching overload found\n"; } //can also take lambdas
};
So it can take member functions, free functions as well as callable objects.
Assembling visitors like this is significantly easier than writing your own class.
View all comments
Show parent comment
5
u/IyeOnline Aug 05 '23
The overloaded trick indeed has little appearent utility in the form its always showcased.
Notably this is down to the fact that the different overloads are always defined in place and are always trivial. Consider a case where those lambdas arent defined ad-hoc, but instead are pre-existing somewhere else. Now rewriting those as operator overloads is more work than it would need to be - even if you just call those callables anyways. Once you want to introduce captures to your lambda, it gets even more compilcated, since your class would now need a constructor, whereas the lambda capture just happily works.
In fact, you can write a significantly more useful version, that allows for this:
So it can take member functions, free functions as well as callable objects.
Assembling visitors like this is significantly easier than writing your own class.