2017-05-12 51 views
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; 
}` 

这里我做了一个PRINT函数,所以它会打印类的数据成员。但如果我将使用int它可以很容易地打印,但如果我将使用int *,因为我已经在我的代码中,或者如果我将使用int **在行array1 num(b);模板类的通用打印功能

我想为INT,INT *或者int通用打印功能**

回答

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