如何使用isnan作为谓词函数std :: find_if(c ++ 11) [英] How to use isnan as a predicate function to std::find_if (c++11)

查看:713
本文介绍了如何使用isnan作为谓词函数std :: find_if(c ++ 11)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个操作在 std :: vector< double> cats ,并且正在这样做:

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

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

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

我如何得到这个在新的gcc下编译?最好还是在老gcc下?没有摆脱stl和手动写循环当然。如果不可能做到这两者,新的gcc就足够了,我会使用 #define 保留两个实现。

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中的模板,它只是一个带有这个签名的普通函数:

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

(有一个模板,但SFINAE意味着它只适用于整数类型。)

(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.

你已经说过C ++ 11,你可以使用一个lambda,并让lambda的主体做重载决议找到正确的重载(或模板专业化):

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

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

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

这篇关于如何使用isnan作为谓词函数std :: find_if(c ++ 11)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆