std::make_any(3)
πΈ NAME πΈ
okay bestie, the name line is literally std::make_any - std::make_any, and this is the std::make_any(3) page from the C++ Standard Libary π. We're so back.
β¨ Synopsis β¨
Defined in header <any>.
template< class T, class... Args > (1)
(since C++17)
std::any make_any( Args&&... args );
template< class T, class U, class... Args > (2)
(since C++17)
std::any make_any( std::initializer_list<U> il, Args&&... args );
So what's the vibe? It constructs an any object containing an object of type T, passing the provided arguments to T's constructor. Iconic behavior, no cap.
- Equivalent to
return std::any(std::in_place_type<T>, std::forward<Args>(args)...); - Equivalent to
return std::any(std::in_place_type<T>, il, std::forward<Args>(args)...);
π¦ Example π¦
// Run this code β yes bestie, go run it π
#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)();
}
π« Possible output π«
Hello, std::any!
(0.1,2.3)
a2.type() = "Z4mainEUlvE_"
bad any_cast
a3.type() = "St8functionIFvvEE"
Lambda #2.
π See also π
constructorβ constructs ananyobject (public member function)any_castβ type-safe access to the contained object(C++17)(function template)
okay bye bestie, mwah π β source/version: http://cppreference.com, date: 2024.06.10, page: std::make_any(3). π«Ά
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms