C++函数指针

dot*_*nic 0 c++ pointers function-pointers

在C++中有没有办法制作一个"untyed"函数指针?例如:

// pointer to global function
void foo( void (*fptr)() );

// pointer to member
void foo( void (Bar::*fptr)() );
Run Code Online (Sandbox Code Playgroud)

有没有办法可以删除该成员所在的班级?所以我可以这样做:

void foo( void ("any type"::*fptr)(), "same type as for the pointer" &instance );
Run Code Online (Sandbox Code Playgroud)

然后,在foo中,我想将该指针存储在一个列表中,这样我就可以在列表上进行迭代并调用指向的函数/成员,而不管它属于哪个类.当然,我需要一个可以调用该函数的实例列表.

谢谢.

Pup*_*ppy 7

您可以使用模板.

template<typename T> void foo( void(T::*)(), T&) { ... }
Run Code Online (Sandbox Code Playgroud)

但是,人们更喜欢采用功能对象方法.您可以动态或静态地执行此操作.

void foo(std::function<void()> func) {
    // std::bind is used to make this out of a member function
}
template<typename T> void foo(T t = T()) {
    t(); // This is the best approach.
}
Run Code Online (Sandbox Code Playgroud)

编辑:一些例子.

void foo(std::function<void()> func) {
    std::cout << "In example one ";
    func();
}
template<typename T> void foo(T t = T()) {
    std::cout << "In example two ";
    t();
}
class some_class {
public:
    void func() { std::cout << "in ur function!\n"; }
};
int main(void)
{
    some_class* ptr = NULL;
    struct tempfunctor {
        tempfunctor(some_class* newptr)
            : ptr(newptr) {}
        some_class* ptr;
        void operator()() { return ptr->func(); }
    };
    foo(tempfunctor(ptr)); // Calls example two
    foo(std::function<void()>(tempfunctor(ptr))); // Calls example one
    foo(std::function<void()>(std::bind(&some_class::func, ptr)); // I'm not that familiar with bind, it looks something similar to this.
    std::cin.get();
}
Run Code Online (Sandbox Code Playgroud)

这是一个称为函数对象习语的习语,在STL和其他高质量库中大量使用.编译时模板更干净,但std :: function可以在运行时绑定.

编辑@OP:我没有在那里看到您的列表要求.A std::function<void()>是你最好的选择.