How can it be useful to overload the “function call” operator?

后端 未结 7 463
终归单人心
终归单人心 2020-12-02 20:43

I recently discovered that in C++ you can overload the \"function call\" operator, in a strange way in which you have to write two pair of parenthesis to do so:



        
7条回答
  •  萌比男神i
    2020-12-02 21:23

    There's little more than a syntactic gain in using operator() until you start using templates. But when using templates you can treat real functions and functors (classes acting as functions) the same way.

    class scaled_sine
    {
        explicit scaled_sine( float _m ) : m(_m) {}
        float operator()(float x) const { return sin(m*x); }
        float m;
    };
    
    template
    float evaluate_at( float x, const T& fn )
    {
       return fn(x);
    }
    
    evaluate_at( 1.0, cos );
    evaluate_at( 1.0, scaled_sine(3.0) );
    

提交回复
热议问题