gpt4 book ai didi

c++ - 编译器如何知道必须调用 std::forward 函数的哪个重载?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:31:06 26 4
gpt4 key购买 nike

以下签名被声明为 std::forward 重载:

template<class T> T&& forward(typename remove_reference<T>::type& arg) noexcept;
template<class T> T&& forward(typename remove_reference<T>::type&& arg) noexcept;

现在,考虑以下模板函数:

template<class T> T&& foo_as_always(T&& t)
{
return std::forward<T>(t);
}

如果我写:

int i = 0;
foo_as_always(i);

然后这就是编译器如何使用 T = int& 实例化 foo_as_always:

int& foo_as_always(int& t)
{
// Does it call the first signature of std::forward(int&)
return std::forward<int&>(t);
}

如果我写:

foo_as_always(0);

然后编译器用T = int实例化foo_as_always:

int&& foo_as_always(int&& t)
{
// Does it call the second signature of std::forward(int&&)?
return std::forward<int>(t);
}

在这两种情况下,t 变量在任何表达式中都是左值。编译器如何知道必须调用 std::forward 函数的哪个重载?

最佳答案

因为您显式提供了模板参数(您提供了 <T> );没有类型推导。

在通话中foo_as_always(i); , i是左值所以 T推导为 int & ,这就是您提供给 std::forward 的内容.

在通话中foo_as_always(0); , 0是一个右值,所以 T推导为 int ,这又是您提供给 std::forward 的内容.

当然,在这两种情况下,它最终都会调用第一个重载,因为 t正如您所说,是左值。但返回类型不同——在第一种情况下,它是 int& && , 所以 int& ,在第二种情况下,它是 int && .

关于c++ - 编译器如何知道必须调用 std::forward 函数的哪个重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25444561/

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