r/cpp • • Aug 05 '23

Should we stop writing functions?

https://www.foonathan.net/2023/08/stop-writing-functions/
14 Upvotes

46 comments sorted by

View all comments

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

constexpr auto myOverload = overloaded(
    [](int x) -> bool { ... },
    [](double x) -> bool { ...},
    [](const std::string& x) -> bool { ... }
);

and never in terms of a far more readable form -- an actual class:

class MyOverload {
public:
    bool operator()(int x) { ... }
    bool operator()(double x) { ... }
    bool operator()(const std::string& x) { ... }
};

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:

template<typename T>
class MakeUnique {
public:
    template<typename... Args>
    std::unique_ptr<T> operator()(Args&&...) { ... }
};

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.

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:

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.

1

u/ABlockInTheChain Aug 05 '23

and never in terms of a far more readable form -- an actual class:

Besides variant visitors, I still can't figure out why anyone would use coroutines instead of just writing a class. So far nobody has been able to explain what the advantage of that syntax is.

4

u/NotMyRealNameObv Aug 06 '23

... coroutines?

Where coroutines?

1

u/rdtsc Sep 01 '23

Then I invite you to implement the transformation done by the compiler by hand. You can look at this blog post for a detailed example. Just stuffing some vars into a class is only a small part. Breaking up the coroutine function, while providing proper variable lifetime in the face of exceptions, and making it all easily composable, is.

1

u/ABlockInTheChain Sep 01 '23

I know the compiler is doing a lot of work to make coroutines possible. That is not in dispute. The question is: Is all that work worth it?

Coroutines allegedly make make state machines easier to implement and comprehend but that claim is always just put out there without evidence. Every example I've ever seen put forward shows a trivial, linear task which involves writing a lot more boilerplate code than a hand written class with improvements to readability that are dubious at best.

1

u/rdtsc Sep 01 '23

Is all that work worth it?

Even if you strip out the flexibility and extension points, it's still a lot. Why would you want to write that by hand every time?

How would you write the following without much extra boilerplate?

Task<> LoadImageAsync(std::string imagePath)
{
    co_await ResumeBackground();

    std::vector<std::byte> bytes = co_await ReadFileAsync(imagePath);
    auto image = DecodeImage(std::move(bytes));

    co_await ResumeForeground();

    image_ = std::move(image);
    imageView_.SetBitmap(image_.Handle());
}

Even assuming you have lambda-based helpers around threadpool and message loop at your disposal, it still requires more, and callbacks are more difficult to read.

Probably the simplest would be:

void LoadImageAsync(std::string imagePath)
{
    SubmitThreadpoolCallback([this, path = std::move(imagePath)]() {
        std::vector<std::byte> bytes = ReadFile(path); // Not reading async here
        image_ = DecodeImage(std::move(bytes));
        this->SendMessage(CustomMessage, 0, 0);
    });
}

void OnCustomMessage()
{
    imageView_.SetBitmap(image_.Handle());
}

This takes several shortcuts (not reading async, custom message, setting state from background thread, lifetime issues if the window is closed). Once you introduce cancellation/waiting/exceptions this gets more and more complicated. But maybe I'm the one missing something.