gpt4 book ai didi

c++ - 为什么 T 在这里不推导为 int&&

转载 作者:太空狗 更新时间:2023-10-29 19:41:31 24 4
gpt4 key购买 nike

下面是函数模板

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

func(4); // 4 is rvalue and T deduces to int

所以我的问题是为什么 T 不推导出 int&& ?

我的意思是如果 T 推导为 int&&

所以 int&& && -> int&& 这对我来说也很有意义!

最佳答案

why T does not deduce to int&& ?

如果模板参数是一个引用,那么在您考虑推导方式之前通常会删除该引用(异常(exception)情况是在针对左值、函数和数组推导时转发引用)。

在这种情况下,T 是根据 4 推导出来的,4 是一个 int,因此 T 推导为整数。结果类型 T&&int&&

请注意,表达式永远不会有引用类型。 4int 类型的右值,它不是 int&&

这与演绎法的一般运作方式一致:

template <class T> void foo(T );
template <class T> void bar(T const& );

foo(4); // calls foo<int>, not foo<int&&>
bar(4); // calls bar<int>, not bar<int const&>

关于c++ - 为什么 T 在这里不推导为 int&&,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39960678/

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