std::as_const_C++中文网
| 定义于头文件 |
||
| template <class T> |
(1) | (C++17 起) |
| template <class T> |
(2) | (C++17 起) |
1) 将左值引用组成 t 的 const 类型
2) 删除 const 右值引用重载,以禁止右值参数
可能的实现
template <class T> constexpr std::add_const_t<T>& as_const(T& t) noexcept { return t; }
示例
#include <string> #include <cassert> #include <utility> #include <type_traits> int main() { std::string mutableString = "Hello World!"; const std::string& constView = std::as_const(mutableString); assert( &constView == &mutableString ); assert( &std::as_const( mutableString ) == &mutableString ); using WhatTypeIsIt = std::remove_reference_t<decltype(std::as_const(mutableString))>; static_assert(std::is_same<std::remove_const_t<WhatTypeIsIt>, std::string>::value, "WhatTypeIsIt should be some kind of string." ); static_assert(!std::is_same< WhatTypeIsIt, std::string >::value, "WhatTypeIsIt shouldn't be a mutable string." ); }