类方法的结果类型?

时间:2012-12-24 05:09:23

标签: c++ templates c++11 typetraits result-of

考虑以下示例:

#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 个答案:

答案 0 :(得分:1)

最简单的方法是使用trailing-return-type,它允许你访问函数参数,以及decltype,它允许你获取表达式的类型。

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

答案 1 :(得分:0)

您只需要使用语法为auto foo(...) -> T的新式函数定义。 Look here