Search code examples
c++boostboost-fusion

How to figure out the return type of a vector of nviews


I have the following problem:

template <int N, typename T>
/*what is the return type*/ nviewgetter( T const& t )
{

    typename T::const_iterator it(t.begin());

    typedef BOOST_TYPEOF_TPL(*it) etype;
    typedef typename boost::fusion::result_of::as_nview<etype, N>::type netype;
    std::vector<netype> r;

    while(it!=t.end()){
        r.push_back( boost::fusion::as_nview<N>(*it) );
        it++;
    }

    //return r;
}

What is expected is that T is a sequence of Forward Sequences (e.g. boost::fusion::vector) and I want to get a view of the N-th element in each element of T . However, I do not know from beforehand the type of boost::fusion::vector , e.g. boost::fusion::vector<int, double> or boost::fusion::vector<int, double, std::string> . In the code I can figure out the correct type but I cannot figure out this in the function declaration.

Thanks !

Any suggestions for code improvement are also welcome. :)


Solution

  • If you don't want to write the full type out, you could move the type definitions into a separate template, so that they are available when you declare the function template; something like:

    template <int N, typename T>
    struct nviewgetter_traits
    {
        typedef BOOST_TYPEOF_TPL(typename T::value_type) etype;
        typedef typename boost::fusion::result_of::as_nview<etype, N>::type netype;
        typedef std::vector<netype> result_type;
    
        // Or combine it into a single monstrosity if you prefer:
        // typedef std::vector<
        //    typename boost::fusion::result_of::as_nview<
        //        BOOST_TYPEOF_TPL(typename T::value_type), N
        //    >::type> result_type;
    };
    
    template <int N, typename T>
    typename nviewgetter_traits<N,T>::result_type nviewgetter(T const & t)
    {
        typename nviewgetter_traits<N,T>::result_type r;
        for (auto it = t.begin(); it != t.end(); ++it) {
            r.push_back( boost::fusion::as_nview<N>(*it) );
        }
        return r;
    };