我讨厌手动编写构造函数。我该如何自动化?

struct MyFunctor {
public:
  MyFunctor(/* repeat what I wrote again!*/)
  :/* repeat what I wrote again! */
  { }

  bool operator()() { return true; }

private:
  Controller *m_controller;
  String m_action;
  bool m_allowRejection;
  /* ... */
};

最佳答案

您可以放弃数据隐藏,并使用C语言的旧结构初始化:

struct MyFunctor
{
    Controller *m_controller;
    String m_action;
    bool m_allowRejection;

    bool operator()() const
    {
        return true;
    }
};

MyFunctor fun = {&some_controller, "hello world", false};


在C ++ 0x中,由于统一的初始化,您甚至可以即时创建对象:

some_function( MyFunctor {&some_controller, "hello world", false} );


...或者您可以切换到Scala并使用主要构造函数;)

关于c++ - 根据非静态数据成员自动生成构造函数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5482662/

10-09 04:03