gpt4 book ai didi

c++ - 模板推导和 decltype(T) 如何作用于引用?

转载 作者:太空狗 更新时间:2023-10-29 20:51:17 24 4
gpt4 key购买 nike

我正在学习 C++ 中的模板。我不明白的是:给定一个类型 X ,并创建一个对象 X a; ,如果我定义对 a 的引用通过 X& b = a; , 然后 std::is_reference<decltype(b)>::value返回真。但是,如果我将 b 作为模板函数的参数,推导的类型不是引用。

#include <iostream>

class X {};

template<typename T>
void
F(T t)
{
if (std::is_reference<T>::value)
std::cout << "T is a reference" << std::endl;
}

int
main()
{
X a;
X &b = a;
std::cout << std::is_reference<decltype(b)>::value << std::endl; // return true
F(b); //return false
}

我的问题是为什么代码会这样工作。

最佳答案

b 的类型作为表达式X 由于[expr.type]/1 :

If an expression initially has the type “reference to T” ([dcl.ref], [dcl.init.ref]), the type is adjusted to T prior to any further analysis.

所以T被推导为X。但是 decltype(b) 不仅仅是 b 的类型作为表达式。根据[dcl.type.simple]/4 (不相关的部分被我删掉了):

For an expression e, the type denoted by decltype(e) is defined as follows:

  • ...

  • otherwise, if e is an unparenthesized id-expression or an unparenthesized class member access, decltype(e) is the type of the entity named by e. ...

  • ...

请注意,它是由b(即X&)命名的实体的类型,而不是表达式b的类型。

关于c++ - 模板推导和 decltype(T) 如何作用于引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50821862/

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