1

it is a C++ class with 5 objects and 25 functions . at run time i want to pass the object and name of the function as parameters and make the object passed call the specified method .

it is like

void actionToBetaken(object,string method_name)
 {
       object.method_name();
 }

how it is possible in C++ ?

4

1 回答 1

9

这通常使用函数指针来完成:

template <typename T, typename U>
void f(T &object, U (T::*method)())
{
   (object.*method)();
}

这假定该方法不带任何参数。您可以通过以下方式传递带有参数的方法:

template <typename T, typename U, typename... Args>
void f(T &object, U (T::*method)(Args...), Args&&... args)
{
   (object.*method)(std::forward<Args>(args)...);
}

int main()
{
    T t;

    f(t, &T::f, 5); // calls t.f(5)
}

您也可以使用std::functionorstd::bind来实现这种功能。

于 2013-03-16T13:38:35.023 回答