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


Tags: , ,

Comments:

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Copyright © 2009-2012 Joys of Programming All rights reserved.
Desk Mess Mirrored v1.8.1 theme from BuyNowShop.com.