默认参数值中的static_cast

static_cast in default argument value

本文关键字:static cast 参数 默认      更新时间:2023-10-16

我想要一个默认参数为static_cast的构造函数,比如:

generate_word_spot(func_double_double_t& cost_f = static_cast<func_double_double_t&>(func_const_t(1))) :
      cost_f_(cost_f)
      {};

其中

class func_const_t : public func_double_double_t 
{ 
   ...
   virtual double operator()(double x){ ... }; 
}

并且CCD_ 1是许多类似于此的函数对象的基类。

GCC对上面的构造函数说"无效的static_cast"。有没有办法实现这样的行为?

您确定在您的案例中需要一个非常数引用吗?如果你可以使用常量引用,那么只需进行

generate_word_spot(const func_double_double_t& cost_f = func_const_t(1)) :
  cost_f_(cost_f)
  {}

无需铸造。(定义后的;也不是。)

否则,对于非常量引用绑定临时对象是不可能的。您需要声明一个独立的非临时对象作为默认参数

func_const_t def_const(1);
...
class generate_word_spot {
  ...
  generate_word_spot(func_double_double_t& cost_f = def_const) :
    cost_f_(cost_f)
    {}
};

使其成为类的静态成员是有意义的

class generate_word_spot {
  ...
  static func_const_t def_const;
  ...
  generate_word_spot(func_double_double_t& cost_f = def_const) :
    cost_f_(cost_f)
    {}
};
func_const_t generate_word_spot::def_const(1);