如何从我的专用 std::max 返回临时值?
你好! 我想将 std::max
专门用于特定于平台的分数类型。
我想要使用的特定于系统的 max
的原型如下所示:
fract builtin_max(fract a, fract b);
我对专门的 std::max
的想法如下所示:
template <> inline
const fract& std::max<fract>(const fract& a, const fract& b) {
return builtin_max(a, b);
}
然而,编译器会抱怨返回对本地临时对象的引用。有什么办法可以解决这个问题吗?
Hallo!
I want to specialize std::max
for a platform-specific fraction type.
The prototype for the system-specific max
I want to use looks like this:
fract builtin_max(fract a, fract b);
My idea for a specialized std::max
looks like this:
template <> inline
const fract& std::max<fract>(const fract& a, const fract& b) {
return builtin_max(a, b);
}
However, the compiler understandably complains about returning a reference to a local temporary. Is there any way I can work around this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以按值返回结果。那么RVO很可能会发生。最终你会得到你想要的行为。
我会将
builtin_max
声明更改为它将帮助编译器识别 RVO 的可能性。
最后你的
max
看起来像:You could return a result by value. Then RVO most likely will take place. In the end you will get behavior as you wanted.
And I'd change
builtin_max
declaration toIt will help to the compiler to recognize the possibility for RVO.
Finally your
max
will look like:如果您可以修改
builtin_max
,那么要采取的方法是更改签名,以便它需要两个常量引用并返回一个常量引用(除非类型足够小以至于按值传递有意义) ,以及它的非常量版本的重载。然后,您可以通过简单的方法调整签名:只需转接呼叫即可。您可以做的另一件简单的事情是不要重载 std::max ,而是在命名空间中生成您自己的 max 函数。所有采用
fract
值的max
的不合格使用都会在尝试使用std::maxmax
函数代码>默认模板。话又说回来,这对于对std::max
的完全限定调用不起作用:If you can modify the
builtin_max
then the way to go is changing the signature so that it takes two constant references and returns a constant reference (unless the type is small enough that pass-by-value makes sense), and overload for the non-const version of it. Then you can adapt the signatures the easy way: just forward the call.Another simple thing that you can do is not overload
std::max
but rather produce your ownmax
function within your namespace. All unqualified uses ofmax
that takefract
values will find yourmax
function before they try to use thestd::max
default template. Then again, this will not work for fully qualified calls tostd::max
:我的解决方案是这样做:
超级简单,并且就像我想要的那样工作:)
My solution was to do it just like this:
Super simple, and works just like I want it :)