Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::any::emplace

      From cppreference.com
      <cpp‎ |utility‎ |any
       
       
      Utilities library
       
       
      template<class ValueType,class...Args>
      std::decay_t<ValueType>& emplace( Args&&...args);
      (1)(since C++17)
      template<class ValueType,class U,class...Args>
      std::decay_t<ValueType>& emplace(std::initializer_list<U> il, Args&&...args);
      (2)(since C++17)

      Changes the contained object to one of typestd::decay_t<ValueType> constructed from the arguments.

      First destroys the current contained object (if any) byreset(), then:

      1) constructs an object of typestd::decay_t<ValueType>,direct-non-list-initialized fromstd::forward<Args>(args)..., as the contained object.
      2) constructs an object of typestd::decay_t<ValueType>,direct-non-list-initialized fromil,std::forward<Args>(args)..., as the contained object.

      Contents

      [edit]Template parameters

      ValueType - contained value type
      Type requirements
      -
      std::decay_t<ValueType> must meet the requirements ofCopyConstructible.

      [edit]Return value

      A reference to the new contained object.

      [edit]Exceptions

      Throws any exception thrown byT's constructor. If an exception is thrown, the previously contained object (if any) has been destroyed, and*this does not contain a value.

      [edit]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);constauto* 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';constauto* va=std::any_cast<std::vector<char>>(&av);std::for_each(va->cbegin(), va->cend(),[](charconst& c){std::cout<< c;});std::cout<<'\n';}

      Possible output:

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

      [edit]See also

      constructs anany object
      (public member function)[edit]
      destroys contained object
      (public member function)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/utility/any/emplace&oldid=160596"

      [8]ページ先頭

      ©2009-2025 Movatter.jp