将参数转发到模板成员函数 [英] Forwarding arguments to template member function

查看:202
本文介绍了将参数转发到模板成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

理想的例子

我需要转发一些预定义的参数加上一些用户传递的参数到成员函数。

I need to forward some predefined arguments plus some user-passed arguments to a member function.

#define FWD(xs) ::std::forward<decltype(xs)>(xs)

template<class T, class... Ts, class... TArgs>
void forwarder(void(T::*fptr)(Ts...), TArgs&&... xs)
{
    T instance;
    (instance.*fptr)(FWD(xs)..., 0);
    //                           ^
    // example predefined argument
}

forwarder(&example::f0, 10, 'a');   
forwarder(&example::f1, 10, "hello", 5);

这适用于非模板成员函数。

This works properly for non-template member functions.

传递给 forwarder 的成员函数指针也可以指向模板函数。不幸的是,编译器在这种情况下不能推导出 T 的类型:

The member function pointer passed to forwarder can, however, point to template functions as well. Unfortunately, the compiler is not able to deduce the type of T in that case:

struct example
{
    void f0(int, int) { }

    template<class T>
    void f1(T&&, int) { }
};

// Compiles
forwarder(&example::f0, 10);

// Does not compile
forwarder(&example::f1, 10);

错误:

prog.cpp:30:28: error: no matching function for call to 'forwarder(<unresolved overloaded function type>, int)'
  forwarder(&example::f1, 10);
                            ^
prog.cpp:20:6: note: candidate: template<class T, class ... Ts, class ... TArgs> void forwarder(void (T::*)(Ts ...), TArgs&& ...)
 void forwarder(void(T::*fptr)(Ts...), TArgs&&... xs)
      ^
prog.cpp:20:6: note:   template argument deduction/substitution failed:
prog.cpp:30:28: note:   couldn't deduce template parameter 'T'
  forwarder(&example::f1, 10);






有什么方法可以帮助编译器正确的类型而不改变转发器 的界面?


Is there any way I can help the compiler deduce the correct types without changing the interface of forwarder?

如果没有,

EDIT:也可以接受传递成员函数指针作为模板参数,可能通过包装器。目标成员函数在编译时总是已知的。 Pseudocode:

It would also be acceptable to pass the member function pointer as a template parameter, maybe through a wrapper. The target member function will always be known at compile-time. Pseudocode:

forwarder<WRAP<example::f0>>(10, 'a');
// Where WRAP can be a macro or a type alias.






ideone示例

推荐答案

我在gcc 4.9中编译了代码,成员函数指针;
like this

I compiled your code in gcc 4.9 by providing template arguments to the member function pointer; like this

int main(){
// Compiles
forwarder(&example::f0, 10);
//Does not compile
forwarder(&example::f1, 10);
//Does compile, instantiate template with int or what ever you need
forwarder(&example::f1<int>,10)
}

我相信发生的是你需要实例化模板成员函数。
是否会改变你的界面太多?
我想任何答案将围绕实例化的成员模板不知何故。

I believe what is going on is that you need to instantiate the template member function. does that change your interface too much? I think any answer will revolve around instantiating that member template somehow.

这篇关于将参数转发到模板成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆