0

我想要一个带有默认参数 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){ ... }; 
}

并且func_double_double_t是许多与此类似的函数对象的基类。

GCCstatic_cast对上述构造函数说“无效”。有没有办法实现这种行为?

4

1 回答 1

1

Are you sure you need a non-const reference in your case? If you can use a const reference then just do

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

No cast necessary. (Neither is the ; after the definition.)

Otherwise, for non-const reference binding temporary object is out of question. You'd need to declare a standalone non-temporary object to use as default argument

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)
    {}
};

It makes sense to make it static member of the class

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);
于 2012-07-21T22:23:23.957 回答