首页 > 解决方案 > 为什么适配器兼容的函数对象不能作为参考传递参数?

问题描述

我想制作一个函数对象以将参数作为参考,而不是值。如果我使用没有 的函数对象std::not1,它可以工作。但是,使用std::not1,除非参数将参数作为值,否则它根本不会编译。

下面的代码来自cppreference not1,我改为LessThan7将参数i作为参考,而不是值:

struct LessThan7 : std::unary_function<int, bool>
{
    bool operator()(int &i) const { return i < 7; }
};

int main()
{
    std::vector<int> v(10);
    std::iota(begin(v), end(v), 0);

    std::cout << std::count_if(begin(v), end(v), std::not1(LessThan7())) << "\n";

    std::function<bool(int)> less_than_9 = [](int x){ return x < 9; };
    std::cout << std::count_if(begin(v), end(v), std::not1(less_than_9)) << "\n";
}

为什么这段代码不起作用?:

error: no matching function for call to object of type 'const LessThan7'
        {return !__pred_(__x);}
                 ^~~~~~~

标签: c++stl

解决方案


传递给的谓词count_if不得修改其参数。int &不允许使用类型参数。您应该使用 const 引用获取参数:

struct LessThan7 : std::unary_function<int, bool>
{
    bool operator()(const int &i) const { return i < 7; }
};

推荐阅读