std::any::emplace(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸ’… std::any::emplace(3) β€” C++ Standard Library

okay bestie, gather round, because this one is so useful and also lowkey the most "i contain multitudes" function in the whole standard library. it's std::any::emplace, from the C++ Standard Library, and it's giving main character energy ✨


🌸 NAME 🌸

std::any::emplace β€” std::any::emplace πŸ’–

(yes, the name is the name, we love a self-titled icon)


✨ Synopsis ✨

template< class ValueType, class... Args >
(1) (since C++17)
std::decay_t<ValueType>& emplace( Args&&... args );
template< class ValueType, class U, class... Args >
std::decay_t<ValueType>& emplace( std::initializer_list<U> il,
(2) (since C++17)
Args&&... args );

So what's the vibe? It changes the contained object to one of type std::decay_t<ValueType>, constructed from the arguments. That's it, that's the whole personality 🫢

First it destroys the current contained object (if any) by reset(), then:

  1. constructs an object of type std::decay_t<ValueType>, direct-non-list-initialized from std::forward<Args>(args)..., as the contained object.
    • This overload participates in overload resolution only if std::is_constructible_v<std::decay_t<ValueType>, Args...> and std::is_copy_constructible_v<std::decay_t<ValueType>> are both true.
  2. constructs an object of type std::decay_t<ValueType>, direct-non-list-initialized from il, std::forward<Args>(args)..., as the contained object.
    • This overload participates in overload resolution only if std::is_constructible_v<std::decay_t<ValueType>, std::initializer_list<U>&, Args...> and std::is_copy_constructible_v<std::decay_t<ValueType>> are both true.
⚠️ important note from the group chat: it direct-non-list-initializes, so no sneaky brace-init business happening behind the scenes. and remember the old object gets nuked before the new one is built β€” we'll get to why that matters in a sec 😭

πŸŽ€ Template parameters πŸŽ€

  • ValueType β€” contained value type (that's the type you're stuffing into the any, bestie)

πŸ¦‹ Type requirements πŸ¦‹

  • std::decay_t<ValueType> must meet the requirements of CopyConstructible.

no cap, that's a hard requirement. it's non-negotiable, it's the dress code, it's the vibe check πŸ’…


🌈 Return value 🌈

A reference to the new contained object. you get a hand-delivered reference to your shiny new thing, go off king πŸ‘‘


πŸ’€ Exceptions πŸ’€

Throws any exception thrown by T's constructor. and if an exception is thrown?

okay so this is the part where you gotta pay attention πŸ™ˆ β€” the previously contained object (if any) has already been destroyed, and *this does not contain a value.

🚨 so like, there's no undo button. the old object is gone gone. if the constructor throws, you're left with an empty any. no strong exception guarantee for you, bestie.

πŸ“ Example πŸ“

// Run this code

#include <algorithm>
#include <any>
#include <iostream>
#include <string>
#include <vector>

class Star
{
    std::string name;
    int id;

public:
    Star(std::string name, int id) : name{name}, id{id}
    {
        std::cout << "Star::Star(string, int)\n";
    }

    void print() const
    {
        std::cout << "Star{\"" << name << "\" : " << id << "};\n";
    }
};

int main()
{
    std::any celestial;
    // (1) emplace(Args&&... args);
    celestial.emplace<Star>("Procyon", 2943);
    const auto* star = std::any_cast<Star>(&celestial);
    star->print();

    std::any av;
    // (2) emplace(std::initializer_list<U> il, Args&&... args);
    av.emplace<std::vector<char>>({'C', '+', '+', '1', '7'} /* no args
*/);
    std::cout << av.type().name() << '\n';
    const auto* va = std::any_cast<std::vector<char>>(&av);
    std::for_each(va->cbegin(), va->cend(), [](char const& c) {
std::cout << c; });
    std::cout << '\n';
}

look at her go 😭✈️ the first one's the plain args overload, the second one's the initializer_list overload with literally zero extra args, and she still slays.


🌟 Possible output 🌟

Star::Star(string, int)
Star{"Procyon" : 2943};
St6vectorIcSaIcEE
C++17

(the St6vectorIcSaIcEE is just the mangled type name being its weird little self, don't worry about it πŸ’€)


πŸ‘‘ See also πŸ‘‘

  • constructor β€” constructs an any object (public member function)
  • reset β€” destroys contained object (public member function)

that's the whole page, bestie, you're officially an emplace expert now, go build something unhinged πŸ’œ

source: cppreference.com Β· version 2024.06.10

xoxo, and remember β€” emplace responsibly, because the old value is never coming back πŸŽ€πŸ’…βœ¨

πŸ“¦ where this page comes from