避免繁琐的可选参数

如果我有一个带有 2 个必需参数和 4 个可选参数的构造函数,我怎样才能避免编写 16 个构造函数,甚至 10 个左右的构造函数,如果我使用默认参数(我不喜欢)因为它的自我文档很差)?是否有任何使用模板的习语或方法可以使我不那么乏味?(而且更容易维护?)

If I have a constructor with say 2 required parameters and 4 optional parameters, how can I avoid writing 16 constructors or even the 10 or so constructors I'd have to write if I used default parameters (which I don't like because it's poor self-documentation)? Are there any idioms or methods using templates I can use to make it less tedious? (And easier to maintain?)

推荐答案

您可能对 命名参数习语.

总而言之,创建一个类来保存要传递给构造函数的值.添加一个方法来设置每个值,并让每个方法在最后执行 return *this; .在你的类中有一个构造函数,它接受这个新类的 const 引用.这可以像这样使用:

To summarize, create a class that holds the values you want to pass to your constructor(s). Add a method to set each of those values, and have each method do a return *this; at the end. Have a constructor in your class that takes a const reference to this new class. This can be used like so:

class Person;

class PersonOptions
{
  friend class Person;
  string name_;
  int age_;
  char gender_;

public:
   PersonOptions() :
     age_(0),
     gender_('U')
   {}

   PersonOptions& name(const string& n) { name_ = n; return *this; }
   PersonOptions& age(int a) { age_ = a; return *this; }
   PersonOptions& gender(char g) { gender_ = g; return *this; }
};

class Person
{
  string name_;
  int age_;
  char gender_;

public:
   Person(const PersonOptions& opts) :
     name_(opts.name_),
     age_(opts.age_),
     gender_(opts.gender_)
   {}
};
Person p = PersonOptions().name("George").age(57).gender('M');

相关文章