gpt4 book ai didi

C++ 完美函数转发

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:40:03 28 4
gpt4 key购买 nike

这是 this 的跟进问题。

A 2002 paper对C++中的函数转发问题作如下观察:

This is the method currently employed by Boost.Bind and Boost.Lambda:

template<class A1, class A2, class A3> void f(A1 & a1, A2 & a2, A3 & a3)
{
return g(a1, a2, a3);
}

Its main deficiency is that it cannot forward a non-const rvalue. The argument deduction creates a non-const reference, and the reference cannot bind to the argument. This makes innocent examples as

int main()
{
f(1, 2, 3);
}

fail (violates C1).

我看到调用失败了,但是解释正确吗?文字 1、2、3 不是常量右值吗?

最佳答案

文字 1、2、3 不是常量右值吗?

不,它们只是 int 类型的右值。根据 C++ 标准,基本类型的右值不能是 const 限定的。

调用失败,因为它们是右值 - 非常量引用不能绑定(bind)到右值。

如果函数采用 const A1 &, const A2&, const A3&,调用将正常,但在这种情况下,函数将无法修改参数。

编辑: 引用我在 C++ 2003 标准中的第一条声明:(3.10.9)

Class rvalues can have cv-qualified types; non-class rvalues always have cv-unqualified types. Rvalues shall always have complete types or the void type; in addition to these types, lvalues can also have incomplete types.

关于C++ 完美函数转发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5235188/

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