名前空間
変種
操作

std::as_const

提供: cppreference.com
< cpp‎ | utility
 
 
ユーティリティライブラリ
汎用ユーティリティ
日付と時間
関数オブジェクト
書式化ライブラリ (C++20)
(C++11)
関係演算子 (C++20で非推奨)
整数比較関数
(C++20)
スワップと型操作
(C++14)
(C++11)
(C++11)
(C++11)
as_const
(C++17)
一般的な語彙の型
(C++11)
(C++17)
(C++17)
(C++17)
(C++17)

初等文字列変換
(C++17)
(C++17)
 
ヘッダ <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;
}

[編集]

#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." );
}


[編集] 関連項目

(C++11)
型が const 修飾されているかどうか調べます
(クラステンプレート) [edit]
(C++11)(C++11)(C++11)
指定された型に const, volatile またはその両方の指定子を追加します
(クラステンプレート) [edit]
指定された型から const, volatile またはその両方の指定子を削除します
(クラステンプレート) [edit]