新しい変数を作成し、同時に std::tie で使用するにはどうすればよいでしょうか? 質問する

新しい変数を作成し、同時に std::tie で使用するにはどうすればよいでしょうか? 質問する

一度に新しい変数を使用したり作成したりする良い方法はありますかstd::tie? つまり、関数が を返しstd::tuple、最終的にその結果を個々のコンポーネントに分割したい場合、事前に変数を定義せずにこれらの割り当てを行う方法はありますか?

たとえば、次のコードを考えてみます。

#include <tuple>

struct Foo {
    Foo(int) {}
};
struct Bar{};

std::tuple <Foo,Bar> example() {
    return std::make_tuple(Foo(1),Bar()); 
}

int main() {
    auto bar = Bar {};

    // Without std::tie
    {
        auto foo_bar = example();
        auto foo = std::get<0>(std::move(foo_bar));
        bar = std::get<1>(std::move(foo_bar));
    }

    // With std::tie
    #if 0
    {
        // Error: no default constructor
        Foo foo;
        std::tie(foo,bar) = example();
    }
    #endif

}

基本的に、関数はタプルを返します。に代入するexample型の変数はすでにありますが、 型の新しい変数が必要です。 がなければのダミーインスタンスを作成する必要はありませんが、コードでは最初にすべてを に入れてからそれを分割する必要があります。 がある場合は、最初にダミーを割り当てる必要がありますが、そのためのデフォルトコンストラクタがありません。実際には、 のコンストラクタが複雑であると仮定しているため、最初にダミー値を作成するのは望ましくありません。最終的には、との両方に代入したいのですが、この代入と のメモリの割り当てを同時に実行したいのです。BarFoostd::tieFoostd::tuplestd::tieFooFoofoobarFoo

ベストアンサー1

この機能は構造化バインディングC++17 で。非常に歓迎すべき追加です!

使用例:

#include <iostream>
#include <tuple>

int main()
{
    auto tuple = std::make_tuple(1, 'a', 2.3);

    // unpack the tuple into individual variables declared at the call site
    auto [ i, c, d ] = tuple;

    std::cout << "i=" << i << " c=" << c << " d=" << d << '\n';

    return 0;
}

GCC 7.2 でテスト済み-std=c++17

おすすめ記事