简体   繁体   English

C ++ std :: add_const无法正常工作?

[英]C++ std::add_const not working correctly?

I tried following code: 我尝试了以下代码:

#include <iostream>
#include <type_traits>
int main() { 
    std::cout << std::is_const<std::add_const<int*&>::type>::value;
}

and the output is 0. Is this correct behaviour? 并且输出为0。这是正确的行为吗?

References cannot be const -qualified, so std::add_const is a no-op for reference types. 引用不能是const限定的,因此std::add_const是引用类型的无操作。

It makes sense when you think about it (and is clearly stated in standard library reference material ), but is potentially surprising at first glance. 当您考虑它时(它在标准库参考资料中有明确说明)是有道理的,但是乍一看可能会令人惊讶。

std::add_const does not quite do what you think it does: std::add_const并没有完全按照您的想法做:

If T is a reference , function, or top-level const-qualified type, then type shall name the same type as T , otherwise T const. 如果T是引用 ,函数或顶级const限定的类型, 则type必须与T命名相同的类型 ,否则应命名 T const。

(From 20.10.7.1 Const-volatile modifications Table 52 in N4140, emphasis mine) (摘自N4140中的20.10.7.1常量修改表52)

As you can see, std::add_const does not add a const for reference types. 如您所见, std::add_const不会为引用类型添加const

But what would a constant reference be in the first place, they are immutable anyways. 但是,始终将引用放在首位的是,它们始终是不变的。 (Not to be confused with reference to const vs. reference to non- const .) (不要将const与非const混淆。)

From the std::add_const documentation : std::add_const文档中:

http://en.cppreference.com/w/cpp/types/add_cv http://en.cppreference.com/w/cpp/types/add_cv

Provides the member typedef type which is the same as T, except it has a cv-qualifier added (unless T is a function, a reference , or already has this cv-qualifier) 提供与T相同的成员typedef类型,除了它添加了cv限定符(除非T是一个函数, 一个引用或已经具有此cv限定符)

If we check the cpprefernece documentation for std::add_const we see it says: 如果检查cpprefernece文档中的std :: add_const,我们会看到它说:

Provides the member typedef type which is the same as T, except it has a cv-qualifier added ( unless T is a function, a reference, or already has this cv-qualifier ) 提供与T相同的成员typedef类型,除了它添加了cv-qualifier( 除非T是函数,引用或已经具有此cv-qualifier

this is consistent with the draft C++ standard section 20.10.7.1 Const-volatile modifications which says the following for add_const : 这与C ++标准草案第20.10.7.1节Const-volatile修改一致,该修改对add_const表示以下add_const

If T is a reference, function, or top-level const-qualified type, then type shall name the same type as T, otherwise T const. 如果T是引用,函数或顶级const限定类型,则type必须与T命名相同的类型,否则应为T const。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM