gpt4 book ai didi

c++ - is_const 不能按预期工作以供引用

转载 作者:IT老高 更新时间:2023-10-28 22:26:43 26 4
gpt4 key购买 nike

我写了一个测试程序:

#include <iostream> 
#include <type_traits>
using namespace std;
template<class T>
void f(T&& t)
{
cout<<is_const<T>()<<endl;
//++t;
}
int main() {
const int i=0;
f(i);
return 0;
}

它输出“0”,表明 T 不是 const!这很奇怪。然后我修改了 f:

template<class T> 
void f(T&& t)
{
cout<<is_const<T>()<<endl;
++t;
}

然后是编译器错误,说我们正在修改只读t。那么 t 是否可以修改?我的程序中是否存在任何错误假设?

最佳答案

std::is_const :

If T is a const-qualified type (that is, const, or const volatile), provides the member constant value equal true. For any other type, value is false.

t 被声明为 forwarding references .所以对于你的代码,T会被推导出为const int&,这是一个引用。引用不能是 const-qualified,它本身不会是 const。准确地说,没有const reference(即int& const),因为引用无法再次反弹。 const int&const int 的引用;并注意 t 因此不可修改。

根据标准,$8.3.2/1 References [dcl.ref]

Cv-qualified references are ill-formed except when the cv-qualifiers are introduced through the use of a typedef-name ([dcl.typedef], [temp.param]) or decltype-specifier ([dcl.type.simple]), in which case the cv-qualifiers are ignored.

更多示例来自 cppreference :

std::cout << std::is_const<int>::value << '\n'; // false
std::cout << std::is_const<const int>::value << '\n'; // true
std::cout << std::is_const<const int*>::value << '\n'; // false
std::cout << std::is_const<int* const>::value << '\n'; // true
std::cout << std::is_const<const int&>::value << '\n'; // false

关于c++ - is_const 不能按预期工作以供引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37202716/

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