首页 > 解决方案 > 通用初始化——向量的填充构造函数

问题描述

是否可以在 c++17 中调用此构造函数

 vector( size_type count, const T& value, const Allocator& alloc = Allocator());

使用统一初始化vector<int>?似乎std::vector<int> data{10, 20}创建了一个大小为 2 的向量。

标签: c++initializationc++17stdvector

解决方案


可能吗?当然。

struct size_type {
    template<class T, std::enable_if_t<std::is_same_v<T, std::vector<int>::size_type>>* = nullptr>
    operator T() const {
        return val;
    }
    std::vector<int>::size_type val;
};

std::vector<int> vi {size_type{10}, 4}; // vector of 10 ints with value 4

只要value_type不是与size_type.

你应该这样做吗?不。


推荐阅读