How do I store a function to a variable?

左心房为你撑大大i 提交于 2019-11-28 20:40:13

The simplest you can do is

unsigned int (*pFunc)(unsigned int) = func_1;

This is a bare function pointer, which cannot be used to point to anything other than a free function.

You can make it less painful if your compiler supports the C++0x auto keyword:

auto pFunc = func_1;

In any case, you can call the function with

unsigned int result = pFunc(100);

There are many other options that provide generality, for example:

  • You can use boost::function with any C++ compiler
  • With a compiler implementing features of C++0x you can use std::function

These can be used to point to any entity that can be invoked with the appropriate signature (it's actually objects that implement an operator() that are called functors).

Update (to address updated question)

Your immediate problem is that you attempt to use Config::current_hash_function (which you declare just fine) but fail to define it.

This defines a global static pointer to a function, unrelated to anything in class Config:

unsigned static int (*current_hash_function)(unsigned int) = kennys_hash_16;

This is what you need instead:

unsigned int (*Config::current_hash_function)(unsigned int) = kennys_hash_16;

No, these are called function pointers.

unsigned int (*fp)(unsigned int) = func_1;

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

boost::function<int(int)>

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<int(int)> Function_t;

    Function_t myFunc1 = boost::bind(&MyFunc1, _1);
    Function_t myFunc2 = boost::bind(&MyFunc2, _1);

    myFunc1(5);
    myFunc2(6);
}
typedef unsigned int (*PGNSI)(unsigned int);

PGNSI variable1 = func_1;
PGNSI variable2 = func_2;

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 <functional>
#include <iostream>

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<int(int)> factorial = fact;
    std::function<int(int, int)> power = pow;

    // usage
    factorial (5);
    power (2, 5);
}
unsigned int (* myFuncPointer)(unsigned int) = &func_1;

However, the syntax for function pointers is awful, so it's common to typedef them:

typedef unsigned int (* myFuncPointerType)(unsigned int);
myFuncPointerType fp = &func_1;

IF you have Boost installed, you can also check out Boost Function.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!