How to design classes with constructor taking a std::initializer_list?
I would take the same approach that the standard took with piecewise_construct
in pair
or defer_lock
in unique_lock
: using tags on the constructor:
struct n_copies_of_t { };
constexpr n_copies_of_t n_copies_of{};
template <typename T, typename A = std::allocator<T>>
class vector {
public:
vector(std::initializer_list<T>);
vector(n_copies_of_t, size_type, const T& = T(), const A& = A());
// etc.
};
That way:
std::vector<int> v{10, 20}; // vector of 2 elems
std::vector<int> v2(10, 20); // error - not a valid ctor
std::vector<int> v3(n_copies_of, 10, 20); // 10 elements, all with value 20.
Plus, I always forget if it's 10 elements of value 20 or 20 elements of value 10, so the tag helps clarify that.