Namespaces
Variants

std::any:: emplace

From cppreference.net
Utilities library
template < class ValueType, class ... Args >
std:: decay_t < ValueType > & emplace ( Args && ... args ) ;
(1) (seit C++17)
template < class ValueType, class U, class ... Args >
std:: decay_t < ValueType > & emplace ( std:: initializer_list < U > il, Args && ... args ) ;
(2) (seit C++17)

Ändert das enthaltene Objekt zu einem Objekt vom Typ std:: decay_t < ValueType > , das aus den Argumenten konstruiert wird.

Zerstört zunächst das aktuell enthaltene Objekt (falls vorhanden) durch reset() , dann:

1) konstruiert ein Objekt vom Typ std:: decay_t < ValueType > , direkt-nicht-Listen-initialisiert aus std:: forward < Args > ( args ) ... , als enthaltenes Objekt.
2) konstruiert ein Objekt vom Typ std:: decay_t < ValueType > , direkt-nicht-Listen-initialisiert aus il, std:: forward < Args > ( args ) ... , als das enthaltene Objekt.

Inhaltsverzeichnis

Template-Parameter

ValueType - Typ des enthaltenen Werts
Typanforderungen
-
std::decay_t<ValueType> muss die Anforderungen von CopyConstructible erfüllen.

Rückgabewert

Eine Referenz auf das neue enthaltene Objekt.

Ausnahmen

Wirft jede Ausnahme, die vom Konstruktor von T geworfen wird. Wenn eine Ausnahme geworfen wird, wurde das zuvor enthaltene Objekt (falls vorhanden) zerstört, und * this enthält keinen Wert.

Beispiel

#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';
}

Mögliche Ausgabe:

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

Siehe auch

konstruiert ein any Objekt
(öffentliche Elementfunktion)
zerstört das enthaltene Objekt
(öffentliche Elementfunktion)