对于多态方法,通过引用可选参数?

时间:2016-06-29 11:01:35

标签: c++

我有一个像这样的多态方法层次结构:

void func(double x, const std::string& s) = 0;

我希望传递一个“可选”参数,该参数在方法中被修改:

void func(double x, const std::string& s, uint64_t& i = 0) = 0;

但是我收到的错误是我的引用未初始化。

实施上述目标的最佳方法是什么?

3 个答案:

答案 0 :(得分:5)

uint64_t&是一个L值引用,因此不能绑定到R值,就像您提供的默认参数一样。您必须提供L值作为默认值。

一个选项是定义一个默认传递的虚拟对象,例如:

static uint64_t dummy_default_value = 0;
void func(double x, const std::string& s, uint64_t& i = dummy_default_value ) = 0;

答案 1 :(得分:5)

我会避免虚拟方法的默认参数(参见good-practice-default-arguments-for-pure-virtual-method),所以只需添加额外的重载

virtual void func(double x, const std::string& s, uint64_t& i) = 0;
void func(double x, const std::string& s) { int i; func(x, s, i) };

如果您真的想保留默认参数,可以使用boost::optional

virtual void func(double x,
                  const std::string& s,
                  boost::optional<uint64_t&> i = boost::none) = 0;

答案 2 :(得分:3)

您可以使用指针而不是引用,并且在函数实现中,只有在传递的指针不是nullptr

时才修改(取消引用)值
void func(double x, const std::string& s, uint64_t* pi = nullptr) = 0;