How to emulate C array initialization “int arr[] =

2018-12-31 22:12发布

(Note: This question is about not having to specify the number of elements and still allow nested types to be directly initialized.)
This question discusses the uses left for a C array like int arr[20];. On his answer, @James Kanze shows one of the last strongholds of C arrays, it's unique initialization characteristics:

int arr[] = { 1, 3, 3, 7, 0, 4, 2, 0, 3, 1, 4, 1, 5, 9 };

We don't have to specify the number of elements, hooray! Now iterate over it with the C++11 functions std::begin and std::end from <iterator> (or your own variants) and you never need to even think of its size.

Now, are there any (possibly TMP) ways to achieve the same with std::array? Use of macros allowed to make it look nicer. :)

??? std_array = { "here", "be", "elements" };

Edit: Intermediate version, compiled from various answers, looks like this:

#include <array>
#include <utility>

template<class T, class... Tail, class Elem = typename std::decay<T>::type>
std::array<Elem,1+sizeof...(Tail)> make_array(T&& head, Tail&&... values)
{
  return { std::forward<T>(head), std::forward<Tail>(values)... };
}

// in code
auto std_array = make_array(1,2,3,4,5);

And employs all kind of cool C++11 stuff:

  • Variadic Templates
  • sizeof...
  • rvalue references
  • perfect forwarding
  • std::array, of course
  • uniform initialization
  • omitting the return type with uniform initialization
  • type inference (auto)

And an example can be found here.

However, as @Johannes points out in the comment on @Xaade's answer, you can't initialize nested types with such a function. Example:

struct A{ int a; int b; };

// C syntax
A arr[] = { {1,2}, {3,4} };
// using std::array
??? std_array = { {1,2}, {3,4} };

Also, the number of initializers is limited to the number of function and template arguments supported by the implementation.

9条回答
栀子花@的思念
2楼-- · 2018-12-31 22:12

Best I can think of is:

template<class T, class... Tail>
auto make_array(T head, Tail... tail) -> std::array<T, 1 + sizeof...(Tail)>
{
     std::array<T, 1 + sizeof...(Tail)> a = { head, tail ... };
     return a;
}

auto a = make_array(1, 2, 3);

However, this requires the compiler to do NRVO, and then also skip the copy of returned value (which is also legal but not required). In practice, I would expect any C++ compiler to be able to optimize that such that it's as fast as direct initialization.

查看更多
萌妹纸的霸气范
3楼-- · 2018-12-31 22:12

Create an array maker type.

It overloads operator, to generate an expression template chaining each element to the previous via references.

Add a finish free function that takes the array maker and generates an array directly from the chain of references.

The syntax should look something like this:

auto arr = finish( make_array<T>->* 1,2,3,4,5 );

It does not permit {} based construction, as only operator= does. If you are willing to use = we can get it to work:

auto arr = finish( make_array<T>= {1}={2}={3}={4}={5} );

or

auto arr = finish( make_array<T>[{1}][{2}[]{3}][{4}][{5}] );

None of these look like good solutions.

Using variardics limits you to your compiler-imposed limit on number of varargs and blocks recursive use of {} for substructures.

In the end, there really isn't a good solution.

What I do is I write my code so it consumes both T[] and std::array data agnostically -- it doesn't care which I feed it. Sometimes this means my forwarding code has to carefully turn [] arrays into std::arrays transparently.

查看更多
闭嘴吧你
4楼-- · 2018-12-31 22:17

C++11 will support this manner of initialization for (most?) std containers.

查看更多
旧人旧事旧时光
5楼-- · 2018-12-31 22:22

I'd expect a simple make_array.

template<typename ret, typename... T> std::array<ret, sizeof...(T)> make_array(T&&... refs) {
    return std::array<ret, sizeof...(T)>{ { std::forward<T>(refs)... } };
}
查看更多
柔情千种
6楼-- · 2018-12-31 22:25

Using trailing return syntax make_array can be further simplified

#include <array>
#include <type_traits>
#include <utility>

template <typename... T>
auto make_array(T&&... t)
  -> std::array<std::common_type_t<T...>, sizeof...(t)>
{
  return {std::forward<T>(t)...};
}

int main()
{
  auto arr = make_array(1, 2, 3, 4, 5);
  return 0;
}

Unfortunatelly for aggregate classes it requires explicit type specification

/*
struct Foo
{
  int a, b;
}; */

auto arr = make_array(Foo{1, 2}, Foo{3, 4}, Foo{5, 6});

In fact this make_array implementation is listed in sizeof... operator


c++17 version

Thanks to template argument deduction for class templates proposal we can use deduction guides to get rid of make_array helper

#include <array>

namespace std
{
template <typename... T> array(T... t)
  -> array<std::common_type_t<T...>, sizeof...(t)>;
}

int main()
{
  std::array a{1, 2, 3, 4};
  return 0; 
}

Compiled with -std=c++1z flag under x86-64 gcc 7.0

查看更多
听够珍惜
7楼-- · 2018-12-31 22:31

(Solution by @dyp)

Note: requires C++14 (std::index_sequence). Although one could implement std::index_sequence in C++11.

#include <iostream>

// ---

#include <array>
#include <utility>

template <typename T>
using c_array = T[];

template<typename T, size_t N, size_t... Indices>
constexpr auto make_array(T (&&src)[N], std::index_sequence<Indices...>) {
    return std::array<T, N>{{ std::move(src[Indices])... }};
}

template<typename T, size_t N>
constexpr auto make_array(T (&&src)[N]) {
    return make_array(std::move(src), std::make_index_sequence<N>{});
}

// ---

struct Point { int x, y; };

std::ostream& operator<< (std::ostream& os, const Point& p) {
    return os << "(" << p.x << "," << p.y << ")";
}

int main() {
    auto xs = make_array(c_array<Point>{{1,2}, {3,4}, {5,6}, {7,8}});

    for (auto&& x : xs) {
        std::cout << x << std::endl;
    }

    return 0;
}
查看更多
登录 后发表回答