Implementing a C++ Executor with Template Specialization
In this post, we’ll implement an Executor that accepts a function of various types and executes it according to different execution policies. The function can be synchronous, asynchronous (returning a std::future
), or even a coroutine. We’ll use template specialization to handle the differences in execution for each type.
Usage Example
int fn() { return 10; }
std::future<int> fnAsync() {
return std::async(std::launch::deferred, [](){ return 100; });
}
// Synchronous execution
Executor<int()> a_executor(fn);
std::cout << a_executor.execute() << std::endl;
// Asynchronous execution
Executor<std::future<int>()> a_executorAsync(fnAsync);
std::cout << a_executorAsync.execute() << std::endl;
Template Specialization
To implement the Executor, we need to use template specialization. This technique allows us to provide an explicit definition for a template based on certain arguments. It’s commonly used in C++ for type traits and conditional compilation.
We’ll determine whether the passed function is synchronous or asynchronous using type traits. The primary template will handle synchronous functions, while a specialized template will handle functions returning std::future
.
// Primary template
template…