Created
February 3, 2017 01:04
-
-
Save utilForever/ca67c54c2d68b3b81e01b3a25e88d787 to your computer and use it in GitHub Desktop.
Call member function pointed by instantiated object (using variadic template and std::bind)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| #include <functional> | |
| class AAA | |
| { | |
| public: | |
| bool A(int a, int b, int c) | |
| { | |
| return a + b + c > 10; | |
| } | |
| }; | |
| template <typename Obj, typename Func, typename... Args> | |
| decltype(auto) CallFunc(Obj* obj, Func (Obj::*func)(Args...), Args&&... args) | |
| { | |
| return (obj->*func)(std::forward<Args>(args)...); | |
| } | |
| int main() | |
| { | |
| AAA* aaa = new AAA(); | |
| if (CallFunc(aaa, &AAA::A, 2, 4, 8)) | |
| { | |
| std::cout << "Hello World\n"; | |
| } | |
| auto fn = std::bind(&AAA::A, aaa, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3); | |
| if (fn(3, 4, 5)) | |
| { | |
| std::cout << "Hello World\n"; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For the first, approach at line 14 for explicit member function pointer was really inspiring code for me!
Invoke 1
I felt that
CallFuncis quite similar tostd::asyncwith its signature. And if I'm right, it usesstd::bindinternally.(Can't sure. Might be different upon vendors...)I used
Fn&&for funtion type deduction. Since function name is address of its code, It won't make any difference with receiving function pointer.Invoke 2
To pretend
thispointer, I overloadedInvokewith second parameter as a pointer. It's simply namedOwnersince it owns member variables.-> typename std::result_of<Fn(Owner*, Args&&...)>::typeis explicitly noted for reader.Use-case