How do I store a function to a variable?

前端 未结 7 1911
灰色年华
灰色年华 2020-12-08 08:36

I think they are called functors? (it\'s been a while)

Basically, I want to store a pointer to a function in a variable, so I can specify what function I want to use

7条回答
  •  我在风中等你
    2020-12-08 08:47

    You could also use function either from the c++0x or from boost. That would be

    boost::function
    

    and then use bind to bind your function to this type.

    Have a look here and here

    Ok here would be a example. I hope that helps.

    int MyFunc1(int i)
    {
        std::cout << "MyFunc1: " << i << std::endl;
        return i;
    }
    
    int MyFunc2(int i)
    {
        std::cout << "MyFunc2: " << i << std::endl;
        return i;
    }
    
    int main(int /*argc*/, char** /*argv*/)
    {
        typedef boost::function Function_t;
    
        Function_t myFunc1 = boost::bind(&MyFunc1, _1);
        Function_t myFunc2 = boost::bind(&MyFunc2, _1);
    
        myFunc1(5);
        myFunc2(6);
    }
    

提交回复
热议问题