gpt4 book ai didi

C++11:编译器什么时候将 {} 视为 std::initializer_list,什么时候不考虑?

转载 作者:搜寻专家 更新时间:2023-10-31 01:32:23 26 4
gpt4 key购买 nike

我有一个快速示例:

#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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com