What are C++ functors and their uses?

后端 未结 14 1545
花落未央
花落未央 2020-11-21 04:27

I keep hearing a lot about functors in C++. Can someone give me an overview as to what they are and in what cases they would be useful?

14条回答
  •  自闭症患者
    2020-11-21 04:50

    Little addition. You can use boost::function, to create functors from functions and methods, like this:

    class Foo
    {
    public:
        void operator () (int i) { printf("Foo %d", i); }
    };
    void Bar(int i) { printf("Bar %d", i); }
    Foo foo;
    boost::function f(foo);//wrap functor
    f(1);//prints "Foo 1"
    boost::function b(&Bar);//wrap normal function
    b(1);//prints "Bar 1"
    

    and you can use boost::bind to add state to this functor

    boost::function f1 = boost::bind(foo, 2);
    f1();//no more argument, function argument stored in f1
    //and this print "Foo 2" (:
    //and normal function
    boost::function b1 = boost::bind(&Bar, 2);
    b1();// print "Bar 2"
    

    and most useful, with boost::bind and boost::function you can create functor from class method, actually this is a delegate:

    class SomeClass
    {
        std::string state_;
    public:
        SomeClass(const char* s) : state_(s) {}
    
        void method( std::string param )
        {
            std::cout << state_ << param << std::endl;
        }
    };
    SomeClass *inst = new SomeClass("Hi, i am ");
    boost::function< void (std::string) > callback;
    callback = boost::bind(&SomeClass::method, inst, _1);//create delegate
    //_1 is a placeholder it holds plase for parameter
    callback("useless");//prints "Hi, i am useless"
    

    You can create list or vector of functors

    std::list< boost::function > events;
    //add some events
    ....
    //call them
    std::for_each(
            events.begin(), events.end(), 
            boost::bind( boost::apply(), _1, e));
    

    There is one problem with all this stuff, compiler error messages is not human readable :)

提交回复
热议问题