简体   繁体   English

模板成员函数指针作为模板参数

[英]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() :我知道如何为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>> .不。虽然如果您只需要Foo的特定实例化,您可以使用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.为了能够使用不同的签名,您必须修改Invoke以对任何类型的可调用对象进行操作。 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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