模板类的通用打印功能

时间:2017-05-12 20:04:51

标签: templates visual-c++

 #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;
}`

这里我已经创建了PRINT函数,因此它将打印类的数据成员。但如果我将使用int它可以轻松打印,但如果我将使用 int * ,因为我在我的代码中,或者如果我将使用 int **行数组1  NUM(B);

我想为int,int *或int **

创建一个通用的print函数

1 个答案:

答案 0 :(得分:0)

您可以使用一些模板魔法取消引用指针。当然,你只能以这种方式打印第一个元素。在让数组衰减到指针后,无法知道长度。

#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

相关问题