C++11:编译器何时将 {} 视为 std::initializer_list,何时不视为?

标签 c++ c++11 templates types initializer-list

我有一个快速示例:

#include <utility>

using namespace std;

struct A{
    int i;
    char c;
};

void f(const A&){}

template<class T>
void g(T&& t)
{
    f(forward<T>(t));
}

int main() {
    A a={1,'@'};//OK
    f({1,'#'});//OK
    g({1,'@'});//Compilation error
    return 0;
}

Clang 会给出这个错误:

    testArray.cpp:16:5: error: no matching function for call to 'g'
        g({1,'@'});//fix: g<A>({1,'@'})
        ^
    testArray.cpp:9:6: note: candidate template ignored: couldn't infer
          template argument 'T'
    void g(T&& t)
         ^

我的问题是:

  1. A a={1,'@'}; 中,如果 {} 推导为 std::initializer_list ,那么它是如何从 std::initilizer_list 转换为 A 类型的呢?

  2. f({1,'#'}); 中,当 f 需要类型 A 时,编译器是否隐式生成 A 对象,还是从 std::initializer_list 转换为 A

  3. 为什么当g()是模板时,模板类型推导不能给出类型Astd::forward 是否有助于将消息从 f 传递到 g(假设 T 是类型 ) >A

最佳答案

  1. In 'A a={1,'@'}'' :If {} is deduced as std::initializer_list, then how it's converted from std::initilizer_list to type A?

不,它与std::initializer_list无关。 。 a只是 copy-list-initialized来自{1,'@'} .

  1. In 'f({1,'#'});' When f requires a type A, does compiler implicitly generates an A object, or it converts from std::initializer_list to A?

它仍然与 std::initializer_list 无关。函数参数为copy-list-initialized来自{1,'#'} .

  1. why when "g()" is a template, the template type deduction doesn't work to give a type A? Does "forward" help to convey the message from f to g, say that T is type A()?

因为这属于non deduced context ,模板参数T无法推导导致编译错误。

6) The parameter P, whose A is a braced-init-list, but P is not std::initializer_list or a reference to one:

还有

when does compiler consider {} as std::initializer_list, and when doesn't?

当您将函数参数类型声明为 std::initializer_list 时然后传递一个大括号列表作为参数,然后 std::initializer_list将被 build 。另一个案例是 auto ,例如

auto x1 = {3}; // x1 is deduced as std::initializer_list<int>
auto x2{1, 2}; // after C++17, error: not a single element
               // before C++17, it was std::initializer_list<int>
auto x3{3};    // after C++17, x3 is deduces as int
               // before C++17 it was std::initializer_list<int>

顺便说一句:即使有 auto它不适用于 {1,'@'} ,应该是 std::initializer_list<char> ,或std::initializer_list<int>

关于C++11:编译器何时将 {} 视为 std::initializer_list,何时不视为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43444677/

相关文章:

c++ - 为什么 >?= 和 <?= 在 VC++ 中不起作用?

c++ - 如何在最后一个 EOL 后删除文件内容?

c++ - C++中最小堆的比较器

c++ - 为什么我的字符串转换为 float-conversion 不能用 istringstream 得到所有小数?

C++11 lambda函数对象成员

c++ - 使用 gcc 11.2 在 Linux 上编译 imgui、glfw、opengl 失败

c++ - 读到 C++ 中的新行进入无限循环

html - Meteor 模板强制为 HTML

c++ - 模板特化中的默认实参参数

c++ - 用模板函数覆盖虚函数