简体   繁体   中英

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?

References cannot be const -qualified, so std::add_const is a no-op for reference types.

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:

If T is a reference , function, or top-level const-qualified type, then type shall name the same type as T , otherwise T const.

(From 20.10.7.1 Const-volatile modifications Table 52 in N4140, emphasis mine)

As you can see, std::add_const does not add a const for reference types.

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 .)

From the std::add_const documentation :

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)

If we check the cpprefernece documentation for std::add_const we see it says:

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 )

this is consistent with the draft C++ standard section 20.10.7.1 Const-volatile modifications which says the following for 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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