Danra
Danra

Reputation: 9906

Emulating braced list initialization before C++11 STL

In pre C++11's standard library, is there any way to make a class constructor from an std::initializer_list-like object, which would work when with braced list initialization like std::initializer_list does?

I can use C++11 (and even C++14) language features. However, with some projects I'm still using libstdc++ on Xcode, which has no C++11 support, since I need to support OS X 10.6.

Upvotes: 1

Views: 585

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 473407

Your problem is that you have C++11 as a language feature, but the standard library doesn't support it. So you're asking if you can construct containers from initializer_lists.

Yes, but it won't be with the same syntax. This function would be sufficient:

template<typename Container>
Container from_list(std::initializer_list<typename Container::value_type> il)
{
  return Container(il.begin(), il.end());
}

auto vec = from_list<std::vector<int>>({1, 2, 3, 4, 5});

Standard library containers have constructors that work with iterator pairs. So this should work with any such container.

However, this assumes that the standard library actually has the initializer_list type. If it doesn't, then you're out of luck.

Upvotes: 2

Related Questions