Somethimes i need sets (or any other container) of 1 element of user's type and create them this way:
boost::assign::list_of(typeVariable).convert_to_container<std::unordered_set<UserType> >()
Do anyone know more beautiful way?
PS: For example we have any business logic API, which searches for elements, and it takes set (or another container) of types for selection. Different users have access to different types. Also we can select any one type for filtering, and in this case we will take this one type from filtering options.
So i just wanted the simple way to write code in 1 line. My current version is:
getElements(filter.type != UNDEFINED
? boost::assign::list_of(filter.type).convert_to_container<std::set<UserType> >()
: std::set<UserType>(allowedTypes.begin(), allowedTypes.end()))
Unfortunately, in C++ you cannot simply use auto set={2.3};
, because this creates not a set, but an std::initializer_list
. However, with the help of
template<typename Tp>
inline std::unordered_set<Tp> make_set(Tp const&x)
{ return {x}; }
you can use
auto set = make_set(2.3);
without the need to specify the type of set
explicitly (as in another answer).
You can extend make_set()
to take any number of arguments of the same type (I leave this as an exercise for you), but it's easier to add an overload taking an initializer list
template<typename Tp>
std::unordered_set<Tp> make_set(std::initializer_list<Tp> const&x)
{ return {x}; }
when
auto set = make_set({2.3,3.1});
creates an std::unordered_set<double>
with two elements.
Edit It seems to me that there is no pure std
solution which avoids explicitly naming the type of the set (std::unordered_set<possibly_templated_user_type>
). Thus, make_set()
(or similar) is the only such solution and, arguably, should be provided by std
(similar to std::make_unique()
and std::make_shared()
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With