【问题标题】:C++ 11 Curly BracesC++ 11 花括号
【发布时间】:2014-02-16 15:04:31
【问题描述】:

我已经好几年没用过 C++了,刚刚遇到这个:

program.build({ default_device })

定义是:

cl_int build(
    const VECTOR_CLASS<Device>& devices,
    const char* options = NULL,
    void (CL_CALLBACK * notifyFptr)(cl_program, void *) = NULL,
    void* data = NULL) const

花括号有什么用?我以前从未见过它们在这样的函数调用中使用过。我认为它与函数指针有关,但这似乎是可选的?

【问题讨论】:

  • 如何用元素列表初始化向量?

标签: c++ c++11 syntax


【解决方案1】:

在:

program.build({ default_device })

您正在自动实例化一个临时的 VECTOR_CLASS&lt;Device&gt; 对象。相当于:

program.build(VECTOR_CLASS<Device>{ default_device })

相当于:

program.build(std::vector<Device>{ default_device })

将调用the std::initializer_list constructor:

std::vector::vector(std::initializer_list<T> init, 
    const Allocator& alloc = Allocator());

【讨论】:

  • program.build({ default_device }) here 等价于program.build(VECTOR_CLASS&lt;Device&gt;{ default_device }):前者是复制列表初始化,而第二个是直接列表初始化。有一个微妙的区别,例如对于明确的演员。
【解决方案2】:

std::vector 有一个接受std::initializer_list 的构造函数。

initializer_list 可以用花括号表示。

因此,这段代码创建了一个包含一个default_device 的向量,并将其传递给build 成员函数。

【讨论】:

  • 仅供参考,std::initializer_list 是 C++11 中的新功能。许多 STL 容器,包括 std::vector,已更新为支持 std::initializer_list 作为构建期间的输入。
  • 感谢:“初始化器列表可以用花括号表示”
  • 你怎么知道VECTOR_CLASSstd::vector
  • @BЈовић 鉴于示例代码和名称,它很可能是 std::vector 或类似的东西
【解决方案3】:

【讨论】:

    猜你喜欢
    • 2018-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-12
    • 1970-01-01
    • 2019-01-26
    • 2014-02-04
    • 2012-01-18
    相关资源
    最近更新 更多