简体   繁体   中英

What type can hold member-function-pointers of difference classes in C++?

I need an array to hold member-function-pointers of different classes. How can I define the array?

The code should look like this:

arr[0] = &CMyClass::FuncX;
arr[1] = &CYourClass::FuncY;
arr[2] = &CHerClass::FuncZ;

I tried void* , but it doesn't work.

You can't; they are all different types and arrays are homogeneous.

Regardless what the arguments are or what the return value is, there is an implicit this which is unique to the class type. The type of a class member pointer is:

return_value (class_type::*)(parameters);

As you can see, because they belong to different classes they will always be a different type. Even if it were the same class, the return_value and parameters would have to be consistent to create an array, otherwise you'd still have different types.

What's the bigger picture? Boost.Bind with Boost.Function comes to mind. Also, virtual functions may solve your problem.

As others have pointed out, you can't store pointers to different kinds of functions directly. You might want to look at the Command template, eg, from Modern C++ Design , which at least lets you put different invokable "things" (pointers or smart pointers to functions, functors, member functions) into a single thing.

On its own, that probably won't be sufficient -- you'll (apparently) end up with the template instantiated over different types, which produces different types. Those types will all use the same syntax, but won't all go into an array (which demands a single type).

Depending on your constraints, (compile-time vs. run-time indexing, in particular) you may be able to use a Boost::tuple to store a collection of command objects. You can treat that a bit like an array, using numeric indexing to get to an individual item. Unlike a normal array, however:

  1. the syntax is a bit ugly, and
  2. The indexing has to be done at compile-time (using compile-time constants).

在不知道函数的参数或返回类型的情况下,很难定义它们,您可以查看此页面来了解其要点或发布函数的声明。

Others have noted why you can't do this. But even if you could, what would you be able to do with it. In order to call a member function pointer, you need to an object of the appropriate type to call it on. So you would need to know the type of each of the member function pointers. You need to take a step back and figure out what it is that you are trying to accomplish.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM