How do I store a function to a variable?

前端 未结 7 1913
灰色年华
灰色年华 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:54

    From C++11 you can use std::function to store functions. To store function you use it as follsonig:

    std::function<return type(parameter type(s))>

    as an example here it is:

    #include 
    #include 
    
    int fact (int a) {
        return a > 1 ? fact (a - 1) * n : 1;
    }
    
    int pow (int b, int p) {
        return p > 1 ? pow (b, p - 1) * b : b;
    }
    
    int main (void) {
        std::function factorial = fact;
        std::function power = pow;
    
        // usage
        factorial (5);
        power (2, 5);
    }
    

提交回复
热议问题