C++ std::add_const 无法正常工作?
C++ std::add_const not working correctly?
我尝试了以下代码:
#include <iostream>
#include <type_traits>
int main() {
std::cout << std::is_const<std::add_const<int*&>::type>::value;
}
并且输出为 0。这是正确的行为吗?
来自 std::add_const
文档:
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)
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.
(来自 20.10.7.1 Const-volatile 修改 Table N4140 中的 52,强调我的)
如您所见,std::add_const
没有为引用类型添加 const
。
但是常量引用首先是什么,它们无论如何都是不可变的。 (不要混淆参考 const
与参考非 const
。)
如果我们检查 std::add_const 的 cpprefernece 文档,我们会看到它说:
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)
这与 C++ 标准草案第 20.10.7.1 节 Const-volatile 修改一致,其中对 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.
引用不能是 const
限定的,因此 std::add_const
是引用类型的空操作。
当你考虑它时(和 is clearly stated in standard library reference material),它是有道理的,但乍一看可能会令人惊讶。
我尝试了以下代码:
#include <iostream>
#include <type_traits>
int main() {
std::cout << std::is_const<std::add_const<int*&>::type>::value;
}
并且输出为 0。这是正确的行为吗?
来自 std::add_const
文档:
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)
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.
(来自 20.10.7.1 Const-volatile 修改 Table N4140 中的 52,强调我的)
如您所见,std::add_const
没有为引用类型添加 const
。
但是常量引用首先是什么,它们无论如何都是不可变的。 (不要混淆参考 const
与参考非 const
。)
如果我们检查 std::add_const 的 cpprefernece 文档,我们会看到它说:
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)
这与 C++ 标准草案第 20.10.7.1 节 Const-volatile 修改一致,其中对 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.
引用不能是 const
限定的,因此 std::add_const
是引用类型的空操作。
当你考虑它时(和 is clearly stated in standard library reference material),它是有道理的,但乍一看可能会令人惊讶。