简体   繁体   中英

Templated member function pointer as template parameter

I am looking to accept a templated member function as a template parameter.

For example, given this class:

class A
{
public:
    template<typename... Args>
    void Foo(Args...) {}

    void Bar() {}
};

I would like to be able to call:

Invoke<&A::Foo>(5, true);

And have this be similar to calling:

A a;
a.Foo(5, true);

I know how to do this for Bar() :

template<void (A::*F)()>
void Invoke()
{
    A a;
    (a.*F)();
}

int main()
{
    Invoke<&A::Bar>();
}

Is it possible to extend this to a templated member function pointer? Or similarly, to write a forwarding function like this that can handle a function with any parameter types. This doesn't work, but something similar to:

template<typename... Args, void (A::*F)(Args...)>
void Invoke(Args... args)
{
    A a;
    (a.*F)(args...);
}

I can see why this might not be possible, but if that's true could you point to the standard for why? I am also trying to learn more about the specifics of the standard.

Is it possible to extend this to a templated member function pointer?

No. Although if you just need a particular instantiation of Foo you could use Invoke<&A::Foo<int, bool>> .

Or similarly, to write a forwarding function like this that can handle a function with any parameter types.

To be able to work with different signatures, you would have to modify Invoke to operate on any kind of callable object. Then, you would have to define a callable object that calls your actual function:

struct callable_foo
{
    explicit callable_foo( A& obj ) : _obj( obj ){}

    template< typename ...Args >
    void operator ()( Args&&... args )
    {
         _obj.Foo( std::forward< Args >( args )... );
    }

    A& _obj;
}

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