Copy array in constexpr constructor

I wrote a class with the constexpr copy constructor. (This is an example structure to simplify it.) One of the fields is an array. I also want to copy it.

 struct Foo { static constexpr int SIZE = 4; constexpr Foo() = default; constexpr Foo(const Foo &foo) : arr{foo.arr[0], foo.arr[1], foo.arr[2], foo.arr[3]}, bar(foo.bar+1) {} int arr[SIZE] = {0, 0, 0, 0}; int bar = 0; }; 

My version works, but it is not scalable. If I change SIZE , I need to change the constructor. Also, the code looks ugly.

Is it better to copy the array to the constructor? The constructor must be constexpr .

+5
source share
3 answers

You can use std :: array. Since this is an aggregate type, I believe this will work.

+3
source

In C ++ 14, you can simply use a loop to copy an array:

 constexpr Foo(const Foo &foo) : bar(foo.bar + 1) { for (int i = 0; i < SIZE; ++i) arr[i] = foo.arr[i]; } 

This does not mean that you should do it. I would recommend using std::array instead. For example, if arr is an array of some type of class with non-trivial initialization, it will be initialized by default and then copied, thereby losing performance instead of copy initialization when using std::array and the default copy constructor.

+3
source

you can do something like C ++ 11 to just copy the array

 template <int LENGTH> constexpr bool copy_array(const char (&from)[LENGTH + 1], char (&to)[LENGTH], int index) { return index < LENGTH ? (to[index] = from[index], copy_array(from, to, ++index)) : false; } constexpr char src[] = "ab"; char dest[2]; copy_array(src, dest, 0); 

edited: And in your context, you could do something like:

 #include <iostream> #include <type_traits> #include <array> #include <utility> struct Foo { static constexpr int SIZE = 4; constexpr Foo() = default; constexpr Foo(const Foo &foo) : arr{foo.arr}, bar(foo.bar + 1) {} std::array<int, SIZE> arr = {{0, 0, 0, 0}}; int bar = 0; }; int main() { constexpr Foo foo1; constexpr Foo foo2(foo1); std::cout << foo1.bar << std::endl; std::cout << foo2.bar << std::endl; return 0; } 
+1
source

Source: https://habr.com/ru/post/1207493/


All Articles