【问题标题】:Optimal way to access std::tuple element in runtime by index在运行时按索引访问 std::tuple 元素的最佳方式
【发布时间】:2014-01-30 12:30:14
【问题描述】:

我有函数 at 旨在通过运行时指定的索引访问 std::tuple 元素

template<std::size_t _Index = 0, typename _Tuple, typename _Function>
inline typename std::enable_if<_Index == std::tuple_size<_Tuple>::value, void>::type
for_each(_Tuple &, _Function)
{}

template<std::size_t _Index = 0, typename _Tuple, typename _Function>
inline typename std::enable_if < _Index < std::tuple_size<_Tuple>::value, void>::type
    for_each(_Tuple &t, _Function f)
{
    f(std::get<_Index>(t));
    for_each<_Index + 1, _Tuple, _Function>(t, f);
}

namespace detail { namespace at {

template < typename _Function >
struct helper
{
    inline helper(size_t index_, _Function f_) : index(index_), f(f_), count(0) {}

    template < typename _Arg >
    void operator()(_Arg &arg_) const
    {
        if(index == count++)
            f(arg_);
    }

    const size_t index;
    mutable size_t count;
    _Function f;
};

}} // end of namespace detail

template < typename _Tuple, typename _Function >
void at(_Tuple &t, size_t index_, _Function f)
{
    if(std::tuple_size<_Tuple> ::value <= index_)
        throw std::out_of_range("");

    for_each(t, detail::at::helper<_Function>(index_, f));
}

它具有线性复杂性。我怎样才能达到 O(1) 复杂度?

【问题讨论】:

  • tuple 类型是否统一?
  • @Yakk 一般情况下他们不是
  • 我不确定优化器是否可以做到这一点,但也许你可以通过元编程生成一系列if-else-if-else-if,然后用开关/查找表代替。

标签: c++ templates c++11 template-meta-programming stdtuple


【解决方案1】:

假设您传递类似于通用 lambda 的东西,即具有重载函数调用运算符的函数对象:

#include <iostream>

struct Func
{
    template<class T>
    void operator()(T p)
    {
        std::cout << __PRETTY_FUNCTION__ << " : " << p << "\n";
    }
};

你可以建立一个函数指针数组:

#include <tuple>

template<int... Is> struct seq {};
template<int N, int... Is> struct gen_seq : gen_seq<N-1, N-1, Is...> {};
template<int... Is> struct gen_seq<0, Is...> : seq<Is...> {};

template<int N, class T, class F>
void apply_one(T& p, F func)
{
    func( std::get<N>(p) );
}

template<class T, class F, int... Is>
void apply(T& p, int index, F func, seq<Is...>)
{
    using FT = void(T&, F);
    static constexpr FT* arr[] = { &apply_one<Is, T, F>... };
    arr[index](p, func);
}

template<class T, class F>
void apply(T& p, int index, F func)
{
    apply(p, index, func, gen_seq<std::tuple_size<T>::value>{});
}

使用示例:

int main()
{
    std::tuple<int, double, char, double> t{1, 2.3, 4, 5.6};
    for(int i = 0; i < 4; ++i) apply(t, i, Func{});
}

clang++ 还接受应用于包含 lambda 表达式的模式的扩展:

static FT* arr[] = { [](T& p, F func){ func(std::get<Is>(p)); }... };

(虽然我不得不承认这看起来很奇怪)

g++4.8.1 拒绝这个。

【讨论】:

  • 构建一个包含 n 个元素的数组是 O(n)
  • @Yakk 现在是静态的 ;)
  • 谢谢。我无法用 msvs2013 编译你的代码,但我的想法很清楚
  • @sliser 嗯 __PRETTY_FUNCTION__ 宏是非标准的,但其余的不应该太花哨..
  • msvs2013 using & constexpr 关键字有问题
猜你喜欢
  • 2011-11-19
  • 1970-01-01
  • 1970-01-01
  • 2017-04-23
  • 1970-01-01
  • 1970-01-01
  • 2013-09-04
  • 1970-01-01
相关资源
最近更新 更多