gpt4 book ai didi

c++ - 为什么不能将 C++ 通用引用与标准引用混合使用?

转载 作者:太空宇宙 更新时间:2023-11-04 14:53:41 25 4
gpt4 key购买 nike

我试图理解 C++11 的通用引用,并编写了以下代码:

#include <cstdio>                                                                                                                                                                                                                                            

template <typename L, typename R>
static void Run(L&& lhs, const R& rhs) {
lhs += rhs;
}

static void Run2(int&& lhs, const int& rhs) {
lhs += rhs;
}

int main() {
int a = 0;
int b = 3;
Run(a, b);
printf("%d\n", a);
// This does not compile.
Run2(a, b);
printf("%d\n", a);
return 0;
}

请注意 Run() 有效,但调用 Run2() 的行将无法编译。我真的不知道为什么。我得到的错误是第一个参数没有从“int”到“int &&”的已知转换

我确信编译器是正确的,但我不明白为什么。好像是 Run()Run2() 做同样的事情吧?

顺便说一句,将 Run2() 更改为使用单个参数进行模板化也不起作用。

最佳答案

“通用引用”只能发生在推断引用类型的上下文中,例如在模板类型上下文 T&& 中。在这种情况下,对于右值参数,T 可以推导为 int,因此您将 int&& 作为参数类型;或作为左值参数的 int&,这将给出类型 int& &&,每个引用折叠规则变成 int&。在您的 Run2 函数中,类型直接为 int&& 因此它不能绑定(bind)到任何左值,除非您使用 std::move

关于c++ - 为什么不能将 C++ 通用引用与标准引用混合使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34833416/

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