2016-11-22 55 views
0

我有一个更复杂的包装类的版本,它封装了如下所示的用户类型的std :: vector。如何否定由mem_fn创建的函数指针的结果

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

但我不知道如何使用它的d不幸的是我没有访问lamdbas,因为即使我正在编译GCC 4.8,现在代码也应该用vs2010编译。

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

回答

1

当你没有lambdas时,记住它们只是可调用对象的语法糖。创建自己的泛型否定赎回:

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

+0

得益于良好的剩余部分。在我的情况下,我可能需要这个语法糖,因为评论者不熟悉功能模式不会喜欢这样长的对象 –

+0

没有lambda =没有语法糖。寻找更好的评论者:P –

+0

我现在仍然希望使用这种解决方案,希望能够像std :: not1,std :: unary_negation等更轻。 –