c++ - 用 boost::function 定义 boost 信号?

标签 c++ boost

通常,您可以像这样定义 boost::signals2::signal:

typedef boost::signals2::signal<void (int)> MySignalType;
MySignalType mySignal;

然后您可以使用MySignalType::slot_function_type来获取与该信号兼容的函数签名。

然而,我正在尝试做相反的事情。

我现有的代码不使用 Boost 信号。相反,代码会传递一个 boost::function 并将其回调以“发出信号”某个事件。我想根据现有的 boost::function 创建一个 boost::signals2::signal 。我尝试了最直观的组合:

typedef boost::function<void (int)> MyFunctionType;
typedef boost::signals2::signal<MyFunctionType> MySignalType;

但这被编译器拒绝了。如果这是不可能的,我会感到惊讶,因为两者都是 Boost 包。我最好的猜测是,boost::function 对象(或 typedef)有自己的内部 typedef,其用途与 slot_function_type 类似,可在需要纯函数签名的情况下使用,但我在boost::function documentation中没有找到类似的东西.

我尝试搜索类似的问答,并浏览 Boost 文档,但没有发现有人在做同样的事情。

有没有办法根据现有的 Boost 函数定义 Boost 信号?

谢谢。

最佳答案

如果你想从 boost::function 中提取签名,那么你可以尝试这样的事情:

#include <boost/signals2.hpp>
#include <boost/function.hpp>
#include <iostream>
#include <ostream>

using namespace boost;
using namespace std;

template<typename T>
struct get_arg;

template<template<typename> class Func,typename Sig>
struct get_arg< Func<Sig> >
{
    typedef Sig type;
};

int main()
{
    typedef boost::function<void()> F;
    signals2::signal< get_arg<F>::type > signal;
}

编辑:

Very interesting. Can you point me to someplace that explains what your code does and how you came up with it?

get_arg 是类模板,它从其参数中提取模板参数(来自 get_arg 的模板参数)。

换句话说就是Metafunction - 它实际上是对类型进行操作的函数(而普通函数对值进行操作)。

template<template<typename> class Func,typename Sig>
struct get_arg< Func<Sig> >

此语法为 partial specialization get_arg 类模板

template<typename> class Func

此语法为 template template parameter .

typedef Sig type;

按照惯例,元函数的结果是嵌套的“类型”成员。

用法是:

get_arg< SomeClassTemplate<SomeType> >::type

这会导致SomeType

有关更多信息,请参阅以下书籍:

  1. 现代 C++ 设计:通用编程和设计模式的应用。作者:安德烈·亚历山德雷斯库
  2. C++ 模板元编程:Boost 及其他领域的概念、工具和技术。作者:大卫·亚伯拉罕 (David Abrahams) 和阿列克谢·古尔托沃伊 (Aleksey Gurtovoy)

关于c++ - 用 boost::function 定义 boost 信号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13299833/

相关文章:

c++ - QVariant 转换为基本类型

c++ - 从服务器收到 FIN 但连接挂起与 libcurl

c++ - 将 Boost Serialize 与 Qt 插件一起使用

c++ - boost::geometry::model::linestring 与 boost::geometry::model::polygon 的交集

c++ - 如何将有界重复匹配为仅 n 和 m 次

c++ - 在 Qt 中创建 COM 对象

c++ - boost_multi 数组太大? bad_alloc 错误

c++ - 使用 cmake 打开 cv build 找不到 libjpeg

c++ - 使用 boost C++ 单元测试套件测试非 fatal error 消息

c++ - Boost.Spirit Qi : different entry points to the same grammar?