【问题标题】:What do parentheses mean within angle brackets for a Boost signal?Boost 信号尖括号内的括号是什么意思?
【发布时间】:2017-12-01 12:50:03
【问题描述】:

在我的基本 c++ 书中,没有像下面这样的类声明。 对我来说奇怪的代码是......

boost::signals2::signal<bool (const std::string& message, 
const std::string& caption, unsigned int style),
boost::signals2::last_value<bool> > ThreadSafeMessageBox;

圆括号(const std:::string...)中的东西不是类型名而是实例。怎么可能?上面的代码编译得很好。

附言模板类(signal)代码是

template<typename Signature,
  typename Combiner = optional_last_value<typename boost::function_traits<Signature>::result_type>,
  typename Group = int,
  typename GroupCompare = std::less<Group>,
  typename SlotFunction = function<Signature>,
  typename ExtendedSlotFunction = typename detail::extended_signature<function_traits<Signature>::arity, Signature>::function_type,
  typename Mutex = mutex >
class signal: public detail::signalN<function_traits<Signature>::arity,
  Signature, Combiner, Group, GroupCompare, SlotFunction, ExtendedSlotFunction, Mutex>::type
{ /*...*};

【问题讨论】:

  • 使用** 突出显示C++ 代码的一部分不是一个好主意。
  • 是函数类型

标签: c++ templates parentheses boost-signals2


【解决方案1】:

查看Boost.Signals2的文档:

Boost.Signals2 库是托管信号和插槽系统的实现。 信号代表具有多个目标的回调

所以我们知道“信号”与“回调”有关。 callback 是稍后调用的函数。

那么,请查看文档中的 "Hello World" 示例:

struct HelloWorld
{
  void operator()() const
  {
    std::cout << "Hello, World!" << std::endl;
  }
};
// ...

  // Signal with no arguments and a void return value
  boost::signals2::signal<void ()> sig;

  // Connect a HelloWorld slot
  HelloWorld hello;
  sig.connect(hello);

  // Call all of the slots
  sig();

首先,我们创建一个信号sig,该信号不带任何参数并且有一个void 返回值。接下来,我们使用connect 方法将hello 函数对象连接到信号。最后,像函数一样使用信号sig 调用槽,然后调用HelloWorld::operator() 打印“Hello, World!”。

阅读完所有这些,我们可以推断出什么?我们可以推断出信号的模板参数是一个函数类型。它表示可以连接到信号的功能类型。

所以,在你的例子中

boost::signals2::signal<bool (const std::string& message, 
                             const std::string& caption, 
                             unsigned int style), 
                        boost::signals2::last_value<bool> 
                       > ThreadSafeMessageBox;

ThreadSafeMessageBox 是一个可以连接到以下函数的信号:

  • 返回bool
  • 采用const std::string&amp;的第一个参数
  • 接受第二个参数const std::string&amp;
  • 接受第三个参数unsigned int

(对于这个问题,我们可以忽略第二个模板参数,它不是必需的模板参数,也不是回调函数签名的一部分,而是称为Combiner

【讨论】:

    【解决方案2】:

    模板参数Signature的预期类型是一个函数签名,即预期的函数参数编号、类型和返回类型的规范。

    你的情况

    boost::signals2::signal<bool (const std::string& message, const std::string& caption, unsigned int style), boost::signals2::last_value<bool> > ThreadSafeMessageBox;
    

    模板boost::signals2::signal的第一个参数是函数签名:

    bool (const std::string& message, const std::string& caption, unsigned int style)
    

    这是一个具有 3 个参数(类型为 stringstringunsigned int)并返回 bool 的函数。

    【讨论】:

      猜你喜欢
      • 2021-11-26
      • 2018-07-15
      • 1970-01-01
      • 2011-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-12
      相关资源
      最近更新 更多