如何使用isnan作为std :: find

编程入门 行业动态 更新时间:2024-10-15 12:29:18
如何使用isnan作为std :: find_if(c ++ 11)的谓词函数(How to use isnan as a predicate function to std::find_if (c++11))

我有一段代码在std::vector<double> cats并且正在执行如下操作:

std::find_if(cats.begin(), cats.end(), std::isnan<double>);

这个编译在4.3以前的gcc下编译,但不再使用gcc 4.7.2编译。 我得到这样的错误:

error: no matching function for call to 'find_if(std::vector<double>::iterator, std::vector<double::iterator, <unresolved overloaded function type>)'

我怎样才能得到这个在新的gcc下编译? 最好还在旧的gcc下? 没有摆脱stl和手动编写循环当然。 如果两者都无法实现,那么新的gcc就足够了,我会用#define离开这两个实现。

I have a piece of code that is operating on a std::vector<double> cats and is doing something like this:

std::find_if(cats.begin(), cats.end(), std::isnan<double>);

this compiles under gcc before 4.3 but no longer compiles with gcc 4.7.2. I get an error like this:

error: no matching function for call to 'find_if(std::vector<double>::iterator, std::vector<double::iterator, <unresolved overloaded function type>)'

How can I get this to compile under newer gcc? And preferably also under the older gcc? Without getting rid of stl and manually writing the loop of course. If it's not possible to do both, the new gcc would suffice and I would leave both implementations in there with a #define.

最满意答案

你真正想要的重载不是GCC 4.7中的模板,它只是一个具有这个签名的普通函数:

bool isnan(double);

(有一个模板,但SFINAE表示它只适用于整型。)

但在以前的版本中,它是一个模板,所以没有一个简单的可移植的方式来获取它的地址。

既然你已经说过C ++ 11,你可以使用lambda,并让lambda的主体重载解析以找到正确的重载(或模板特化):

std::find_if( cats.begin(), cats.end(), [](double d) { return std::isnan(d); } );

否则,对于C ++ 03,您可以提供自己的转发包装器:

struct IsNan { double operator()(double d) const { return std::isnan(d); } }; std::find_if( cats.begin(), cats.end(), IsNan() );

The overload you actually want is not a template in GCC 4.7, it is just a normal function with this signature:

bool isnan(double);

(There is a template, but SFINAE means it only applies to integral types.)

But in previous versions it was a template, so there isn't an easy portable way to take its address.

Since you've said C++11, you can use a lambda and let the body of the lambda do overload resolution to find the right overload (or template specialization):

std::find_if( cats.begin(), cats.end(), [](double d) { return std::isnan(d); } );

Otherwise for C++03 you could provide your own forwarding wrapper:

struct IsNan { double operator()(double d) const { return std::isnan(d); } }; std::find_if( cats.begin(), cats.end(), IsNan() );

更多推荐

本文发布于:2023-08-03 21:09:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1400321.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   isnan   find   std

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!