std::variant::variant(3)
π
std::variant::variant(3) π
okay bestie, welcome to the C++ Standard Libary manual page for std::variant::variant. This is the constructor page, and it is lowkey a whole buffet of ways to make a variant. Since C++17, obviously. β¨
πΈ NAME πΈ
std::variant::variant - std::variant::variant
yes, that is literally the name twice. it's giving constructor-page energy and we respect it. π
β¨ Synopsis β¨
okay so here's the overload lineup. the (since C++17) notes are part of the page, not me being extra. π«Ά
constexpr variant() noexcept(/* see below */); (1)
(since C++17)
constexpr variant( const variant& other ); (2)
(since C++17)
constexpr variant( variant&& other ) noexcept(/* see below */); (3)
(since C++17)
template< class T > (4)
(since C++17)
constexpr variant( T&& t ) noexcept(/* see below */);
template< class T,
class... Args > (5)
(since C++17)
constexpr explicit variant( std::in_place_type_t<T>,
Args&&... args );
template< class T,
class U,
class... Args > (6)
(since C++17)
constexpr explicit variant( std::in_place_type_t<T>,
std::initializer_list<U> il,
Args&&... args );
template< std::size_t I,
class... Args > (7)
(since C++17)
constexpr explicit variant( std::in_place_index_t<I>,
Args&&... args );
template< std::size_t I,
class U,
class... Args > (8)
(since C++17)
constexpr explicit variant( std::in_place_index_t<I>,
std::initializer_list<U> il,
Args&&... args );
okay so the whole mood is: Constructs a new variant object. and here is every single way it does that, no skipping, bestie. π
- Default constructor. Constructs a
variantholding the value-initialized value of the first alternative (index()is zero).- This constructor is
constexprif and only if the value initialization of the alternative typeT_0would satisfy the requirements for aconstexprfunction. - This overload participates in overload resolution only if
std::is_default_constructible_v<T_0>istrue.
- This constructor is
- Copy constructor. If
otheris notvalueless_by_exception, constructs avariantholding the same alternative asotherand direct-initializes the contained value with*std::get_if<other.index()>(std::addressof(other)). Otherwise, initializes avalueless_by_exceptionvariant.- This constructor is defined as deleted unless
std::is_copy_constructible_v<T_i>istruefor allT_iinTypes.... - It is trivial if
std::is_trivially_copy_constructible_v<T_i>istruefor allT_iinTypes....
- This constructor is defined as deleted unless
- Move constructor. If
otheris notvalueless_by_exception, constructs avariantholding the same alternative asotherand direct-initializes the contained value withstd::move(*std::get_if<other.index()>(std::addressof(other))). Otherwise, initializes avalueless_by_exceptionvariant.- This overload participates in overload resolution only if
std::is_move_constructible_v<T_i>istruefor allT_iinTypes.... - It is trivial if
std::is_trivially_move_constructible_v<T_i>istruefor allT_iinTypes....
- This overload participates in overload resolution only if
- Converting constructor. Constructs a
variantholding the alternative typeT_jthat would be selected by overload resolution for the expressionF(std::forward<T>(t))if there was an overload of imaginary functionF(T_i)for eachT_iinTypes..., except that narrowing conversions aren't considered.
Formally:
- An overload
F(T_i)is only considered if the declarationT_i x[] = { std::forward<T>(t) };is valid for some invented variablex. Direct-initializes the contained value as if by direct non-list-initialization fromstd::forward<T>(t). - This overload participates in overload resolution only if
sizeof...(Types) > 0,std::decay_t<T>(until C++20)std::remove_cvref_t<T>(since C++20) is neither the same type asvariant, nor a specialization ofstd::in_place_type_t, nor a specialization ofstd::in_place_index_t,std::is_constructible_v<T_j, T>istrue,- and the expression
F(std::forward<T>(t))(withFbeing the above-mentioned set of imaginary functions) is well formed.
- This constructor is a
constexprconstructor ifT_j's selected constructor is aconstexprconstructor.
std::variant<std::string> v("abc"); // OK
std::variant<std::string, std::string> w("abc"); // ill-formed
std::variant<std::string, const char*> x("abc"); // OK, chooses const char*
std::variant<std::string, bool> y("abc"); // OK, chooses string; bool is not a candidate
std::variant<float, long, double> z = 0; // OK, holds long
// float and double are not candidates
- Constructs a
variantwith the specified alternativeTand initializes the contained value with the argumentsstd::forward<Args>(args)....- If
T's selected constructor is aconstexprconstructor, this constructor is also aconstexprconstructor. - This overload participates in overload resolution only if there is exactly one occurrence of
TinTypes...andstd::is_constructible_v<T, Args...>istrue.
- If
- Constructs a
variantwith the specified alternativeTand initializes the contained value with the argumentsil,std::forward<Args>(args)....- If
T's selected constructor is aconstexprconstructor, this constructor is also aconstexprconstructor. - This overload participates in overload resolution only if there is exactly one occurrence of
TinTypes...andstd::is_constructible_v<T, std::initializer_list<U>&, Args...>istrue.
- If
- Constructs a
variantwith the alternativeT_ispecified by the indexIand initializes the contained value with the argumentsstd::forward<Args>(args)....- If
T_i's selected constructor is aconstexprconstructor, this constructor is also aconstexprconstructor. - This overload participates in overload resolution only if
I < sizeof...(Types)andstd::is_constructible_v<T_i, Args...>istrue.
- If
- Constructs a
variantwith the alternativeT_ispecified by the indexIand initializes the contained value with the argumentsil,std::forward<Args>(args)....- If
T_i's selected constructor is aconstexprconstructor, this constructor is also aconstexprconstructor. - This overload participates in overload resolution only if
I < sizeof...(Types)andstd::is_constructible_v<T_i, std::initializer_list<U>&, Args...>istrue.
- If
πΈ Parameters πΈ
otherβ anothervariantobject whose contained value to copy/movetβ value to initialize the contained value withargs...β arguments to initialize the contained value withilβ initializer list to initialize the contained value with
π₯ Exceptions π₯
- May throw any exception thrown by the value initialization of the first alternative.
noexcept specification:
noexcept(std::is_nothrow_default_constructible_v<T_0>)
- May throw any exception thrown by direct-initializing any
T_iinTypes.... - May throw any exception thrown by move-constructing any
T_iinTypes....
noexcept specification:
noexcept((std::is_nothrow_move_constructible_v<Types> && ...))
- May throw any exception thrown by the initialization of the selected alternative
T_j.
noexcept specification:
noexcept(std::is_nothrow_constructible_v<T_j, T>)
5-8. May throw any exception thrown by calling the selected constructor of the selected alternative.
π Example π
// Run this code
#include <cassert>
#include <iostream>
#include <string>
#include <variant>
#include <vector>
using vector_t = std::vector<int>;
auto& operator<<(auto& out, const vector_t& v)
{
out << "{ ";
for (int e : v)
out << e << ' ';
return out << '}';
}
int main()
{
// value-initializes first alternative
std::variant<int, std::string> var0;
assert(std::holds_alternative<int>(var0) and
var0.index() == 0 and
std::get<int>(var0) == 0);
// initializes first alternative with std::string{"STR"};
std::variant<std::string, int> var1{"STR"};
assert(var1.index() == 0);
std::cout << "1) " << std::get<std::string>(var1) << '\n';
// initializes second alternative with int == 42;
std::variant<std::string, int> var2{42};
assert(std::holds_alternative<int>(var2));
std::cout << "2) " << std::get<int>(var2) << '\n';
// initializes first alternative with std::string{4, 'A'};
std::variant<std::string, vector_t, float> var3
{
std::in_place_type<std::string>, 4, 'A'
};
assert(var3.index() == 0);
std::cout << "3) " << std::get<std::string>(var3) << '\n';
// initializes second alternative with std::vector{1,2,3,4,5};
std::variant<std::string, vector_t, char> var4
{
std::in_place_type<vector_t>, {1, 2, 3, 4, 5}
};
assert(var4.index() == 1);
std::cout << "4) " << std::get<vector_t>(var4) << '\n';
// initializes first alternative with std::string{"ABCDE", 3};
std::variant<std::string, vector_t, bool> var5
{std::in_place_index<0>, "ABCDE", 3};
assert(var5.index() == 0);
std::cout << "5) " << std::get<std::string>(var5) << '\n';
// initializes second alternative with std::vector(4, 42);
std::variant<std::string, vector_t, char> var6
{std::in_place_index<1>, 4, 42};
assert(std::holds_alternative<vector_t>(var6));
std::cout << "6) " << std::get<vector_t>(var6) << '\n';
}
Output:
1) STR
2) 42
3) AAAA
4) { 1 2 3 4 5 }
5) ABC
6) { 42 42 42 42 }
Bestie, if your terminal prints something that looks exactly like that, you did it right β that's the whole vibe check passed, no notes. π
π Defect reports π
Okay so this is the part where the C++ committee admits they fumbled a little and then fixed it retroactively for standards they already published. The following behavior-changing defect reports were applied retroactively to previously published C++ standards. Yes, that means what you think it means β the past got edited. Time travel but make it ISO. π
LWG 2901β applied toC++17- Behavior as published: allocator-aware constructors provided but
variantcan't properly support allocators - Correct behavior: constructors removed
- Behavior as published: allocator-aware constructors provided but
P0739R0β applied toC++17- Behavior as published: converting constructor template interacts poorly with class template argument deduction
- Correct behavior: constraint added
LWG 3024β applied toC++17- Behavior as published: copy constructor doesn't participate in overload resolution if any member type is not copyable
- Correct behavior: defined as deleted instead
P0602R4β applied toC++17- Behavior as published: copy/move constructors may not be trivial even if underlying constructors are trivial
- Correct behavior: required to propagate triviality
P0608R3β applied toC++17- Behavior as published: converting constructor blindly assembles an overload set, leading to unintended conversions
- Correct behavior: narrowing and boolean conversions not considered
P1957R2β applied toC++17- Behavior as published: converting constructor for
booldid not allow implicit conversion - Correct behavior: Pointer to
boolconversion is narrowing and converting constructor has no exception forbool
- Behavior as published: converting constructor for
Ngl, the fact that all six of these say C++17 is sending me. One standard, six glow-ups. She's been through it. π«Ά
π Category π
- conditionally noexcept β¨
Like, some of the constructors are noexcept and some aren't β it depends on the vibe (and by vibe I mean the underlying types). Conditionally is doing a lot of heavy lifting in that sentence, iykyk. π
And that's the page, bestie! πΈ This little masterpiece is straight from http://cppreference.com, dated 2024.06.10, and it's the man page for std::variant::variant(3). Go construct something iconic. Periodt. ππ¦
π¦ 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