私はこのように、クラスのメンバ変数に値を代入するC++ 17の構造バインディングを使用したい:構造化バインディングを使用してクラスメンバーを割り当てることはできますか?
#include <cmath>
#include <iostream>
struct Result {
double value;
bool error;
};
Result square_root(double input) { return {std::sqrt(input), input < 0}; }
struct Calculator {
double result_;
bool error_;
public:
void ComputeSquareRoot(double input) {
[ result_, error_ ] = square_root(input);
}
void DisplayResult() {
if (error_)
std::cout << "Cannot take the square root of a negative number.\n";
else
std::cout << "The square root is " << result_ << ".\n";
}
};
int main(int argc, char* argv[]) {
Calculator calc;
calc.ComputeSquareRoot(64);
calc.DisplayResult();
}
しかし、このコードは、(打ち鳴らす5.0を使用して)次のエラーでコンパイルに失敗:
> clang++ structured_bindings.cpp -std=c++17 -o structured_bindings
structured_bindings.cpp:20:7: error: 'result_' in capture list does not name a variable
[ result_, error_ ] = square_root(input);
^
structured_bindings.cpp:20:16: error: 'error_' in capture list does not name a variable
[ result_, error_ ] = square_root(input);
^
structured_bindings.cpp:20:25: error: expected body of lambda expression
[ result_, error_ ] = square_root(input);
^
3 errors generated.
ラムダキャプチャには多少の混乱があるようです。確かにこれは動作します:
auto[result, error] = square_root(input);
result_ = result;
error_ = error;
しかし、新しいローカル変数を使用する必要はありません。これは構造化バインディングで可能ですか?
別の変数ではなく、 'Calculator'に' Result'オブジェクトを置くことができると思います。 – Galik
@Galikはい、これは疑問を実証するための少し複雑な例でした。 :) –