gpt4 book ai didi

c++ - 默认参数值中的 static_cast

转载 作者:行者123 更新时间:2023-11-28 08:00:33 25 4
gpt4 key购买 nike

我想要一个带有默认参数 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 是许多类似于此的函数对象的基类。

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

最佳答案

您确定在您的案例中需要非常量引用吗?如果您可以使用 const 引用,那么就这样做

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

无需强制转换。 (定义后的 ; 也不是。)

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

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

关于c++ - 默认参数值中的 static_cast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11596269/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com