If you have a std::variant<int, double, std::string> it's just as obvious what's going on with std::visit(MyOverload(), variant) as it is std::visit(myOverload, variant). And if you really want, you can always slap one of these bad boys in there:
static constexpr MyOverload myOverload;
The distinction between required template parameters and deduced arguments as evidenced by std::make_unique is indeed made distinguishable as the article shows and it can indeed be nice to separate the two kinds of arguments. But that also requires C++20 and we have had other approaches since C++11 that achieve the same thing:
If you do want to separate the arguments then this achieves it. It also lets you specify the deleter in a pretty natural way by adding a second template argument to MakeUnique itself.
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.
17
u/tangerinelion Aug 05 '23
Working on a 6MLOC code base the number of times I've seen accidental use of ADL is exactly zero.
The overload trick, IMO, has no place in production code. It's a cute thing but why do we always frame it in terms of
and never in terms of a far more readable form -- an actual class:
If you have a
std::variant<int, double, std::string>it's just as obvious what's going on withstd::visit(MyOverload(), variant)as it isstd::visit(myOverload, variant). And if you really want, you can always slap one of these bad boys in there:The distinction between required template parameters and deduced arguments as evidenced by
std::make_uniqueis indeed made distinguishable as the article shows and it can indeed be nice to separate the two kinds of arguments. But that also requires C++20 and we have had other approaches since C++11 that achieve the same thing:If you do want to separate the arguments then this achieves it. It also lets you specify the deleter in a pretty natural way by adding a second template argument to
MakeUniqueitself.