C++ template specialization
Implementation of Executor
We need a executor which takes a function of different types and executes the function using different execution policy. The function prototype can be passed to the executor. The function can be any of any type such as a synchronous function, a async function that returns future or a coroutine. The execution of the function is different for each type of function. Let us see how can we implement the executor.
Usage
int fn() { return 10; }
std::future<int> fnAsync() { return std::async(std::launch::deferred, [](){ return 100; }); }
Executor<int()> a_executor(fn);
std::cout << a_executor.execute() << std::endl;
Executor<std::future<int>()> a_executorAsync(fnAsync);
std::cout << a_executorAsync.execute() << std::endl;
Template Specialization
If we want to implement the executor during compile time, we need to know template specialization. In template specialization, there is a primary template and specialized template. The template that is being specialized is called the primary template. You can provide an explicit specialized definition for a given set of template arguments, therefore overwriting the implicit code the compiler would generate instead. This is the technique that powers features such as type traits and conditional compilation.
We need to identify whether the passed function prototype is sync version or async version. We can use type traits to implement this…