Open In App

Tag Dis in C++

Last Updated : 23 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Tag dis 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 dis and its working in C++.

Tag Dis 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 dis 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.

Example of Tag Dis

C++
// C++ Program to show the implementation of
// tag dis
#include <bits/stdc++.h>
using namespace std;

// Creating the different tags of type empty
// struct
struct t1{};
struct t2{};

// Defining a function for type t2
void fun(int a, t1) {
    cout << "Calling function of tag t" << 
      a << endl;
}

// Defining the function with different 
// implementation for type t2
void fun(int a, t2) {
    cout << "Function with tag t" << 
      a << endl;
}

int main() {

    // Function calling with different tags
    fun(1, t1{});
    fun(2, t2{});
  	return 0;
}

Output
Calling function of tag t1
Function with tag t2

Applications of Tag Dis in C++

Following are some main applications of tag dis in C++:

  • Tag dis can be used to explicitly select the desired implementation of the overloaded function.
  • It is used to optimize functions based on iterator types such as random iterator, forward iterator, etc.
  • Type specific optimization can be done by using regular function overloading but condition specific optimizations in generic algorithms can be done using tag dis.
  • It is also used to select the features of the function to be enabled for that particular execution based on the argument types and purpose.