Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::get_if(std::variant)

      From cppreference.com
      <cpp‎ |utility‎ |variant
       
       
      Utilities library
       
       
      Defined in header<variant>
      (1)(since C++17)
      template<std::size_t I,class...Types>

      constexprstd::add_pointer_t<std::variant_alternative_t<I,std::variant<Types...>>>

          get_if(std::variant<Types...>* pv)noexcept;
      template<std::size_t I,class...Types>

      constexprstd::add_pointer_t<conststd::variant_alternative_t<I,std::variant<Types...>>>

          get_if(conststd::variant<Types...>* pv)noexcept;
      (2)(since C++17)
      template<class T,class...Types>

      constexprstd::add_pointer_t<T>

          get_if(std::variant<Types...>* pv)noexcept;
      template<class T,class...Types>

      constexprstd::add_pointer_t<const T>

          get_if(conststd::variant<Types...>* pv)noexcept;
      1) Index-based non-throwing accessor: Ifpv is not a null pointer andpv->index()== I, returns a pointer to the value stored in the variant pointed to bypv. Otherwise, returns a null pointer value. The call is ill-formed ifI is not a valid index in the variant.
      2) Type-based non-throwing accessor: Equivalent to(1) withI being the zero-based index ofT inTypes.... The call is ill-formed ifT is not a unique element ofTypes....

      Contents

      [edit]Template parameters

      I - index to look up
      Type - unique type to look up

      [edit]Parameters

      pv - pointer to a variant

      [edit]Return value

      Pointer to the value stored in the pointed-to variant or null pointer on error.

      [edit]Example

      Run this code
      #include <iostream>#include <variant> int main(){auto check_value=[](conststd::variant<int,float>& v){if(constint* pval= std::get_if<int>(&v))std::cout<<"variant value: "<<*pval<<'\n';elsestd::cout<<"failed to get value!"<<'\n';}; std::variant<int,float> v{12}, w{3.f};    check_value(v);    check_value(w);}

      Output:

      variant value: 12failed to get value!

      [edit]See also

      reads the value of the variant given the index or the type (if the type is unique), throws on error
      (function template)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/utility/variant/get_if&oldid=172847"

      [8]ページ先頭

      ©2009-2025 Movatter.jp