2017-05-12 49 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