我可以从std :: tuple获得“cons list”行为吗?

时间:2014-02-04 05:47:22

标签: c++ c++11 stdtuple

我想递归地定义一个设置std :: tuple的所有元素的函数。如果它是一个boost :: tuple,我只需查看here并复制此示例:

inline void set_to_zero(const null_type&) {};

template <class H, class T>
inline void set_to_zero(cons<H, T>& x) { x.get_head() = 0; set_to_zero(x.get_tail()); }

到目前为止,我找不到任何与std :: tuple相似的内容。有什么关系吗?

更新:好的,我需要更多地充实这个问题。

template<typename T>
struct simple_setter
{
    void set(T &target);  // somebody else's stuff, defined elsewhere
};


template<typename Tuple> class foo;

template<>
struct foo<boost::tuple<>>
{
    foo()  {}
    void set(boost::tuple<> &target)  {}
};

template<typename E, typename... Es>
struct foo<boost::tuple<E, Es...>>
{
    explicit foo(const simple_setter<E> &head_setter, const simple_setter<Es> & ... other_setters) :
         _head(head_setter),
         _tail(other_setters)
    {}

    void set(boost::tuple<E, Es...> &target) {
        _head.set(target.get_head()),
        _tail.set(target.get_tail())
    }

    // more methods to do other things

    const simple_setter<E> &_head;
    const foo<boost::tuple<Es ...>> _tail;
};

我正在编写包含元组的类foo,以便做一堆事情,其中​​一个就是设置所有元素。我希望保留foo的这种递归定义,但要从boost :: tuples切换到std :: tuples。

1 个答案:

答案 0 :(得分:0)

递归可以这样实现

template < typename _Tuple >
inline void set_to_zero(_Tuple& tuple, std::integral_constant<size_t, 0>)
{ 
}

template < typename _Tuple, size_t N >
inline void set_to_zero(_Tuple& tuple, std::integral_constant<size_t, N>)
{
    set_to_zero(tuple, std::integral_constant<size_t, N - 1>());
//  action(std::get<N - 1>(tuple));
}

template < typename _Tuple >
inline void set_to_zero(_Tuple& tuple)
{ 
    set_to_zero(tuple, std::integral_constant<size_t, std::tuple_size<_Tuple>::value>());
}

或更一般的表格

template < typename _Tuple, typename _Func >
inline void for_each(_Tuple& tuple, _Func func_, std::integral_constant<size_t, 0>)
{
}

template < typename _Tuple, typename _Func, size_t N >
inline void for_each(_Tuple& tuple, _Func func_, std::integral_constant<size_t, N>)
{
    for_each(tuple, func_, std::integral_constant<size_t, N - 1>());
    func_(std::get<N - 1>(tuple));
}

template < typename _Tuple, typename _Functor >
inline void for_each(_Tuple& tuple, _Functor func_)
{
    for_each(tuple, func_, std::integral_constant<size_t, std::tuple_size<_Tuple>::value>()); 
}

广义形式的使用样本

    struct DoSomething
    {
        void operator()(int a)  {} // overload for int
        void operator()(double a) {} // overload for double
    };

    std::tuple<int, double> tuple_;

    for_each(tuple_, DoSomething());