什么时候会有 && + && -> && 与 c++ 引用崩溃?

问题描述 投票:0回答:2

我对理解引用折叠有一些疑问,所以我在以下代码中做了实验:

template<typename T>
void func(T&& t) {}


int main() {
    // There is no reference collapse here, only binding left or right values to references with universal reference
    int a = 10;
    func(a);
    func(10);
    func(std::move(a));

    // The following is not case of universal reference, they are reference collapse, only that the type is template type
    int& b1 = a;
    int&& b2 = 10;
    func(b1); // this is the collapse of & + && -> &
    func(b2); // this is the collapse of & + && -> &, since b2 is left reference here not right reference
   
    return 0;
}

我对上面代码的理解正确吗?请给我看一下崩溃的情况

&& + && -> &&
好吗?

c++ reference
2个回答
0
投票

您对转发参考有一些误解。

int a = 10;
func(a); // T is deduced as int&, then int& && -> int& is the type of parameter t
func(10); // T is deduced as int, then int&& is the type of parameter t
func(std::move(a));

// The following is not case of universal reference, they are reference collapse, only that the type is template type
int& b1 = a;
int&& b2 = 10;
func(b1); // T is deduced as int&, then int& && -> int& is the type of parameter t
func(b2); // T is deduced as int&, then int& && -> int& is the type of parameter t

请给我看一下折叠的情况 && + && -> && 吗?

你可以

func<int&&>(0); // T is specified as int&&, then int&& && -> int&& is the type of parameter t

0
投票

您的折叠示例实际上并不是参考折叠。模板参数推导使用与引用折叠平行但不依赖于引用折叠的不同措辞。

std::add_rvalue_reference
是参考折叠的主要示例。

std::add_rvalue_reference<int&>::type x = ...; // x is a lvalue reference & + && = &
std::add_rvalue_reference<int&&>::type y = ...; // y is a rvalue reference && + && = &
© www.soinside.com 2019 - 2024. All rights reserved.