避免了可选参数的繁琐 [英] avoiding the tedium of optional parameters
问题描述
如果我有一个构造函数,说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');
这篇关于避免了可选参数的繁琐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!