使用 std::tr1::bind 或 std::tr1::mem_fn 时,可以使用 std::not1 的替代方案

what alternative to std::not1 is to be used when using std::tr1::bind or std::tr1::mem_fn

本文关键字:std tr1 not1 方案 可以使 fn bind mem 使用      更新时间:2023-10-16

我有一个我的类 Foo 的智能 ptr 向量:

struct Foo
{
  Foo() : mEnabled( false ) {}
  bool mEnabled;
  bool isEnabled() const { return mEnabled; }
  void setEnabled( bool inEnabled ) { mEnabled = inEnabled; }
  /* ... */
};
typedef std::tr1::shared_ptr< Foo > tFooPtr;
typedef std::vector< tFooPtr > tFooVec;

我有这个工作得很好:

 tFooVec foo_vector; // insert couple of elements
 size_t count = count_if( foo_vector.begin(), foo_vector.end(), std::tr1::mem_fn( &Foo::isEnabled ) );

但是当我想count_if"禁用"Foo对象时,使用什么功能"助手"

 size_t count = count_if( foo_vector.begin(), foo_vector.end(), std::not1( std::tr1::mem_fn( &Foo::isEnabled ) ) ); // does not compile

上面的行不编译:

/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_algo.h:446: error: no match for call to '(std::unary_negate<std::tr1::_Mem_fn<bool (Foo::*)()const> >) (std::tr1::shared_ptr<Foo>&)'
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_function.h:322: note: candidates are: bool std::unary_negate<_Predicate>::operator()(const typename _Predicate::argument_type&) const [with _Predicate = std::tr1::_Mem_fn<bool (Foo::*)()const>]
make: *** [src/shared_ptr_tests.o] Error 1

(在 Linux 上使用 g++ 4.1.2)

我认为编译问题来自std::not1正在使用std::unary_negate,这需要函数/谓词提供的Predicate::argument_type。后者是在谓语派生自std::unary_function叹息时给出

话虽如此,我假设std::tr1::mem_fn没有使用std::unary_function也没有提供argument_type

我现在使用的解决方案是,我现在使用 boost::bind 而不是 std::tr1::bind

#include <boost/bind.hpp>
using namespace boost;
...
size_t countboost = count_if( foo_vector.begin(), foo_vector.end(), !( bind( &Foo::isEnabled, _1 )) );

为了避免复杂化(和混淆),我在整个代码中将 std::tr1::bind 的用法替换为 boost::bind 。

!boost::bind(...为我工作:

  bool test(int i)
  {
    return i < 2;
  }
  TEST( boost_bind_test, negateTest )
  {
    std::vector<int> vec;
    vec.push_back(1);
    vec.push_back(2);
    vec.push_back(3);
    ASSERT_EQ(2, count_if( vec.begin(), vec.end(), !boost::bind(&test, _1)));
  };

潜在的问题是mem_fun(isEnabled)采用const Foo *,而算法count_if传递一个shared_ptr<Foo>到它的谓词。

我不完全确定为什么这适用于mem_fn( &Foo::isEnabled ),但不适用于not1(mem_fn( &Foo::isEnabled )).我所能想到的是,额外的包装器引入了对不同转换的需求。但是你可以解决它:

bool sharedEnabled(tFooPtr x) {
  return x->isEnabled();
}
size_t count2 = std::count_if( foo_vector.begin(), foo_vector.end(), std::not1( std::ptr_fun(&sharedEnabled ) ) );