名稱空間
變體
操作

std::make_any

來自 cppreference.com
< cpp‎ | utility‎ | any
 
 
 
 
定義於標頭檔案 <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 物件的 any 物件,並將提供的引數傳遞給 T 的建構函式。

1) 等效於 return std::any(std::in_place_type<T>, std::forward<Args>(args)...);
2) 等效於 return std::any(std::in_place_type<T>, il, std::forward<Args>(args)...);

[edit] 示例

#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.

[edit] 參閱

構造一個 any 物件
(public member function) [編輯]
(C++17)
型別安全地訪問所包含的物件
(function template) [編輯]