0
 #include<iostream>
using namespace std;
template<class T>
class array1{
private:
    T a;
public:
    array1(T b){
        a = b;
    }
    friend ostream& operator<<(ostream& out,array1 b){
        out << b.a;
        return out;
    }
};
int main(){
    int* b = new int[2];
    b[0] = 5;
    b[1] = 10;
    array1<int*> num(b);
    cout << num;
    system("pause");
    return 0;
}`

Here i have made a PRINT function so it will print the data member of class. but if i will use int it can print easily but if i will use int* as i have in my code , or if i will use int ** in line array1 num(b);

I want to make a generic print function for int , int* or int**

Irtaza fayaz
  • 383
  • 4
  • 11

1 Answers1

0

You can use some template magic to dereference the pointer. Of course you can only print the first element this way. After you let the array decay to a pointer there is no way of knowing the length.

#include <iostream>
#include <type_traits>

// https://stackoverflow.com/questions/9851594
template < typename T >
struct remove_all_pointers
{
  typedef T type;
};

template < typename T >
struct remove_all_pointers < T* >
{
  typedef typename remove_all_pointers<T>::type type;
};


template < typename T >
typename std::enable_if<
  std::is_same< T, typename remove_all_pointers<T>::type >::value,
  typename remove_all_pointers<T>::type&
  >::type
dereference(T& a)
{
  return a;
}

template < typename T >
typename std::enable_if<
  !std::is_same< T, typename remove_all_pointers<T>::type >::value,
  typename remove_all_pointers<T>::type&
  >::type
dereference(T& a)
{
  return dereference(*a);
}


template<class T>
class array1
{
private:
    T a;
public:
    array1(T b){
        a = b;
    }
    friend std::ostream& operator<<(std::ostream& out,array1 b){
        out << dereference(b.a);
        return out;
    }
};


int main()
{
    int* b = new int[2];
    b[0] = 5;
    b[1] = 10;
    array1<int*> num(b);
    std::cout << num << '\n';
}

Online demo

Henri Menke
  • 10,705
  • 1
  • 24
  • 42