2012-12-24 27 views
1

請看下面的例子:類方法的結果類型?

#include <iostream> 
#include <numeric> 
#include <array> 
#include <type_traits> 

// Array: I cannot modify this class 
template<typename T, unsigned int N> 
class Array 
{ 
    public: 
     Array() : _data() {std::iota(std::begin(_data), std::end(_data), 0);} 
     inline T& operator[](unsigned int i) {return _data[i];} 
     inline const T& operator[](unsigned int i) const {return _data[i];} 
     static constexpr unsigned int size() {return N;} 
    protected: 
     T _data[N]; 
}; 

// Test function: How to get the type returned by T::operator[](unsigned int) ? 
template<typename T> 
typename std::result_of<T::operator[](const unsigned int)>::type f(const T& x) 
{ 
    return x[0]; 
} 

// Main 
int main(int argc, char* argv[]) 
{ 
    Array<double, 5> x; 
    std::array<double, 5> y = {{0}}; 
    for (unsigned int i = 0; i < x.size(); ++i) std::cout<<x[i]<<std::endl; 
    for (unsigned int i = 0; i < y.size(); ++i) std::cout<<y[i]<<std::endl; 
    std::cout<<f(x)<<std::endl; 
    std::cout<<f(y)<<std::endl; 
    return 0; 
} 

有沒有什麼辦法讓通過T::operator[](unsigned int)返回的類型?

目前,G ++說:argument in position '1' is not a potential constant expression

+2

應該是在'decltype的線(STD :: declval ()[0])'... –

+0

尋找一個獨立的函數的結果類型的相關問題,當你不不知道其簽名,請參閱http://alfps.wordpress.com/2012/01/08/resultof-a-function-with-c11/#comments –

回答

1

最簡單的方法將使用拖尾返回類型,它允許您與decltype訪問函數的參數,同時,它可以讓你獲得一個表達式的類型。

template<typename T> 
auto f(const T& x) -> decltype(x[0]) 
{ 
    return x[0]; 
} 
0

所有你需要的是用新風格的功能defenition語法auto foo(...) -> TLook here