c++ - 如何否定由 mem_fn 创建的函数指针的结果

标签 c++ visual-studio-2010

我有一个更复杂的包装类版本,它封装了如下用户类型的 std::vector。

struct UserType1Encapsulator
{
   template <typename F>
   UserType1Encapsulator& Filter( F filterFunction )
   {
       std::vector<userType1> newList;
       for ( size_t i = 0; i < iTerrainList.size(); i++)  --> can't use range for loop vs2010 
       {
           if ( filterFunction(iTerrainList[i]) )
               newList.push_back(iTerrainList[i]);

       }
       encapsulatedList = newList;
       return *this;
   }

std::vector<userType1> encapsulatedList;
}

我正在做一些链接的事情,比如 Filter.Filter.Map 等。

一切都很好,直到我发现我需要否定对我传递的函数指针的操作

   userVec.Filter( std::mem_fn(&userType1::isCopy) );

我需要使用像

这样的东西
userVec.Filter( std::not1( std::mem_fn(&userType1::isCopy)) );

但我不确定如何使用它,不幸的是我无法访问 lamdbas,因为即使我正在使用 GCC 4.8 进行编译,现在代码也应该使用 vs2010 进行编译。

否定 std::mem_fn 的结果的正确方法是什么,它将在 vs2010 中编译?

最佳答案

当您没有 lambda 表达式时,请记住它们只是可调用对象的语法糖。创建您自己的通用否定可调用对象:

template <typename TFunction>
struct negator
{
    // `_f` will be your mem_fn
    TFunction _f;

    negator(TFunction f) : _f(f) { }

    bool operator()(/* same arguments as isCopy */) const
    {
        return !f(/* same arguments as isCopy */);
    }
};

template <typename TFunction>
negator<TFunction> make_negator(TFunction f)
{
    return negator<TFunction>(f);
}

然后您应该能够按如下方式使用它:

userVec.Filter( make_negator( std::mem_fn(&userType1::isCopy)) );

full wandbox example

关于c++ - 如何否定由 mem_fn 创建的函数指针的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40740303/

相关文章:

c - 初始化 Switch Case

c++ - LNK2005,MSVC2010 中的 "already defined error"链接器错误

database - 组件 OLE DB 源没有输入

c++ - 将二维数组转换为一维数组以绘制线条

c++ - 为多次执行创建makefile

c++ - 删除 std::map 中的特定元素

c++ - 将二维数组指针传递给 C++ 中的函数

c# - 不包含适合入口点的静态 'main' 方法

c++ - 在 C++ 函数中传递原始数据类型的最佳实践

c++ - 将 .txt 文件中的 char 值读入数组 C++ 时出错