Namespaces
Variants

std:: as_const

From cppreference.net
Utilities library
헤더 파일에 정의됨 <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 타입에 대한 lvalue 참조를 형성합니다.
2) rvalue 인수를 허용하지 않기 위해 const rvalue 참조 오버로드가 삭제되었습니다.

목차

가능한 구현

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 should be some kind of string.");
    static_assert(!std::is_same_v<ExprType, std::string>,
                  "ExprType shouldn't be a mutable string.");
}

참고 항목

(C++11)
타입이 const 한정자인지 검사합니다
(클래스 템플릿)
(C++11) (C++11) (C++11)
주어진 타입에 const 및/또는 volatile 지정자를 추가합니다
(클래스 템플릿)
주어진 타입에서 const 및/또는 volatile 지정자를 제거합니다
(클래스 템플릿)
view constant_range 으로 변환합니다
(클래스 템플릿) (레인지 어댑터 객체)