简体   繁体   中英

use external function as member-function pointer

Is it possible in C++ to create a function which is not defined in class A but can be treated like a method pointer? Eg.:

typedef bool (A::*MethodType)(int a);

MethodType g_someMethod = &A::SomeMethod;

Now, I want to create a new function AnotherMethod which is of the type MethodType . I have tried to do the following:

bool A_AnotherMethod(A* _this, int a) {
    std::cout << __FUNCTION__ << "\n";
    return true;
}

MethodType g_someMethod = A_AnotherMethod;

// ...

(this->*g_someMethod )(42);

But I get

error C2440: '=' : cannot convert from 'bool (__cdecl *)(A *,int)' to 'bool (__cdecl A::* )(int)'

How to do it correctly?

No, you can't. C++ does not have a feature similar to extension methods in C#.

ps Method pointers have clumsy syntax in C++ and are rarely used. But this is the way how they are defined in the language.

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