Question

I would like to have a constructor with default argument static_cast like:

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

where

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

and func_double_double_t is the base class for many function objects similar to this.

GCC says "invalid static_cast" for the above constructor. Is there a way to achieve such a behavior?

Was it helpful?

Solution

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top