どのようにすることができますに対して繰り返し処理を実行要素は、std::タプル?

StackOverflow https://stackoverflow.com/questions/1198260

質問

たいのですがに対して繰り返し処理を実行タプル(C++11)?また、以下の:

for(int i=0; i<std::tuple_size<T...>::value; ++i) 
  std::get<i>(my_tuple).do_sth();

が動作しない:

エラー1:まも弱い:を拡大させることができません'スナー...'固定長の引数リスト。
2:できませんが一定の表現です。

なので、どうやって正しく繰り返し処理を実行し、要素のタプル?

役に立ちましたか?

解決

Boost.Fusion の可能性あります:

テストされていない例:

struct DoSomething
{
    template<typename T>
    void operator()(T& t) const
    {
        t.do_sth();
    }
};

tuple<....> t = ...;
boost::fusion::for_each(t, DoSomething());

他のヒント

私は反復処理に基づいて答えを持っていますタプルのオーバーます:

#include <tuple>
#include <utility> 
#include <iostream>

template<std::size_t I = 0, typename... Tp>
inline typename std::enable_if<I == sizeof...(Tp), void>::type
  print(std::tuple<Tp...>& t)
  { }

template<std::size_t I = 0, typename... Tp>
inline typename std::enable_if<I < sizeof...(Tp), void>::type
  print(std::tuple<Tp...>& t)
  {
    std::cout << std::get<I>(t) << std::endl;
    print<I + 1, Tp...>(t);
  }

int
main()
{
  typedef std::tuple<int, float, double> T;
  T t = std::make_tuple(2, 3.14159F, 2345.678);

  print(t);
}

いつものアイデアは、時間再帰をコンパイル使用することです。実際には、このアイデアは、元のタプルの論文で述べたように、タイプセーフであるのprintfを作るために使用されます。

これは容易タプルためfor_eachに一般化することができる:

#include <tuple>
#include <utility> 

template<std::size_t I = 0, typename FuncT, typename... Tp>
inline typename std::enable_if<I == sizeof...(Tp), void>::type
  for_each(std::tuple<Tp...> &, FuncT) // Unused arguments are given no names.
  { }

template<std::size_t I = 0, typename FuncT, typename... Tp>
inline typename std::enable_if<I < sizeof...(Tp), void>::type
  for_each(std::tuple<Tp...>& t, FuncT f)
  {
    f(std::get<I>(t));
    for_each<I + 1, FuncT, Tp...>(t, f);
  }

これは、その後FuncTを持っているいくつかの努力を必要としますが、タプルが含まれている可能性があり、すべてのタイプのための適切なオーバーロードで何かを表しています。あなたはすべてのタプルの要素を知っている場合、これは共通の基底クラスまたは類似した何かを共有する最も効果的に機能します。

C++17日に利用できる std::apply折り表現:

std::apply([](auto&&... args) {((/* args.dosomething() */), ...);}, the_tuple);

完全にイタプル:

#include <tuple>
#include <iostream>

int main()
{
    std::tuple t{42, 'a', 4.2}; // Another C++17 feature: class template argument deduction
    std::apply([](auto&&... args) {((std::cout << args << '\n'), ...);}, t);
}

【オンライン例Coliru]

このソリューション課題を解決すの評価順 M.Alagganの回答.

使用Boost.Hanaと、一般的なラムダます:

#include <tuple>
#include <iostream>
#include <boost/hana.hpp>
#include <boost/hana/ext/std/tuple.hpp>

struct Foo1 {
    int foo() const { return 42; }
};

struct Foo2 {
    int bar = 0;
    int foo() { bar = 24; return bar; }
};

int main() {
    using namespace std;
    using boost::hana::for_each;

    Foo1 foo1;
    Foo2 foo2;

    for_each(tie(foo1, foo2), [](auto &foo) {
        cout << foo.foo() << endl;
    });

    cout << "foo2.bar after mutation: " << foo2.bar << endl;
}

http://coliru.stacked-crooked.com/a/27b3691f55caf271する

C ++ 17では、あなたはこれを行うことができます

std::apply([](auto ...x){std::make_tuple(x.do_something()...);} , the_tuple);

これはすでにはstd ::を使用した実験::適用、クラン++ 3.9で動作します。

あなたがここにBoost.Tupleで示され、テンプレートメタプログラミングを使用する必要があります:

#include <boost/tuple/tuple.hpp>
#include <iostream>

template <typename T_Tuple, size_t size>
struct print_tuple_helper {
    static std::ostream & print( std::ostream & s, const T_Tuple & t ) {
        return print_tuple_helper<T_Tuple,size-1>::print( s, t ) << boost::get<size-1>( t );
    }
};

template <typename T_Tuple>
struct print_tuple_helper<T_Tuple,0> {
    static std::ostream & print( std::ostream & s, const T_Tuple & ) {
        return s;
    }
};

template <typename T_Tuple>
std::ostream & print_tuple( std::ostream & s, const T_Tuple & t ) {
    return print_tuple_helper<T_Tuple,boost::tuples::length<T_Tuple>::value>::print( s, t );
}

int main() {

    const boost::tuple<int,char,float,char,double> t( 0, ' ', 2.5f, '\n', 3.1416 );
    print_tuple( std::cout, t );

    return 0;
}

C ++ 0xのでは、あなたの代わりに可変引数テンプレート関数としてprint_tuple()を書くことができます。

C++言語による紹介 拡大諸表 この目的です。れたトラックのためのC++20が狭くのカット不足により時間の言語の文言の見直し( こちらのこちらの).

現在同意書式は、上記リンク):

{
    auto tup = std::make_tuple(0, 'a', 3.14);
    template for (auto elem : tup)
        std::cout << elem << std::endl;
}

まず、いくつかのインデックスヘルパーを定義します:

template <size_t ...I>
struct index_sequence {};

template <size_t N, size_t ...I>
struct make_index_sequence : public make_index_sequence<N - 1, N - 1, I...> {};

template <size_t ...I>
struct make_index_sequence<0, I...> : public index_sequence<I...> {};

あなたの関数を使用すると、各タプルの要素に適用したいと思います:

template <typename T>
/* ... */ foo(T t) { /* ... */ }

あなたが書くことができます:

template<typename ...T, size_t ...I>
/* ... */ do_foo_helper(std::tuple<T...> &ts, index_sequence<I...>) {
    std::tie(foo(std::get<I>(ts)) ...);
}

template <typename ...T>
/* ... */ do_foo(std::tuple<T...> &ts) {
    return do_foo_helper(ts, make_index_sequence<sizeof...(T)>());
}

またはfoovoidを返した場合、使用します。

std::tie((foo(std::get<I>(ts)), 1) ... );

注:C ++ 14 make_index_sequenceはすでに(定義されている上でます。http:// EN。 cppreference.com/w/cpp/utility/integer_sequence に)。

:あなたは左から右への評価順序を必要とした場合は、

、このような何かを考えます

template <typename T, typename ...R>
void do_foo_iter(T t, R ...r) {
    foo(t);
    do_foo(r...);
}

void do_foo_iter() {}

template<typename ...T, size_t ...I>
void do_foo_helper(std::tuple<T...> &ts, index_sequence<I...>) {
    do_foo_iter(std::get<I>(ts) ...);
}

template <typename ...T>
void do_foo(std::tuple<T...> &ts) {
    do_foo_helper(ts, make_index_sequence<sizeof...(T)>());
}

より簡単で、直感的でコンパイラに優しいということでC++17、 if constexpr:

// prints every element of a tuple
template<size_t I = 0, typename... Tp>
void print(std::tuple<Tp...>& t) {
    std::cout << std::get<I>(t) << " ";
    // do things
    if constexpr(I+1 != sizeof...(Tp))
        print<I+1>(t);
}

これはコンパイル時の再帰の一提@emsr.これを使用しませんのSFINAEなっていました。)でコンパイラです。

タプル::あなたがSTDを使用したい場合、あなたは可変引数テンプレートをサポートC ++コンパイラを持っている、(G ++ 4.5でテスト済み)コード怒鳴るを試してみてください。これは、あなたの質問への答えである必要があります。

#include <tuple>

// ------------- UTILITY---------------
template<int...> struct index_tuple{}; 

template<int I, typename IndexTuple, typename... Types> 
struct make_indexes_impl; 

template<int I, int... Indexes, typename T, typename ... Types> 
struct make_indexes_impl<I, index_tuple<Indexes...>, T, Types...> 
{ 
    typedef typename make_indexes_impl<I + 1, index_tuple<Indexes..., I>, Types...>::type type; 
}; 

template<int I, int... Indexes> 
struct make_indexes_impl<I, index_tuple<Indexes...> > 
{ 
    typedef index_tuple<Indexes...> type; 
}; 

template<typename ... Types> 
struct make_indexes : make_indexes_impl<0, index_tuple<>, Types...> 
{}; 

// ----------- FOR EACH -----------------
template<typename Func, typename Last>
void for_each_impl(Func&& f, Last&& last)
{
    f(last);
}

template<typename Func, typename First, typename ... Rest>
void for_each_impl(Func&& f, First&& first, Rest&&...rest) 
{
    f(first);
    for_each_impl( std::forward<Func>(f), rest...);
}

template<typename Func, int ... Indexes, typename ... Args>
void for_each_helper( Func&& f, index_tuple<Indexes...>, std::tuple<Args...>&& tup)
{
    for_each_impl( std::forward<Func>(f), std::forward<Args>(std::get<Indexes>(tup))...);
}

template<typename Func, typename ... Args>
void for_each( std::tuple<Args...>& tup, Func&& f)
{
   for_each_helper(std::forward<Func>(f), 
                   typename make_indexes<Args...>::type(), 
                   std::forward<std::tuple<Args...>>(tup) );
}

template<typename Func, typename ... Args>
void for_each( std::tuple<Args...>&& tup, Func&& f)
{
   for_each_helper(std::forward<Func>(f), 
                   typename make_indexes<Args...>::type(), 
                   std::forward<std::tuple<Args...>>(tup) );
}

ブースト::融合が別のオプションですが、それは、独自のタプル型が必要です後押し::融合::タプルを。標準へのより良いスティックをすることができます!ここではテストがあります:

#include <iostream>

// ---------- FUNCTOR ----------
struct Functor 
{
    template<typename T>
    void operator()(T& t) const { std::cout << t << std::endl; }
};

int main()
{
    for_each( std::make_tuple(2, 0.6, 'c'), Functor() );
    return 0;
}

可変長引数テンプレートのパワー!

ここだけの標準ライブラリでタプル項目を反復処理の容易なC ++ 17の方法です

#include <tuple>      // std::tuple
#include <functional> // std::invoke

template <
    size_t Index = 0, // start iteration at 0 index
    typename TTuple,  // the tuple type
    size_t Size =
        std::tuple_size_v<
            std::remove_reference_t<TTuple>>, // tuple size
    typename TCallable, // the callable to bo invoked for each tuple item
    typename... TArgs   // other arguments to be passed to the callable 
>
void for_each(TTuple&& tuple, TCallable&& callable, TArgs&&... args)
{
    if constexpr (Index < Size)
    {
        std::invoke(callable, args..., std::get<Index>(tuple));

        if constexpr (Index + 1 < Size)
            for_each<Index + 1>(
                std::forward<TTuple>(tuple),
                std::forward<TCallable>(callable),
                std::forward<TArgs>(args)...);
    }
}

例:

#include <iostream>

int main()
{
    std::tuple<int, char> items{1, 'a'};
    for_each(items, [](const auto& item) {
        std::cout << item << "\n";
    });
}

出力:

1
a

これは、条件付きの場合には呼び出し可能な戻り値を(それでも例えば、ボイドブール割り当て可能な値を返さない呼び出し可能オブジェクトで動作)、ループを切断するように拡張することができます

#include <tuple>      // std::tuple
#include <functional> // std::invoke

template <
    size_t Index = 0, // start iteration at 0 index
    typename TTuple,  // the tuple type
    size_t Size =
    std::tuple_size_v<
    std::remove_reference_t<TTuple>>, // tuple size
    typename TCallable, // the callable to bo invoked for each tuple item
    typename... TArgs   // other arguments to be passed to the callable 
    >
    void for_each(TTuple&& tuple, TCallable&& callable, TArgs&&... args)
{
    if constexpr (Index < Size)
    {
        if constexpr (std::is_assignable_v<bool&, std::invoke_result_t<TCallable&&, TArgs&&..., decltype(std::get<Index>(tuple))>>)
        {
            if (!std::invoke(callable, args..., std::get<Index>(tuple)))
                return;
        }
        else
        {
            std::invoke(callable, args..., std::get<Index>(tuple));
        }

        if constexpr (Index + 1 < Size)
            for_each<Index + 1>(
                std::forward<TTuple>(tuple),
                std::forward<TCallable>(callable),
                std::forward<TArgs>(args)...);
    }
}

例:

#include <iostream>

int main()
{
    std::tuple<int, char> items{ 1, 'a' };
    for_each(items, [](const auto& item) {
        std::cout << item << "\n";
    });

    std::cout << "---\n";

    for_each(items, [](const auto& item) {
        std::cout << item << "\n";
        return false;
    });
}

出力:

1
a
---
1
あなたのヘルパー関数は次のように見えるかもしれませんので、

ブーストのタプルは、ヘルパー関数get_head()get_tail()を提供しています:

inline void call_do_sth(const null_type&) {};

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

ここで説明したようにのhttp:// WWW .boost.org / DOC / LIBS / 1_34_0 / LIBS /タプル/ DOC / tuple_advanced_interface.html

std::tupleと、それは似ている必要があります。

方法は動作するはずです、またはあなたが(すでに提供IO事業者などの)他の利点を持っているstd::tupleに切り替える必要があります前に示唆したように、

実際には、残念ながらboost::tupleは、そのようなインタフェースを提供していないようです。 boost::tupleの欠点は、gccでありますが - それはまだ可変長引数テンプレートを受け入れていないが、私は私のマシンにインストールされているブーストの最新バージョンを持っていないとして、それはすでに固定されてもよい。

私が見逃していた列車ですが、このこちらの今後の開発の参考にする。
ここでの私の構築に基づくこと 答え この 概要:

#include <tuple>
#include <utility>

template<std::size_t N>
struct tuple_functor
{
    template<typename T, typename F>
    static void run(std::size_t i, T&& t, F&& f)
    {
        const std::size_t I = (N - 1);
        switch(i)
        {
        case I:
            std::forward<F>(f)(std::get<I>(std::forward<T>(t)));
            break;

        default:
            tuple_functor<I>::run(i, std::forward<T>(t), std::forward<F>(f));
        }
    }
};

template<>
struct tuple_functor<0>
{
    template<typename T, typename F>
    static void run(std::size_t, T, F){}
};

使用しますのでテストを行うこととされ

template<typename... T>
void logger(std::string format, T... args) //behaves like C#'s String.Format()
{
    auto tp = std::forward_as_tuple(args...);
    auto fc = [](const auto& t){std::cout << t;};

    /* ... */

    std::size_t some_index = ...
    tuple_functor<sizeof...(T)>::run(some_index, tp, fc);

    /* ... */
}

ありきの余改善する。


としてコーコードします:

const std::size_t num = sizeof...(T);
auto my_tuple = std::forward_as_tuple(t...);
auto do_sth = [](const auto& elem){/* ... */};
for(int i = 0; i < num; ++i)
    tuple_functor<num>::run(i, my_tuple, do_sth);

MSVCのSTLで_For_each_tuple_element機能は、(文書化されていない)があります

#include <tuple>

// ...

std::tuple<int, char, float> values{};
std::_For_each_tuple_element(values, [](auto&& value)
{
    // process 'value'
});
ここで

私はここで見てきたすべての回答のは、ここをと、私は言っています<最善を反復のhref = "https://stackoverflow.com/a/6401663/4618482"> @sigidagi のの方法。残念ながら、彼の答えは、私の意見では、固有の明瞭さを覆い隠している非常に冗長です。

これは、より簡潔でかつstd::tuplestd::pairstd::arrayで動作する彼のソリューションの私のバージョンです。

template<typename UnaryFunction>
void invoke_with_arg(UnaryFunction)
{}

/**
 * Invoke the unary function with each of the arguments in turn.
 */
template<typename UnaryFunction, typename Arg0, typename... Args>
void invoke_with_arg(UnaryFunction f, Arg0&& a0, Args&&... as)
{
    f(std::forward<Arg0>(a0));
    invoke_with_arg(std::move(f), std::forward<Args>(as)...);
}

template<typename Tuple, typename UnaryFunction, std::size_t... Indices>
void for_each_helper(Tuple&& t, UnaryFunction f, std::index_sequence<Indices...>)
{
    using std::get;
    invoke_with_arg(std::move(f), get<Indices>(std::forward<Tuple>(t))...);
}

/**
 * Invoke the unary function for each of the elements of the tuple.
 */
template<typename Tuple, typename UnaryFunction>
void for_each(Tuple&& t, UnaryFunction f)
{
    using size = std::tuple_size<typename std::remove_reference<Tuple>::type>;
    for_each_helper(
        std::forward<Tuple>(t),
        std::move(f),
        std::make_index_sequence<size::value>()
    );
}

デモ: coliruする

C ++ 14のstd::make_index_sequenceはC ++ 11 のを実現することができる。

を使用 constexprif constexpr(C++17)これはとてもシンプルなものになって、真っ直ぐ進む:

template <std::size_t I = 0, typename ... Ts>
void print(std::tuple<Ts...> tup) {
  if constexpr (I == sizeof...(Ts)) {
    return;
  } else {
    std::cout << std::get<I>(tup) << ' ';
    print<I+1>(tup);
  }
}

私はここにもう一つの解決策があり、関数オブジェクトのタプルを反復処理するために同じ問題につまずいています:

#include <tuple> 
#include <iostream>

// Function objects
class A 
{
    public: 
        inline void operator()() const { std::cout << "A\n"; };
};

class B 
{
    public: 
        inline void operator()() const { std::cout << "B\n"; };
};

class C 
{
    public:
        inline void operator()() const { std::cout << "C\n"; };
};

class D 
{
    public:
        inline void operator()() const { std::cout << "D\n"; };
};


// Call iterator using recursion.
template<typename Fobjects, int N = 0> 
struct call_functors 
{
    static void apply(Fobjects const& funcs)
    {
        std::get<N>(funcs)(); 

        // Choose either the stopper or descend further,  
        // depending if N + 1 < size of the tuple. 
        using caller = std::conditional_t
        <
            N + 1 < std::tuple_size_v<Fobjects>,
            call_functors<Fobjects, N + 1>, 
            call_functors<Fobjects, -1>
        >;

        caller::apply(funcs); 
    }
};

// Stopper.
template<typename Fobjects> 
struct call_functors<Fobjects, -1>
{
    static void apply(Fobjects const& funcs)
    {
    }
};

// Call dispatch function.
template<typename Fobjects>
void call(Fobjects const& funcs)
{
    call_functors<Fobjects>::apply(funcs);
};


using namespace std; 

int main()
{
    using Tuple = tuple<A,B,C,D>; 

    Tuple functors = {A{}, B{}, C{}, D{}}; 

    call(functors); 

    return 0; 
}

出力:

A 
B 
C 
D

他の人は、優れた設計のサードパーティ ライブラリについて言及していますので、参考にしてください。ただし、これらのサードパーティ ライブラリを使用せずに C++ を使用している場合は、次のコードが役立つ場合があります。

namespace detail {

template <class Tuple, std::size_t I, class = void>
struct for_each_in_tuple_helper {
  template <class UnaryFunction>
  static void apply(Tuple&& tp, UnaryFunction& f) {
    f(std::get<I>(std::forward<Tuple>(tp)));
    for_each_in_tuple_helper<Tuple, I + 1u>::apply(std::forward<Tuple>(tp), f);
  }
};

template <class Tuple, std::size_t I>
struct for_each_in_tuple_helper<Tuple, I, typename std::enable_if<
    I == std::tuple_size<typename std::decay<Tuple>::type>::value>::type> {
  template <class UnaryFunction>
  static void apply(Tuple&&, UnaryFunction&) {}
};

}  // namespace detail

template <class Tuple, class UnaryFunction>
UnaryFunction for_each_in_tuple(Tuple&& tp, UnaryFunction f) {
  detail::for_each_in_tuple_helper<Tuple, 0u>
      ::apply(std::forward<Tuple>(tp), f);
  return std::move(f);
}

注記:コードは C++11 をサポートするコンパイラでコンパイルでき、標準ライブラリの設計との一貫性が保たれます。

  1. タプルはそうである必要はありません std::tuple, 、代わりに、サポートするものであれば何でも構いません std::get そして std::tuple_size;特に、 std::array そして std::pair 使用することができます。

  2. タプルは参照型または cv 修飾されたものにすることができます。

  3. 以下と同様の動作をします std::for_each, 、入力を返します UnaryFunction;

  4. C++14 (またはそれ以降のバージョン) ユーザーの場合、 typename std::enable_if<T>::type そして typename std::decay<T>::type 簡易版に置き換えることもできますが、 std::enable_if_t<T> そして std::decay_t<T>;

  5. C++17 (またはそれ以降のバージョン) ユーザーの場合、 std::tuple_size<T>::value 簡易版に置き換えることもできますが、 std::tuple_size_v<T>.

  6. C++20 (またはそれ以降のバージョン) ユーザーの場合、 SFINAE この機能は、 Concepts.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top