C ++ 11 variadic std :: function参数 [英] C++11 variadic std::function parameter

查看:118
本文介绍了C ++ 11 variadic std :: function参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

名为 test 的函数以std :: function<>作为参数。

A function named test takes std::function<> as its parameter.

template<typename R, typename ...A>
void test(std::function<R(A...)> f)
{
    // ...
}

但是,如果我执行以下操作:

But, if I do the following:

void foo(int n) { /* ... */ }

// ...

test(foo);

编译器(gcc 4.6.1)说没有匹配的函数调用测试(void(&)(int))

Compiler(gcc 4.6.1) says no matching function for call to test(void (&)(int)).

code>编译并正常工作,如何修改 test()函数?在 test()函数中,我需要类型为std :: function<>的 f

To make the last line test(foo) compiles and works properly, how can I modify the test() function? In test() function, I need f with type of std::function<>.

我的意思是,是否有任何模板技巧让编译器确定函数的签名(例如 foo 并自动将其转换为 std :: function< void(int)>

I mean, is there any template tricks to let compiler determine the signature of function(foo in example), and convert it to std::function<void(int)> automatically?

我想让这个工作对lambdas(无论是声明和无状态)。

I want to make this work for lambdas(both stated and stateless) as well.

推荐答案

看起来您想使用重载

template<typename R, typename ...A>
void test(R f(A...))
{
    test(std::function<R(A...)>(f));
}

这个简单的实现将接受大部分。异常函数将被拒绝(如 void(int ...))。更多的工作将给你更多的一般性。

This simple implementation will accept most if not all the functions you will try to pass. Exotic functions will be rejected (like void(int...)). More work will give you more genericity.

这篇关于C ++ 11 variadic std :: function参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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