![]() |
VOOZH | about |
Tag dispatch is a programming technique by which we can call different overloads of a function based on the dummy argument passed to it. It is especially useful when we want to perform different action using functions with similar argument and return type. In this article, we will learn about the tag dispatch and its working in C++.
In normal operator overloading, the functions at least needs to have a different number of arguments or different type of argument or different return type. Otherwise, the compiler won't be able to distinguish between them.
Tag dispatch is a technique used in C++ to select different implementations of a function or algorithm based on a dummy argument passed as compile-time information. It allows you to achieve function overloading with the same type of arguments present in every function.
The dummy argument passed at the function call is called a tag. We generally use an empty struct as a tag.
struct t{};
When we pass this struct to the function along with other arguments, the compiler automatically select the implementation with the given tag as argument.
Calling function of tag t1 Function with tag t2
Following are some main applications of tag dispatch in C++: