any_make_any

any_make_any (std::any 객체 생성 함수)

std::make_any는 주어진 인자들을 T의 생성자에 전달하여 T 타입 객체를 담는 std::any 객체를 생성하는 헬퍼 함수예요. C++17부터 사용할 수 있어요. 이 함수를 사용하면 std::any를 직접 만들 때보다 코드가 간결해져요.

출처: cppreference

본문

함수 정의

<any> 헤더에 정의됨
template < class T , class ... Args > std :: any make_any ( Args && ... args ); (1) (C++17부터)
template < class T , class U , class ... Args > std :: any make_any ( std :: initializer_list < U > il , Args && ... args ); (2) (C++17부터)

이 함수는 T 타입의 객체를 담는 std::any 객체를 생성해요. 제공된 인자들은 T의 생성자에 그대로 전달돼요. (2)번 오버로드는 initializer_list를 첫 번째 인자로 받아서 T의 생성자에 전달해요.

예제

#include <any>
#include <complex>
#include <functional>
#include <iostream>
#include <string>

int main()
{
    auto a0 = std::make_any<std::string>("Hello, std::any!\n");
    auto a1 = std::make_any<std::complex<double>>(0.1, 2.3);

    std::cout << std::any_cast<std::string&>(a0);
    std::cout << std::any_cast<std::complex<double>&>(a1) << '\n';

    using lambda = std::function<void(void)>;

    // Put a lambda into std::any. Attempt #1 (failed).
    std::any a2 = [] { std::cout << "Lambda #1.\n"; };
    std::cout << "a2.type() = \"" << a2.type().name() << "\"\n";
    
    // any_cast casts to <void(void)> but actual type is not
    // a std::function..., but ~ main::{lambda()#1}, and it is
    // unique for each lambda. So, this throws...
    try
    {
        std::any_cast<lambda>(a2)();
    }
    catch (std::bad_any_cast const& ex)
    {
        std::cout << ex.what() << '\n';
    }

    // Put a lambda into std::any. Attempt #2 (successful).
    auto a3 = std::make_any<lambda>([] { std::cout << "Lambda #2.\n"; });
    std::cout << "a3.type() = \"" << a3.type().name() << "\"\n";
    std::any_cast<lambda>(a3)();
}

가능한 출력

Hello, std::any!
(0.1,2.3)
a2.type() = "Z4mainEUlvE_"
bad any_cast
a3.type() = "St8functionIFvvEE"
Lambda #2.

참고 항목

(생성자) any 객체를 생성해요 (public 멤버 함수) [edit]
any_cast (C++17) 포함된 객체에 타입 안전하게 접근해요 (함수 템플릿) [edit]

더 알아보기 (Learn more)

cppreference