---
# System prepended metadata

title: C++ indirect callback

---

C++ indirect callback
===

main.cpp:
```cpp=
#include <future>
#include <thread>
#include <iostream>

int main()
{
    auto retry = [](const std::function<int()> &callback,
                    const size_t &retry_count,
                    const std::chrono::seconds &retry_delay)
        -> int
    {
        for (size_t i = 0; i < retry_count; i++)
        {
            int result;
            auto worker = std::async(std::launch::async,
                                     [&result, &callback]()
                                     { result = callback(); });
            if (worker.wait_for(retry_delay) == std::future_status::ready)
                return result;
        }

        return 0;
    };

    auto callback = []() -> int
    {
        std::this_thread::sleep_for(std::chrono::seconds(10));
        return 1;
    };

    auto worker = std::async(std::launch::async,
                             retry, callback, 3, std::chrono::seconds(1));

    if (worker.wait_for(std::chrono::seconds(5)) == std::future_status::ready)
        std::cout << "Result: " << worker.get() << std::endl;
    else
        std::cout << "Timeout" << std::endl;

#ifdef SLOW
    return 0;
#elif defined(FAST)
    exit(0);
#else
    return 0;
#endif
}
```

Makefile:
```Makefile=
SRC = $(wildcard *.cpp)
CXX = g++
CXXFLAGS = -Wall -Wextra -Werror -std=c++17 -pedantic

.PHONY: all clean fast slow
all: slow fast

# With defined macro "FAST"
fast: $(SRC)
	$(CXX) $(CXXFLAGS) -DFAST $(SRC) -o $@

slow: $(SRC)
	$(CXX) $(CXXFLAGS) -DSLOW $(SRC) -o $@

clean:
	rm -f fast slow
```

What's the output? Cost time? and Why?