Skip to content

Last updated:2026-10-12

C++17 std::variant

I recently came up with some interesting questions and put together a little summary - how many of them can you answer?

Note: the complete answers will be revealed in the members' community.

Question 1: How many types' constructors does the std::variant constructor invoke - one, two, or n?

std::variant<std::string, int> a1;
std::variant<X, Y> a2;

Related questions:

  1. What is the default construction behavior of std::variant?
  2. What happens when the types contained in a std::variant do not have a default constructor?
  3. How do you specify the initial value type of a std::variant?

Question 2: Can the following code run correctly? If it can, explain why; otherwise give several solutions.

struct X {
    X(int v) : v_(v) {}
    int v_;
};

struct Y {
    Y(double v) : v_(v) {}
    double v_;
};

std::variant<X, Y> a1;

Related questions:

  1. How do you add a type with a default constructor to a std::variant?
  2. What are the solutions when there is no default constructor in the std::variant type list?
  3. How do you explicitly construct a std::variant to avoid default construction problems?

Question 3: What is monostate, and what problem does it solve?

Related questions:

  1. How do you use std::monostate in a std::variant?
  2. What impact does the introduction of std::monostate have on the design of std::variant?
  3. In what situations is it appropriate to use std::monostate?

Question 4: What are the differences between defer_lock_t, try_to_lock_t, and adopt_lock_t? In which scenarios are they used?

Related questions:

  1. What are the usage scenarios and implementation mechanism of defer_lock_t?
  2. How does try_to_lock_t handle attempting to lock a mutex?
  3. What should be noted when adopt_lock_t takes ownership of an already-held lock?

Comments