C ++ Supply initializer list constructor for class template

I have a Templ template template with a template parameter T, and the Templ class has a data member of type T called obj. I wrote a Variadic constructor template that translates arguments into an obj constructor:

template <class T> class Templ { public: template <class... Args> explicit Templ (Args&&... args) : obj (std::forward<Args>(args)...) { } private: T obj; }; 

Now I realized that type T can be a class with an initialization list constructor, and I want it to be accessible through Templ. So I checked what to do std::list::emplace and std::make_shared . They have a variational function like mine, but they don't have overrides taking an init list. For some reason.

So the first question is: why? I mean, what if I use some T class with init-list ctor and then I use std::list<T> ? Why is there no version in the :: emplace list that accepts the initializer_list file? Maybe there is a good reason why I should do this ... so I want to know.

Also, no matter what the STL does, should I provide the init-list ctor with a good design? I mean, this is exactly the same as the variational ctor, isn't it? Allowing the user to select any type or class T for use with Templ <> and directly call any ctor defined for T. Even if he accepts an init list.

+4
source share
1 answer

The problem with redirecting initializer_list constructors is that all but the most trivial types of arguments are not output ( Templates do not always guess the types of initializer lists ):

 #include <map> template<typename T> struct U { T t; template<typename...A> explicit U(A&&...a): t(std::forward<A>(a)...) {} template<typename L, typename = typename std::enable_if< std::is_constructible<T, std::initializer_list<L>>::value>::type> explicit U(std::initializer_list<L> l): t(l) {} }; U<std::map<int, int>> m{{{0, 1}, {2, 3}}}; // fails, couldn't deduce 'L' 

Since you have to write m{std::initializer_list<...>{...}} in most cases, it makes no sense to specify it only for primitives and, of course, not for the standard one.

If you think that any interesting initializer_list arguments are likely to be for container types, you can look at the approach taken in If necessary, supporting the initializer_list construct for templates, possibly packaging containers .

+2
source

All Articles