1

I want to create a function to display a variable's value by using a pointer, but I attempted to create only one function to display any type of value. I had to use template but I have some issues with displaying strings or chars. Just for solving it, I need a getType() function (like in Java)

     #include <iostream>
     using namespace std;

     template <typename T> 
     void displayByPtr(T *ptr){


           if( // If ptr's data type is char // ){
    
               T *holder = ptr;
               cout << "\nDisplayed char/string by pointer: ";
               while((*holder) != '\0'){
                   cout << (*holder);
                   holder++;
           }
           cout << "\n";
           } else {
             cout << "\nDisplayed value by pointer :" << (*ptr) << "\n"; 
           }

     }



    int main(){


         char decision = 'Y';   
         while(decision == 'Y'){
              cout << "Enter a type \n Press 1 for integer,\n Press 2 for double, \n";
              cout << " Press 3 for float, \n Press 4 for character/string, \n --> ";
              int type = 0;
              cin >> type;
              switch(type){
                   
                             .
                             .
                             .
                  case 4:
                       char inputCh[100];
                       char *ptr4;
                       cout << "Enter char value: ";
                       cin >> inputCh;
                       ptr4 = inputCh;
                       displayByPtr<char>(ptr4);
                       cout << "\n Would you like to continue ? ";
                       cin >> decision;
                       break;

I actually tried it with typeid(variable).name() in "if( // If ptr's data type is char // )" just for once, and it did not work out. Im trying to do some research for that function's syntax, but I would like to hear if there's an another way.

Ryuulan
  • 61
  • 4

1 Answers1

4

You can use template specialization.

     template <typename T> // general version
     void displayByPtr(T *ptr){

           cout << "\nDisplayed value by pointer :" << (*ptr) << "\n"; 

     }

     template <> // specialized to char
     void displayByPtr(char *ptr){

           char *holder = ptr;
           cout << "\nDisplayed char/string by pointer: ";
           while((*holder) != '\0'){
               cout << (*holder);
               holder++;
           }
           cout << "\n";

     }
MikeCAT
  • 73,922
  • 11
  • 45
  • 70