C++1zから<utility>ヘッダに、as_const()関数テンプレートが追加されます。
この関数は、引数として渡されたオブジェクトをconstにします。その際、オブジェクトのコピーは発生しません。また、この関数に右辺値は渡せません。
#include <iostream> #include <utility> int main() { std::string a = "hello"; const std::string& b = std::as_const(a); // 非constの左辺値をconstにする const std::string& c = std::as_const(b); // const左辺値をそのまま返す // const std::string& d = std::as_const(std::move(a)); // コンパイルエラー }
この関数は、constと非constのオーバーロードがあった場合に、const版を意図して呼び出すことを目的としているのだそうです。
言語組み込みのconst_cast命令はconst (とvolatile)の付け外しができますが、こちらはconstを付けることしかできません。
宣言
// <utility> namespace std { template <class T> constexpr add_const_t<T>& as_const(T& t) noexcept; template <class T> void as_const(const T&&) = delete; }
参照
- N4380 Constant View: A proposal for a
std::as_consthelper function template - P0007R0 Constant View: A proposal for a
std::as_consthelper function template - P0007R1 Constant View: A proposal for a
std::as_consthelper function template
お断り
この記事の内容は、C++1zが正式リリースされる際には変更される可能性があります。正式リリース後には、C++日本語リファレンスサイトcpprefjpの以下の階層の下に解説ページを用意する予定です。