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');
                        这篇关于避免繁琐的可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:避免繁琐的可选参数
				
        
 
            
        基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
 - 我有静态或动态 boost 库吗? 2021-01-01
 - 这个宏可以转换成函数吗? 2022-01-01
 - 在 C++ 中计算滚动/移动平均值 2021-01-01
 - 常量变量在标题中不起作用 2021-01-01
 - 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
 - 如何通过C程序打开命令提示符Cmd 2022-12-09
 - C++结构和函数声明。为什么它不能编译? 2022-11-07
 - 如何在 C++ 中初始化静态常量成员? 2022-01-01
 - 如何检查GTK+3.0中的小部件类型? 2022-11-30
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				