LoginSignup
0
0

More than 1 year has passed since last update.

C++で計算型プロパティ

Posted at

PythonやSwiftにある計算型プロパティ(Computed Property)をC++でも使いたい!

計算型プロパティもどき

template <typename T>
class Property {
 public:
  Property(std::function<T(void)> get, std::function<void(T)> set) {
    this->get = get;
    this->set = set;
  }

  std::function<T(void)> get;
  std::function<void(T)> set;

  operator const T() {
    return get();
  }
  void operator=(const T newValue) {
    set(newValue);
  }
};

使用例

class Circle {
public:
  Property<double> radius = {
    [this]() {
      return radius_;
    },
    [this](double newValue) {
      radius_ = newValue;
    }
  };
  Property<double> diameter = {
    [this]() {
      return radius * 2;
    },
    [this](double newValue) {
      radius = newValue / 2;
    } 
  };
  Property<double> circumference = {
    [this]() {
      return diameter * 3.14;
    },
    [this](double newValue) {
      diameter = newValue / 3.14;
    }
  };

  Circle(double radius) {
    radius_ = radius;
  }

private:
  // 格納型プロパティ (Stored Property) としては1つしか持っていない状態
  double radius_;
};

int main(void) {
  Circle circle(5.0);  // 半径5
  std::cout << "radius: " << circle.radius << std::endl;                // 5
  std::cout << "diameter: " << circle.diameter << std::endl;            // 10
  std::cout << "circumference: " << circle.circumference << std::endl;  // 314

  circle.diameter = 1;  // 直径1
  std::cout << "radius: " << circle.radius << std::endl;                // 0.5
  std::cout << "diameter: " << circle.diameter << std::endl;            // 1
  std::cout << "circumference: " << circle.circumference << std::endl;  // 3.14

  circle.circumference = 314;  // 円周314
  std::cout << "radius: " << circle.radius << std::endl;                // 50
  std::cout << "diameter: " << circle.diameter << std::endl;            // 100
  std::cout << "circumference: " << circle.circumference << std::endl;  // 314

  return 0;
}

初投稿でした。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0