C++ – Printing type and value of a Element in a Template
Posted by Joys of Programming on in C/C++
When you work with templates, you would like to print the type and value of an element of the template. This program shows how to print these values. typeid returns the type and the name function returns human readable format for the type like i for int, f for float
#include <iostream>
#include <typeinfo>
using namespace std;
/*Using template to make a generic stack class*/
template <typename T> class DataType {
public:
/*Data element*/
T data;
/*Printing the value of the template data*/
static void print_value(T value) {
cout << value;
}
/*Printing the type of the template*/
static void print_type(T value) {
cout << typeid(value).name();
}
};
int main() {
/*Integer data type*/
DataType<int> dint;
dint.data = 2;
cout << "Type: ";
DataType<int>::print_type(dint.data);
cout << " Value: ";
DataType<int>::print_value(dint.data);
cout <<"\n";
/*float data type*/
DataType<float> dfloat;
dfloat.data = 3.5;
cout << "Type: ";
DataType<float>::print_type(dfloat.data);
cout << " Value: ";
DataType<float>::print_value(dfloat.data);
cout <<"\n";
}
The output of the program is something like this
Type: i Value: 2 Type: f Value: 3.5
Comments: