std:: as_const
From cppreference.net
|
定义于头文件
<utility>
|
||
|
template
<
class
T
>
constexpr std:: add_const_t < T > & as_const ( T & t ) noexcept ; |
(1) | (C++17 起) |
|
template
<
class
T
>
void as_const ( const T && ) = delete ; |
(2) | (C++17 起) |
1)
形成指向
t
的 const 类型的左值引用。
2)
const 右值引用重载被删除,以禁止右值参数。
目录 |
可能的实现
template<class T> constexpr std::add_const_t<T>& as_const(T& t) noexcept { return t; } |
注释
| 功能测试 宏 | 值 | 标准 | 功能 |
|---|---|---|---|
__cpp_lib_as_const
|
201510L
|
(C++17) |
std::as_const
|
示例
运行此代码
#include <cassert> #include <string> #include <type_traits> #include <utility> int main() { std::string mutableString = "Hello World!"; auto&& constRef = std::as_const(mutableString); mutableString.clear(); // 正确 // constRef.clear(); // 错误:'constRef' 具有 'const' 限定, // 但 'clear' 未标记为 const assert(&constRef == &mutableString); assert(&std::as_const(mutableString) == &mutableString); using ExprType = std::remove_reference_t<decltype(std::as_const(mutableString))>; static_assert(std::is_same_v<std::remove_const_t<ExprType>, std::string>, "ExprType 应为某种字符串类型。"); static_assert(!std::is_same_v<ExprType, std::string>, "ExprType 不应为可变字符串。"); }
参见
|
(C++11)
|
检查类型是否具有 const 限定符
(类模板) |
|
(C++11)
(C++11)
(C++11)
|
向给定类型添加
const
和/或
volatile
限定符
(类模板) |
|
(C++11)
(C++11)
(C++11)
|
从给定类型移除
const
和/或
volatile
限定符
(类模板) |
将
view
转换为
constant_range
(类模板) (范围适配器对象) |