【问题标题】:Overload operators for std::function?std::function 的重载运算符?
【发布时间】:2015-08-19 21:50:01
【问题描述】:

假设您想对函数执行数学运算。从数学上我们知道f(x)*g(x) 也是一个函数,如果f 和g 是。

如何用std::function 表达这一点?我正在考虑重载数学运算符:

typedef std::function<double(double)> func;

func operator * (const func &f, func &g) 
{
        auto temp = [&] () { return f( ?? ) * g ( ?? ); };
        return temp; 
}

但我不确定f 和g 的论点将如何发挥作用。我可以为此使用std::placeholders 吗?正确的做法是什么?

【问题讨论】:

    标签: c++ c++11 operator-overloading std functor


    【解决方案1】:

    应该是

    func operator* (const func &f, const func &g) 
    {
            return [=](double x) { return f(x) * g(x); }
    }
    

    不过,我不建议这样做。一方面,因为你不能向std 添加东西,所以ADL 找不到这个操作符,所以你必须依赖普通的不合格查找,这充其量是脆弱的。还有,多层std::function效率很低。

    【讨论】:

    • 谢谢!应该想到的:)
    【解决方案2】:

    在返回类型中不需要类型擦除。你真的想要这样的东西:

    class composed {
       std::function<double(double)> f;
       std::function<double(double)> g;
    public:
       composed(std::function<double(double)> f, std::function<double(double)> g) : f(f), g(g) { }
       double operator()(double x) { return f(x) * g(x); }
    };
    inline composed operator*(std::function<double(double)> f, std::function<double(double)> g) { return composed(f,g); }
    

    这比返回std::function&lt;double(double)&gt; 更有效。如果调用者愿意,composed 仍然可以转换为 1。但是当你只是将它传递给std::transform时,直接调用composed效率更高。

    事实上,operator* 的工业级实现也会尝试捕获f 和g 的实际类型,因此composed 将成为模板。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-04
      • 2021-10-25
      • 1970-01-01
      • 2018-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-11
      相关资源
      最近更新 更多