有没有办法在c ++中使用没有指针的方法设置方法?

时间:2013-05-25 04:55:20

标签: c++

有没有办法使用没有指针的方法设置方法?

void (*_method)();

void setMethod(void (*method)()) {
    _method = method;
}

void getMethod() {
    _method()
}

void aMethod() {

}

main() {
    setMethod(aMethod);
    getMethod();
}

有没有办法在没有指针的情况下做到这一点?只是直接变量?我知道我可以在没有指针的情况下做这样的事情:

void callSomeMethod(void (method)()) {
    method();
}

但是如果没有它们,上面的整个事情能完成吗?

2 个答案:

答案 0 :(得分:3)

如果你想避免使用指针,你总是可以使用引用。

void callSomeMethod(void (&method)())
{
    method();
}

这样可以防止将空指针传递给callSomeMethod()

答案 1 :(得分:2)

是。您可以使用std::functionstd::bind执行此操作。 http://en.cppreference.com/w/cpp/utility/functional/function