代码之家  ›  专栏  ›  技术社区  ›  Geoff

如何使用boost确定给定数组类型的下标运算符的返回类型?

  •  0
  • Geoff  · 技术社区  · 16 年前

    如果要使用boost确定数组(T)的下标运算符返回的类型,需要使用什么类型签名?请注意,我将使用的数组不包含typedef,并且是第三方的。

    SomeArray<int> tmp(1);  
    int& somevalue = tmp[0]; //would equate  
    typename subscript_result<SomeArray<int> >::type somevalue = tmp[0];
    

    像这样的

    template<class T>
    struct subscript_result
    {
      typedef boost::result_of<T::operator[](typename T::difference_type)>::type type;
    };
    

    ? 我总是在类型签名中遇到运算符[]的问题:|

    谢谢您!

    1 回复  |  直到 16 年前
        1
  •  0
  •   UncleBens    16 年前

    也许你可以 BOOST_TYPEOF / BOOST_TYPEOF_TPL : http://www.boost.org/doc/libs/1_35_0/doc/html/typeof/refe.html#typeof.typo

    BOOST_TYPEOF(tmp[0]) i;
    

    decltype(tmp[0]) i;


    #include <boost/typeof/typeof.hpp>
    
    template <class T>
    struct identity
    {
        typedef T type;
    };
    
    template <class T>
    struct subscript_result
    {
    
        template <class Result, class Obj, class Arg>
        static identity<Result> get_subscript_type(Result (Obj::*)(Arg));
    
        typedef BOOST_TYPEOF(get_subscript_type(&T::operator[])) aux;
        typedef typename aux::type type;
    };
    
    #include <vector>
    #include <iostream>
    
    template <class Container>
    void foo(Container& c)
    {
        typename subscript_result<Container>::type t = c[0];
        ++t;
    }
    
    int main()
    {
        //prove that foo gets a reference to vector<int>
        std::vector<int> vec(1);
        foo(vec);
        std::cout << vec[0] << '\n';
    }
    

    您可能还需要为常量重载提出一些建议,以及为数组/指针引入专门化。