Have an amazing solution built in RAD Studio? Let us know. Looking for discounts? Visit our Special Offers page!
C++RAD Studio

C++BuilderでC++17 構造化束縛(Structured Bindings)の使用方法を学ぶ

write-efficient-code-with-modern-c17-feature-structured-bindings

このブログでは、C++17で利用可能な構造化束縛(Structured Bindings)を使用して効率的なコードを迅速に書く方法をC++Builderで学びます。

C++17では、糖衣構文(syntax sugar)と自動型推論を統合する新機能として「構造化束縛」が導入されました。構造化束縛は、ペア、タプル、構造体や配列などを要素に分解する機能で、これを利用すると関数から複数の値を返した場合、戻り値の受け取りが簡単になります。

構造化束縛の構文は、以下の通りです。

auto [var1, var2, ...] = <pair, tuple, struct, or array expression>;
  • 変数 var1, var2 – のリストは、代入される式に含まれる変数の数と正確に一致しなければなりません。
  • 次に以下のいずれかが必要
    • std::pair
    • std::tuple
    • 構造体
    • 配列
  • 型として “auto”,”const auto”, “auto&&”といった自動推論型が使用可能(auto以外の型、例えば、intやdoubleといった具体的な型は使用不可)

角括弧[…]で囲まれた変数の数が一致しない場合、以下のコード例のようにコンパイラはエラーを発生し、構文の間違いを指摘します。

std::tuple<float, int, long> tup {3.55, 1, 99};
auto [a, b] = tup; // gives an error

実際のコード例を見てみましょう。

#ifdef _WIN32
#include <tchar.h>
#else
typedef char _TCHAR;
#define _tmain main
#endif
 
#include <string>
#include <iostream>
#include <tuple>
 
// Demonstrate structured bindings - here, a method might in the past
// have had a bool success result, and an error param written to.
// Now, can return both (all error info) as one tuple, bound automatically
// to local vars through the auto keyword (much nicer than std::tie
// in C++11/14)
 
auto connect_to_network() {
  // The connection could succeed, or fail with an error message
  // Here, mimic it failing
  bool connected{ false }; // failed!
 
  std::string str_error{ "404: resource not found" };
 
  return std::make_tuple(connected, str_error);
}
 
int _tmain(int argc, _TCHAR* argv[]) {
  auto [connected, str_error] = connect_to_network();
 
  if (!connected) {
    std::cout << str_error;
  }
 
  system("pause");
 
  return 0;
}

上記のコードのように構造化束縛を使用することで、より効率的で整頓されたコードを記述できます。

「構造化束縛」について詳しく知りたい方は、公式ドキュメントを参考ください。また、このブログで紹介しましたサンプルコードは、こちらからダウンロードできます。

C++Builder 10.4では、最新のC++17の言語仕様をサポートしており、C++17の新機能もすぐに試せます。製品の詳細は、こちらを参照してください。

「C++Builderで使用方法を学ぶ」シリーズのバックナンバー

RAD Studio 13.2 Florence Now Available! Kai 1.1.1 Now Available! What's Coming in RAD Studio 13.2 Florence

Reduce development time and get to market faster with RAD Studio, Delphi, or C++Builder.
Design. Code. Compile. Deploy.

Start Free Trial   Upgrade Today

   Free Delphi Community Edition   Free C++Builder Community Edition

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

IN THE ARTICLES