60

JavaScript ES6 には、 destructuringと呼ばれる言語機能があります。他の多くの言語にも存在します。

JavaScript ES6 では、次のようになります。

var animal = {
    species: 'dog',
    weight: 23,
    sound: 'woof'
}

//Destructuring
var {species, sound} = animal

//The dog says woof!
console.log('The ' + species + ' says ' + sound + '!')

同様の構文を取得し、この種の機能をエミュレートするには、C++ で何ができますか?

4

5 に答える 5

114

C++17 では、これは構造化バインディングと呼ばれ、次のことが可能になります。

struct animal {
    std::string species;
    int weight;
    std::string sound;
};

int main()
{
  auto pluto = animal { "dog", 23, "woof" };

  auto [ species, weight, sound ] = pluto;

  std::cout << "species=" << species << " weight=" << weight << " sound=" << sound << "\n";
}
于 2016-12-01T15:10:43.767 に答える
53

std::tuple(または) オブジェクトの特定のケースstd::pairに対して、C++ はstd::tie同様の関数を提供します。

std::tuple<int, bool, double> my_obj {1, false, 2.0};
// later on...
int x;
bool y;
double z;
std::tie(x, y, z) = my_obj;
// or, if we don't want all the contents:
std::tie(std::ignore, y, std::ignore) = my_obj;

あなたが提示したとおりの記法へのアプローチを私は知りません。

于 2015-07-13T22:39:39.293 に答える
6

ほとんどの場合、std::mapstd::tie:

#include <iostream>
#include <tuple>
#include <map>
using namespace std;

// an abstact object consisting of key-value pairs
struct thing
{
    std::map<std::string, std::string> kv;
};


int main()
{
    thing animal;
    animal.kv["species"] = "dog";
    animal.kv["sound"] = "woof";

    auto species = std::tie(animal.kv["species"], animal.kv["sound"]);

    std::cout << "The " << std::get<0>(species) << " says " << std::get<1>(species) << '\n';

    return 0;
}
于 2015-07-13T22:39:34.437 に答える
2

残念ながら、JavaScript で慣れ親しんでいる方法を使用することはできません (ちなみに、これは JS の新しいテクノロジーのようです)。その理由は、C++ では、構造体/オブジェクト/代入式内の複数の変数に代入することができないからです。

var {species, sound} = animal

そして、単純な変数としてspeciesandを使用します。現在、C++ にはその機能がありません。sound

代入演算子をオーバーロードしながら構造体やオブジェクトに代入することはできますが、その正確な動作をエミュレートする方法がわかりません (今日の時点で)。同様のソリューションを提供する他の回答を検討してください。多分それはあなたの要件に合っています。

于 2015-07-13T22:56:37.443 に答える
2

別の可能性は次のように行うことができます

#define DESTRUCTURE2(var1, var2, object) var1(object.var1), var2(object.var2)

これは次のように使用されます:

struct Example
{
    int foo;
    int bar;
};

Example testObject;

int DESTRUCTURE2(foo, bar, testObject);

とのローカル変数を生成fooしますbar

もちろん、すべて同じ型の変数を作成することに制限されていますが、autoそれを回避するために使用できると思います。

そして、そのマクロはちょうど 2 つの変数を実行することに制限されています。したがって、DESTRUCTURE3、DESTRUCTURE4 などを作成して、必要な数をカバーする必要があります。

個人的にはこのコード スタイルは好きではありませんが、JavaScript 機能のいくつかの側面にかなり近いものになっています。

于 2015-07-14T00:38:33.697 に答える