2013-03-03 50 views
0

我有我的代碼一類相當於std::array<T1, N>和功能:使用[]運算符從指向std :: array <T, N>的指針獲取類型?

template <class T2> 
inline void f(T2* const myarray) 
{ 
    std::pair<double, /*SOMETHING*/> x; 
} 

假設T2*是指向我的課媲美std::array<T1, N>,我想知道我必須寫,而不是/*SOMETHING*/[]獲得T1運營商myarray

注:我不要求一個更聰明的方式來獲得從一個指針類型std::array

+0

這是可能的,你正在尋找[*模板模板參數*](http://stackoverflow.com/questions/213761/what-are-some-uses-of-template-template-parameters-in-c) 。 – 2013-03-03 01:12:07

+3

'typename T2 :: value_type'? – Pubby 2013-03-03 01:12:16

+1

如果你確定這是一個指針數組類/類型,你可以做'decltype((* myArray的)[0])' – 2013-03-03 01:12:37

回答

3

這個工作對我來說:

#include <type_traits> 
#include <array> 
#include <utility> 

template <class T2> 
inline void f(T2* const myarray) 
{ 
    std::pair<double, typename T2::value_type> x; 
    static_assert(std::is_same<decltype(x.second), int>::value, ""); 
} 

int 
main() 
{ 
    std::array<int, 2> a; 
    f(&a); 
} 

如果你的「陣列狀」類模板沒有value_type,下面還應該工作:

std::pair<double, typename std::remove_reference<decltype((*myarray)[0])>::type> x; 

但僅供參考,常量通常不會使用合格的參數,並且在C++ 11中,如果碰巧返回參數(如in),甚至會導致悲觀化:

return myarray; 

雖然在這種情況下,myarray是一個指針,在這種情況下它並不重要。

如果改爲指:

inline void f(T2 const* myarray) 

(指針const T2,代替const指針T2

那麼上述配方需要輕微的調整:

std::pair<double, typename std::remove_const< 
            typename std::remove_reference< 
             decltype((*myarray)[0]) 
            >::type 
           >::type> x; 

如果您的「陣列式」類模板確實有value_type,那麼第一個建議:

std::pair<double, typename T2::value_type> x; 

作品無論在哪裏const是。