in_place_tin_place_index_tin_place_type_t结构

C++17 中引入。

in_place_tin_place_type_tin_place_index_t标记类型用于选择以所需方式创建对象的重载构造函数。 对于使用这些标记类型的类型,它们还可以帮助避免临时复制或移动操作。

语法

struct in_place_t
{
    explicit in_place_t() = default;
};

inline constexpr in_place_t in_place{};

template <class T>
struct in_place_type_t
{
    explicit in_place_type_t() = default;
};

template <class T>
constexpr in_place_type_t<T> in_place_type{};

template <size_t I>
struct in_place_index_t
{
    explicit in_place_index_t() = default;
};

template <size_t I>
constexpr in_place_index_t<I> in_place_index{};

参数

I
在其中创建对象的索引。

T
要创建的对象的类型。

注解

  • in_place_t 指示对象的就地构造。 用于在 . 中 std::optional就地创建对象。
  • in_place_type_t 指示特定类型的对象的就地构造。 它很有用, std::any 因为 std::any 可以保存任何类型的类型,因此我们需要指定它保留的类型。
  • in_place_index_t 指示特定索引处对象的就地构造。 用于 std::variant 指定创建对象的索引。

以下类类型在其构造函数中使用这些结构:expectedoptional、或 single_viewany variant

示例

#include <iostream>
#include <optional>
#include <any>
#include <variant>

// compile with /std:c++17

struct MyStruct
{
    double value;
    MyStruct(double v0, double v1 = 0) : value(v0 + v1) {}
};

int main()
{
    // Construct a MyStruct directly inside opt
    std::optional<MyStruct> opt(std::in_place, 29.0, 13.0);

    // Construct a MyStruct object inside an any object
    std::any a(std::in_place_type<MyStruct>, 3.14);

    // Construct a MyStruct object inside a vector at index 0
    std::variant<MyStruct, int> v(std::in_place_index<0>, 2.718);

    if (opt)
    {
        std::cout << opt->value << ", ";
    }

    std::cout << std::any_cast<MyStruct>(a).value << ", "
              << std::get<0>(v).value;

    return 0;
}
42, 3.14, 2.718

要求

标头<utility>

命名空间std

编译器选项:/std:c++17或更高版本。