std::as_const
提供: cppreference.com
ヘッダ <utility> で定義 | ||
template<class T> constexprstd::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>constexprstd::add_const_t<T>& as_const(T& t)noexcept{return t;} |
[編集]例
Run this code
#include <string>#include <cassert>#include <utility>#include <type_traits> int main(){std::string mutableString ="Hello World!";conststd::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.");}
[編集]関連項目
(C++11) | 型が const 修飾されているかどうか調べます (クラステンプレート) |
(C++11)(C++11)(C++11) | 指定された型に const, volatile またはその両方の指定子を追加します (クラステンプレート) |
(C++11)(C++11)(C++11) | 指定された型から const, volatile またはその両方の指定子を削除します (クラステンプレート) |