Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing pointer to any member function as class template argument

Tags:

c++

templates

template<typename T, typename M, M Method>
class ProxyObject
{
public:

    template<typename... Args>
    void Invoke (T& Object, _In_ Args&&... A)
    {
        (void)(Object.*Method)(std::forward<Args>(A)...);
    }
};

class Object
{
public:

    int MyMethod (int Val)
    {
        wcout << L"Hello!" << endl;
        return Val;
    }
};


int wmain ()
{
    Object myObj;
    ProxyObject<Object, decltype(&Object::MyMethod), &Object::MyMethod> obj;

    obj.Invoke(myObj, 10);

    return 0;
}

The decltype(&Object::MyMethod) seems redundant in the definition of obj. Is there any way to make the ProxyObject automatically infer the type of the pointer-to-member-function being passed, so that I can define obj as follows:

ProxyObject<Object, &Object::MyMethod> obj;
like image 597
TripShock Avatar asked Sep 16 '26 09:09

TripShock


1 Answers

I think it's impossible for class template, because you have to specify the member function type explicitly.

Template function could help you lot with the argument deduction:

template<typename T, typename M, typename... Args>
void invoke (T& Object, M Method, Args&&... A)
{
    (void)(Object.*Method)(std::forward<Args>(A)...);
}

then

invoke(myObj, &Object::MyMethod, 10);

LIVE

like image 194
songyuanyao Avatar answered Sep 17 '26 22:09

songyuanyao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!