私はC#でのプロパティのアイデアが本当に好きです。ちょっとしたプロジェクトとして、私はC++でそれらを実装するという考え方を変えてきました。私はhttps://stackoverflow.com/a/5924594/245869のようにうまくいっていますが、lambdaと非静的なデータメンバの初期化によって、このアイデアで非常に良い構文を使用できるようになるとは思えませんでした。ここに私の実装です:C++ 11;非静的データメンバ初期化は他のデータメンバにアクセスできますか?
#include <iostream>
#include <functional>
using namespace std;
template< typename T >
class property {
public:
property(function<const T&(void)> getter, function<void(const T&)> setter)
: getter_(getter),
setter_(setter)
{};
operator const T&() {
return getter_();
};
property<T>& operator=(const T& value) {
setter_(value);
}
private:
function<const T&(void)> getter_;
function<void(const T&)> setter_;
};
class Foobar {
public:
property<int> num {
[&]() { return num_; },
[&](const int& value) { num_ = value; }
};
private:
int num_;
};
int main() {
// This version works fine...
int myNum;
property<int> num = property<int>(
[&]() { return myNum; },
[&](const int& value) { myNum = value; }
);
num = 5;
cout << num << endl; // Outputs 5
cout << myNum << endl; // Outputs 5 again.
// This is what I would like to see work, if the property
// member of Foobar would compile...
// Foobar foo;
// foo.num = 5;
// cout << foo.num << endl;
return 0;
}
私は[main()の例を参照してください]通常、私のプロパティクラスを使用することができますが、G ++ 4.7とMinGWのは、特にデータとしてプロパティを使用しての私の試みのために気にしません。メンバー:
\property.cpp: In lambda function:
\property.cpp:40:7: error: invalid use of non-static data member 'Foobar::num_'
だから、私の財産の実装作品のコンセプトようだが、私は私のラムダ関数から他のデータメンバにアクセスすることはできませんので、それは無駄になるかもしれません。私がここでやろうとしていることをスタンダードがどのように定義しているのかは分かりませんが、私は運がまったくないのですか?
関連性:移動専用のタイプをサポートし、一般的に不要なコピーを避けるために、コンストラクタで 'getter_(std :: move(getter))、setter_(std :: move(setter))'を使用します。 –
質問:面白いこととは別に、私は単純な 'int&'がもっと有用であると信じています。シンプルなリファレンスに比べて、あなたのソリューションの利点は何ですか? (それ自体は役に立たない...) –
@ R.MartinhoFernandes私は完全に同意する。 'property <>'自体もコピー/移動セマンティクスをサポートする必要があり、プロパティを持つクラスをコピー/移動することができます。私はコンセプトを働かせるまで実装をできる限り最小限に抑えたいと思っていました。しかし、ありがとう! @MatthieuM。 –