C++ Supply initializer-list constructor for class template

痞子三分冷 提交于 2019-12-01 06:06:53
ecatmur

The problem with forwarding initializer_list constructors is that all but the most trivial argument types aren't deducible (Templates don't always guess initializer list types):

#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'd have to write m{std::initializer_list<...>{...}} in most cases, there's not much point providing it just for primitives, and certainly not for the standard to do so.

If you think that any interesting initializer_list arguments are likely to be for container types, you could look at the approach taken in Optionally supporting initializer_list construction for templates maybe wrapping containers.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!