繁体   English   中英

如何从我的专业std :: max返回一个临时文件?

[英]How can I return a temporary from my specialized 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);
}

但是,可以理解,编译器抱怨返回对本地临时文件的引用。 有什么办法可以解决这个问题?

您可以按值返回结果。 然后最有可能发生RVO 最后,您将获得所需的行为。

然后将builtin_max声明更改为

fract builtin_max(const fract& a, const fract& b);

这将有助于编译器认识到RVO的可能性。

最终,您的max看起来像:

template <> 
fract std::max<fract>(const fract& a, const fract& b) {
    return builtin_max(a, b);
}

如果您可以修改builtin_max则可以通过更改签名来使其采用两个常量引用并返回一个常量引用(除非类型足够小,以使传递值有意义),而对于非它的const版本。 然后,您可以通过简单的方法来修改签名:只需转发呼叫即可。

fract const & builtin_max( fract const & lhs, fract const & rhs );
fract & builtin_max( fract & lhs, fract & rhs );

template <>
fract const & std::max( fract const & lhs, fract const & rhs ) {
   return builtin_max( lhs, rhs );
}
template <>
fract & std::max( fract & lhs, fract & rhs ) {
   return builtin_max( lhs, rhs );
}

您可以做的另一件简单的事情不是重载std::max而是在您的命名空间内生成您自己的max函数。 所有使用fract值的max不合格用法都会在尝试使用std::max默认模板之前找到max函数。 再说一次,这对于对std::max完全限定调用不起作用:

namespace x {
   class fract;
   fract max( fract lhs, fract rhs ) { return builtin_max( lhs, rhs ); }
}
// force a link time error if fully qualified std::max is used (undefined)
// instead of silently getting std::max to use < (if it is defined)
// if there is no operator<( fract const &, fract const & ), leave this out
// to get an earlier compile time error
template <> fract const & std::max( fract const &, fract const & );
template <> fract & std::max( fract &, fract & );

int main() {
   using namespace std;
   fract a,b;
   max( a, b );          // x::max
   // std::max( a, b )   // ouch, link time error
}

我的解决方案是这样做:

fract std::max(fract a, fract b) {
    return builtin_max(a, b);
}

超级简单,就像我想要的一样工作:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM