可以使用std :: function来存储带有可变参数的函数 [英] Can std::function be used to store a function with variadic arguments

查看:365
本文介绍了可以使用std :: function来存储带有可变参数的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在我的应用程序中传递的结构,其中包含一堆回调函数:

I have a structure that I pass around my application which contains a bunch of callback functions:

typedef struct {
    std::function<void (void)>    f1;
    std::function<void (int)>     f2;
    std::function<int  (float *)> f3;
    // ... and so on
} CallbackTable;

我通过将不同的函数绑定到各种回调来处理应用程序中的状态控制,具体取决于当前的系统状态;它工作正常.

I handle state control within the application by binding different functions to the various callbacks, depending upon the current system state; it works fine.

我现在想做的是添加一些额外的回调,这些回调的签名包含可变数量的参数,类似于printf:例如,

What I'd now like to do is to add a couple of extra callbacks with signatures containing variable numbers of arguments, akin to printf: for example,

    std::function<int  (const char * format, ...)> printToStdOut;

无效.在Visual C ++中,我收到一条错误消息,指出:

This doesn't work. In Visual C++, I get an error message stating:

error C2027: use of undefined type 'std::_Get_function_impl<_Fty>'

我仍然对C ++语法的这一领域感到满意,并且非常感谢任何关于如何从此处开始的建议.我的首要目标是能够按照以下方式拨打电话:

I'm still feeling my way through this area of C++ syntax and would very much appreciate any advice on how I should proceed from here. My overriding objective is to be able to make a call along the lines of:

myCallbackTable.printToStdOut("I've just eaten %d bananas\r\n", nBananas);

...并根据系统状态将输出定向到控制台,文件或GUI窗口.

...and to have the output directed to a console, to a file or to a GUI window, according to the system state.

推荐答案

原始答案有误,已修改,但可能仍然不是一个好的答案,将其留在此处用于教育目的:

Original answer was wrong, modified but still may not be a good answer, leaving it here for educational purposes:

许多可变参数函数具有va_list版本.例如, printf 具有 vprintf .这些变体显式采用va_list而不是省略号.

Many variable argument functions have a va_list version. printf for example has vprintf. These variants explicitly take a va_list instead of an ellipses.

#include <iostream>
#include <functional>
#include <cstdarg>


int main()
{
   std::function<int(const char*,va_list)> test2(vprintf);

   return 0;
}

但是,调用它很痛苦.

int invoke_variadic(const std::function<int(const char*,va_list)>& ref,const char* a ,...)
{
    va_list args;
    va_start(args,a);
    ref(a,args);
    va_end(args);
}

原始帖子出了什么问题(感谢/u/T.C.): std :: function< int(const char *,va_list)>test2(printf)进行编译,我认为它有效".但是它之所以编译是因为printf可以接受任何类型的参数(包括va_list),并且 std :: function 仅检查是否可以通过这种方式调用.

What was wrong with original post (thanks /u/T.C.): std::function<int(const char*,va_list)> test2(printf) compiles, which I took to meaning it "worked". However it compiles because printf can accept arguments of any type (including a va_list), and std::function only checks if it can be invoked in that way.

这篇关于可以使用std :: function来存储带有可变参数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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