std::array Type Initialization - c++

With a std::array you can initialize it like this:
std::array<int,5> myArray = {1,2,3,4,5};
If I where trying to create my own array class how would I do something similar?

std::array rely on aggregate initialization (the C way of initializing struct), basically this is valid c++:
struct A {
int values[2];
size_t size;
};
A a = {{42, 44}, 2U}; // No constructor involved
// | |--- a.size
// |--- a.values
Now if you remove the size attribute, you get:
struct A {
int values[2];
};
A a = {{42, 44}}; // Valid!
But c++ gives you something called brace-elision we allow you to omit the inner brackets, so:
A a = {42, 44}; // Still valid!
Now, just makes A a template:
template <typename T, size_t N>
struct A {
T data[N];
};
A<int, 2> a = {{42, 44}};
Note that this does not makes use of initializer_list which are used for std::vector, std::list, and so on.
Also note that:
A<int, 2> a1{42, 44}; // Not valid prior to c++14
A<int, 2> a2{{42, 44}}; // Ok even for c++11
And note that clang will throw warning whatever the version you use by default.
A minimalist version of std::array could look like this:
template <typename T, size_t N>
struct my_array {
T _data[N];
T& operator[] (size_t i) { return _data[i]; }
const T& operator[] (size_t i) const { return _data[i]; }
constexpr size_t size () const { return N; }
T* begin () { return _data; }
const T* begin () const{ return _data; }
T* end () { return _data + size(); }
T* end () const { return _data + size(); }
};
Please note that the standard std::array has a lot more stuff than this (a lots of typedefs, other methods, a lots of overloads, ...), but this is a small base to get you started.
Also note that _data has to be public so that aggregate initialization can work (it does not work if you have private / protected members!).

Here is a simple implementation that supports initializing with a list of elements:
//template class 'array' takes 'T' (the type of the array) and 'size'
template<typename T, std::size_t size>
class array
{
public:
//This is the concept of initializer lists (wrapper around variadic arguments, that
//allows for easy access)
array(std::initializer_list<T> list)
{
//Loop through each value in 'list', and assign it to internal array
for (std::size_t i = 0; i < list.size(); ++i)
arr[i] = *(list.begin() + i); //list.begin() returns an iterator to the firsts
//element, which can be moved using +
//(deferenced to get the value)
}
//Overloads operator[] for easy access (no bounds checking!)
T operator[](std::size_t index)
{
return arr[index];
}
private:
T arr[size]; //internal array
};
You can then use it like so:
array<int, 2> a = { 2, 5 };
int b = a[0]; //'b' == '2'

Related

What is the most efficient way to iterate over array and preprocess it before copy in C++?

I have custom array constructor like below:
rtc::ArrayView<const uint8_t> frame,
rtc::ArrayView<uint8_t> encrypted_frame,
uint8_t unencrypted_bytes = 10;
How could I efficiently loop into these frames and do processing for it? Is only for loop the possible option? If we just want to copy the frame without preprocessing, I know that we could just copy using std::copy. Is there any ways to make this iterator processing more efficient?
// // Copy rest of frame
// std::copy(frame.begin() + unencrypted_bytes, frame.begin() +
// (encrypted_frame.size() - 41),
// encrypted_frame.begin() + unencrypted_bytes);
// Doing XOR for Frame
for (size_t i = unencrypted_bytes; i < encrypted_frame.size() - 41; i++) {
// encrypted_frame[i] = i;
RTC_LOG(LS_INFO) << "Ivan, original frame Before XOR : " << i << " "
<< frame[i];
encrypted_frame[i] = frame[i] ^ fake_key_;
RTC_LOG(LS_INFO) << "Ivan, encrypted frame After XOR : " << i << " "
<< encrypted_frame[i];
}
Below is my array view constructor
/*
* Copyright 2015 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef API_ARRAY_VIEW_H_
#define API_ARRAY_VIEW_H_
#include <algorithm>
#include <array>
#include <iterator>
#include <type_traits>
#include "rtc_base/checks.h"
#include "rtc_base/type_traits.h"
namespace rtc {
// tl;dr: rtc::ArrayView is the same thing as gsl::span from the Guideline
// Support Library.
//
// Many functions read from or write to arrays. The obvious way to do this is
// to use two arguments, a pointer to the first element and an element count:
//
// bool Contains17(const int* arr, size_t size) {
// for (size_t i = 0; i < size; ++i) {
// if (arr[i] == 17)
// return true;
// }
// return false;
// }
//
// This is flexible, since it doesn't matter how the array is stored (C array,
// std::vector, rtc::Buffer, ...), but it's error-prone because the caller has
// to correctly specify the array length:
//
// Contains17(arr, arraysize(arr)); // C array
// Contains17(arr.data(), arr.size()); // std::vector
// Contains17(arr, size); // pointer + size
// ...
//
// It's also kind of messy to have two separate arguments for what is
// conceptually a single thing.
//
// Enter rtc::ArrayView<T>. It contains a T pointer (to an array it doesn't
// own) and a count, and supports the basic things you'd expect, such as
// indexing and iteration. It allows us to write our function like this:
//
// bool Contains17(rtc::ArrayView<const int> arr) {
// for (auto e : arr) {
// if (e == 17)
// return true;
// }
// return false;
// }
//
// And even better, because a bunch of things will implicitly convert to
// ArrayView, we can call it like this:
//
// Contains17(arr); // C array
// Contains17(arr); // std::vector
// Contains17(rtc::ArrayView<int>(arr, size)); // pointer + size
// Contains17(nullptr); // nullptr -> empty ArrayView
// ...
//
// ArrayView<T> stores both a pointer and a size, but you may also use
// ArrayView<T, N>, which has a size that's fixed at compile time (which means
// it only has to store the pointer).
//
// One important point is that ArrayView<T> and ArrayView<const T> are
// different types, which allow and don't allow mutation of the array elements,
// respectively. The implicit conversions work just like you'd hope, so that
// e.g. vector<int> will convert to either ArrayView<int> or ArrayView<const
// int>, but const vector<int> will convert only to ArrayView<const int>.
// (ArrayView itself can be the source type in such conversions, so
// ArrayView<int> will convert to ArrayView<const int>.)
//
// Note: ArrayView is tiny (just a pointer and a count if variable-sized, just
// a pointer if fix-sized) and trivially copyable, so it's probably cheaper to
// pass it by value than by const reference.
namespace impl {
// Magic constant for indicating that the size of an ArrayView is variable
// instead of fixed.
enum : std::ptrdiff_t { kArrayViewVarSize = -4711 };
// Base class for ArrayViews of fixed nonzero size.
template <typename T, std::ptrdiff_t Size>
class ArrayViewBase {
static_assert(Size > 0, "ArrayView size must be variable or non-negative");
public:
ArrayViewBase(T* data, size_t size) : data_(data) {}
static constexpr size_t size() { return Size; }
static constexpr bool empty() { return false; }
T* data() const { return data_; }
protected:
static constexpr bool fixed_size() { return true; }
private:
T* data_;
};
// Specialized base class for ArrayViews of fixed zero size.
template <typename T>
class ArrayViewBase<T, 0> {
public:
explicit ArrayViewBase(T* data, size_t size) {}
static constexpr size_t size() { return 0; }
static constexpr bool empty() { return true; }
T* data() const { return nullptr; }
protected:
static constexpr bool fixed_size() { return true; }
};
// Specialized base class for ArrayViews of variable size.
template <typename T>
class ArrayViewBase<T, impl::kArrayViewVarSize> {
public:
ArrayViewBase(T* data, size_t size)
: data_(size == 0 ? nullptr : data), size_(size) {}
size_t size() const { return size_; }
bool empty() const { return size_ == 0; }
T* data() const { return data_; }
protected:
static constexpr bool fixed_size() { return false; }
private:
T* data_;
size_t size_;
};
} // namespace impl
template <typename T, std::ptrdiff_t Size = impl::kArrayViewVarSize>
class ArrayView final : public impl::ArrayViewBase<T, Size> {
public:
using value_type = T;
using const_iterator = const T*;
// Construct an ArrayView from a pointer and a length.
template <typename U>
ArrayView(U* data, size_t size)
: impl::ArrayViewBase<T, Size>::ArrayViewBase(data, size) {
RTC_DCHECK_EQ(size == 0 ? nullptr : data, this->data());
RTC_DCHECK_EQ(size, this->size());
RTC_DCHECK_EQ(!this->data(),
this->size() == 0); // data is null iff size == 0.
}
// Construct an empty ArrayView. Note that fixed-size ArrayViews of size > 0
// cannot be empty.
ArrayView() : ArrayView(nullptr, 0) {}
ArrayView(std::nullptr_t) // NOLINT
: ArrayView() {}
ArrayView(std::nullptr_t, size_t size)
: ArrayView(static_cast<T*>(nullptr), size) {
static_assert(Size == 0 || Size == impl::kArrayViewVarSize, "");
RTC_DCHECK_EQ(0, size);
}
// Construct an ArrayView from a C-style array.
template <typename U, size_t N>
ArrayView(U (&array)[N]) // NOLINT
: ArrayView(array, N) {
static_assert(Size == N || Size == impl::kArrayViewVarSize,
"Array size must match ArrayView size");
}
// (Only if size is fixed.) Construct a fixed size ArrayView<T, N> from a
// non-const std::array instance. For an ArrayView with variable size, the
// used ctor is ArrayView(U& u) instead.
template <typename U,
size_t N,
typename std::enable_if<
Size == static_cast<std::ptrdiff_t>(N)>::type* = nullptr>
ArrayView(std::array<U, N>& u) // NOLINT
: ArrayView(u.data(), u.size()) {}
// (Only if size is fixed.) Construct a fixed size ArrayView<T, N> where T is
// const from a const(expr) std::array instance. For an ArrayView with
// variable size, the used ctor is ArrayView(U& u) instead.
template <typename U,
size_t N,
typename std::enable_if<
Size == static_cast<std::ptrdiff_t>(N)>::type* = nullptr>
ArrayView(const std::array<U, N>& u) // NOLINT
: ArrayView(u.data(), u.size()) {}
// (Only if size is fixed.) Construct an ArrayView from any type U that has a
// static constexpr size() method whose return value is equal to Size, and a
// data() method whose return value converts implicitly to T*. In particular,
// this means we allow conversion from ArrayView<T, N> to ArrayView<const T,
// N>, but not the other way around. We also don't allow conversion from
// ArrayView<T> to ArrayView<T, N>, or from ArrayView<T, M> to ArrayView<T,
// N> when M != N.
template <
typename U,
typename std::enable_if<Size != impl::kArrayViewVarSize &&
HasDataAndSize<U, T>::value>::type* = nullptr>
ArrayView(U& u) // NOLINT
: ArrayView(u.data(), u.size()) {
static_assert(U::size() == Size, "Sizes must match exactly");
}
template <
typename U,
typename std::enable_if<Size != impl::kArrayViewVarSize &&
HasDataAndSize<U, T>::value>::type* = nullptr>
ArrayView(const U& u) // NOLINT(runtime/explicit)
: ArrayView(u.data(), u.size()) {
static_assert(U::size() == Size, "Sizes must match exactly");
}
// (Only if size is variable.) Construct an ArrayView from any type U that
// has a size() method whose return value converts implicitly to size_t, and
// a data() method whose return value converts implicitly to T*. In
// particular, this means we allow conversion from ArrayView<T> to
// ArrayView<const T>, but not the other way around. Other allowed
// conversions include
// ArrayView<T, N> to ArrayView<T> or ArrayView<const T>,
// std::vector<T> to ArrayView<T> or ArrayView<const T>,
// const std::vector<T> to ArrayView<const T>,
// rtc::Buffer to ArrayView<uint8_t> or ArrayView<const uint8_t>, and
// const rtc::Buffer to ArrayView<const uint8_t>.
template <
typename U,
typename std::enable_if<Size == impl::kArrayViewVarSize &&
HasDataAndSize<U, T>::value>::type* = nullptr>
ArrayView(U& u) // NOLINT
: ArrayView(u.data(), u.size()) {}
template <
typename U,
typename std::enable_if<Size == impl::kArrayViewVarSize &&
HasDataAndSize<U, T>::value>::type* = nullptr>
ArrayView(const U& u) // NOLINT(runtime/explicit)
: ArrayView(u.data(), u.size()) {}
// Indexing and iteration. These allow mutation even if the ArrayView is
// const, because the ArrayView doesn't own the array. (To prevent mutation,
// use a const element type.)
T& operator[](size_t idx) const {
RTC_DCHECK_LT(idx, this->size());
RTC_DCHECK(this->data());
return this->data()[idx];
}
T* begin() const { return this->data(); }
T* end() const { return this->data() + this->size(); }
const T* cbegin() const { return this->data(); }
const T* cend() const { return this->data() + this->size(); }
std::reverse_iterator<T*> rbegin() const {
return std::make_reverse_iterator(end());
}
std::reverse_iterator<T*> rend() const {
return std::make_reverse_iterator(begin());
}
std::reverse_iterator<const T*> crbegin() const {
return std::make_reverse_iterator(cend());
}
std::reverse_iterator<const T*> crend() const {
return std::make_reverse_iterator(cbegin());
}
ArrayView<T> subview(size_t offset, size_t size) const {
return offset < this->size()
? ArrayView<T>(this->data() + offset,
std::min(size, this->size() - offset))
: ArrayView<T>();
}
ArrayView<T> subview(size_t offset) const {
return subview(offset, this->size());
}
};
// Comparing two ArrayViews compares their (pointer,size) pairs; it does *not*
// dereference the pointers.
template <typename T, std::ptrdiff_t Size1, std::ptrdiff_t Size2>
bool operator==(const ArrayView<T, Size1>& a, const ArrayView<T, Size2>& b) {
return a.data() == b.data() && a.size() == b.size();
}
template <typename T, std::ptrdiff_t Size1, std::ptrdiff_t Size2>
bool operator!=(const ArrayView<T, Size1>& a, const ArrayView<T, Size2>& b) {
return !(a == b);
}
// Variable-size ArrayViews are the size of two pointers; fixed-size ArrayViews
// are the size of one pointer. (And as a special case, fixed-size ArrayViews
// of size 0 require no storage.)
static_assert(sizeof(ArrayView<int>) == 2 * sizeof(int*), "");
static_assert(sizeof(ArrayView<int, 17>) == sizeof(int*), "");
static_assert(std::is_empty<ArrayView<int, 0>>::value, "");
template <typename T>
inline ArrayView<T> MakeArrayView(T* data, size_t size) {
return ArrayView<T>(data, size);
}
// Only for primitive types that have the same size and aligment.
// Allow reinterpret cast of the array view to another primitive type of the
// same size.
// Template arguments order is (U, T, Size) to allow deduction of the template
// arguments in client calls: reinterpret_array_view<target_type>(array_view).
template <typename U, typename T, std::ptrdiff_t Size>
inline ArrayView<U, Size> reinterpret_array_view(ArrayView<T, Size> view) {
static_assert(sizeof(U) == sizeof(T) && alignof(U) == alignof(T),
"ArrayView reinterpret_cast is only supported for casting "
"between views that represent the same chunk of memory.");
static_assert(
std::is_fundamental<T>::value && std::is_fundamental<U>::value,
"ArrayView reinterpret_cast is only supported for casting between "
"fundamental types.");
return ArrayView<U, Size>(reinterpret_cast<U*>(view.data()), view.size());
}
} // namespace rtc
#endif // API_ARRAY_VIEW_H_
This looks like WebRTC code. And if I had to guess, you're encrypting the media bytes of an RTP packet (just a guess). And so you probably want that to be fast.
I'm going to assume you recognize that the RTC_LOG statements in your main loop are likely more of a loop performance killer than anything else you can do to optimize the xor encryption. It's going to negate whatever optimizations you do if you are logging each individual byte. So let's start with this.
for (size_t i = unencrypted_bytes; i < encrypted_frame.size() - 41; i++) {
encrypted_frame[i] = frame[i] ^ fake_key_;
}
The operator overload for [] looks like this:
T& operator[](size_t idx) const {
RTC_DCHECK_LT(idx, this->size());
RTC_DCHECK(this->data());
return this->data()[idx];
}
So that means every iteration a call to data() for both the source and destination arrays. And operator[] overload does some additional validation checks. In a release build, the compiler may be able to optimize most of that away since. But I don't know that for a fact because I don't know if the compiler will optimize your ArrayView like it would operations on a std:: collection class. Nor do I know if those RTC_DCHECK macros are no-ops in a release build.
But in a Debug build, it will be really slow. So if we can make debug fast, we can assume it carries over to your release build.
We can make sure our primary loop that iterates over the bytes and doesn't make any function calls within the loop. That's going to be your biggest speed up. Hence, this will be much faster than what you have:
uint8_t* frame_data = frame.data();
uint8_t* encrypted_data = encrypted_frame.data()
const size_t stop = i < encrypted_frame.size() - 41;
for (size_t i = frame_data + unencrypted_bytes; i < stop; i++) {
encrypted_data[i] = frame_data[i] ^ fake_key_;
}
You could optionally use std::transform instead of a for-loop, but I think that will be nearly equivalent.
Again, it's entirely possible the compiler will optimize out the original function be as good as what I just produced. But since ArrayView doesn't compile locally for me (don't have the webrtc sources handy), I don't know. Otherwise, if I could, I'd have all my assumptions validated on godbolt.
But I do know from experience that a function call per element in really tight loop iterating over bytes or words, even if declared inline, is never as fast as manually inlining all the code you need directly into the loop.
For xor-ing a source range to a destination range, I'd use std::transform:
std::transform(
frame.cbegin() + unencrypted_bytes,
frame.cend() - 41,
encrypted_frame.begin(),
[=] (const auto byte) -> std::uint8_t { return byte ^ fake_key_; });
In C++, it is often the case that clearly expressing the intention of the program with high-level abstractions using the standard library is the best choice. Source code should be used to express what the program needs to do, and avoid dictating how to do it as much as possible*, because that would constrain compiler optimizations from coming up with the best possible approach.
* Unless you really know what you're doing and you have the benchmarks to prove it
It would also be nice to make use of std::bit_xor, but that would require two input ranges in order to invoke the overload for std::transform that accepts a binary operator. Assuming the constant fake_key_ is a std::uint8_t, here's the definition for an iterator to model an infinite, filled range:
template <class T>
struct filled {
using value_type = T;
using difference_type = std::ptrdiff_t;
using reference = const T &;
using pointer = const T *;
using iterator_category = std::input_iterator_tag;
constexpr filled() noexcept = default;
constexpr filled(const filled &) = default;
constexpr filled(filled &&) = default;
constexpr filled(reference value) : value{value} {}
constexpr filled &operator=(const filled &) = default;
constexpr filled &operator=(filled &&) = default;
constexpr ~filled() = default;
constexpr bool operator==(const filled &) const noexcept { return false; }
constexpr reference operator*() const noexcept { return value; }
constexpr pointer operator->() const noexcept {
return std::addressof(value);
}
constexpr filled &operator++() noexcept { return *this; }
constexpr filled operator++(int) { return *this; }
private:
value_type value;
};
static_assert(std::input_iterator<filled<std::uint8_t>>);
Enabling the use of this overload:
std::transform(
frame.cbegin() + unencrypted_bytes,
frame.cend() - 41,
encrypted_frame.begin(),
filled<std::uint8_t>(fake_key_),
std::bit_xor<std::uint8_t>());

Implementing an efficient and convenient constructor for a C++ vector class template

I'm trying to implement a constructor for a C++ vector class template that is both efficient and convenient to use. The latter is, of course, somewhat subjective — I'm aiming at something like Vec2D myVec = Vec2D({1.0, 2.0}).
To start with, I'm thinking about a class template for fixed-length vectors, so no immediate use for std::vector I'd say. With template <typename T, unsigned short n>, two options to store the elements of the vector would be T mElements[n] or std::array<T, n> mElements. I would go with the latter (same storage and some added benefits compared to the former).
Now, on to the constructor (and the question) — what should be its parameter? The following options come to mind:
Using std::array<T, n> initElements would require the use of double curved brackets for initialisation as it is an aggregate, i.e. Vec2D myVec = Vec2D({{1.0, 2.0}}). Omitting the outer curly brackets might still compile, though results in a warning. Additionally, if we were to generalise this to a 2D array, e.g. for a matrix class template, it would require quadruple curved brackets (or triple when omitting the outer pair again, taking a warning for granted). Not so convenient.
Using T initElems[] would require e.g. double dElems[2] = {1.0, 2.0} followed by Vec2D myVec = Vec2D(dElems), it is not possible to directly pass {1.0, 2.0} as argument. Not so convenient.
Using std::initializer_list<T>, which would allow Vec2D myVec{1.0, 2.0}. This also nicely generalises to a 2D array. However, I don't see how one would use this as a constructor when overloading operators, say operator +.
Using std::vector<T>. This allows the use of Vec2D myVec = Vec2D({1.0, 2.0}), nicely generalises to 2D arrays, and is easy to use in overloaded operators. However, it does not seem very efficient.
The (intentionally basic) code below reflects the last option. Are there alternatives which are more efficient, without losing convenience?
template <typename T, unsigned short n>
class Vector {
public:
std::array<T, n> mElements;
// Constructor
Vector(std::vector<T> initElements) {
for (unsigned short k = 0; k < n; k++) {
mElements[k] = initElements[k];
}
}
// Overloaded operator +
Vector operator + (const Vector& rightVector) const {
std::vector<T> sumVec(n);
for (unsigned short k = 0; k < n; k++) {
sumVec[k] = mElements[k] + rightVector.mElements[k];
}
return Vector(sumVec);
}
};
With the usage
using Vec2D = Vector<double, 2>;
Vec2D myVec = Vec2D({1.0, 2.0});
You could also make use of parameter packs, which (combined with some nice polymorphism) can enable you to do stuff like this:
Vector<int, 3> v1{std::vector<int>{1, 2, 3}};
Vector<double, 3> v2 = {5., 6., 7.};
Vector<float, 3> v3 = v1 + v2;
Where Vector is defined as follows:
#include <vector>
#include <array>
#include <algorithm>
#include <cassert>
template <typename T, size_t n>
struct Vector : std::array<T, n>
{
/* Default constructor, needed as recursion endpoint */
Vector() = default;
/* Recursive constructor that takes an arbitrary number of arguments
* Dangerous: only adds the last n arguments */
template <typename... Ts>
Vector(T v, Ts... args) : Vector(args...) { addItem(v); };
/* Vector constructor that takes an arbitrary std::vector v
* Dangerous: only adds the first n items */
template <typename T2>
explicit Vector(const std::vector<T2>& v) : added{std::min(v.size(), n)}
{
assert(v.size() == n);
for (size_t i = 0; i < added; i++)
{
(*this)[i] = (T)v[i];
}
}
/* Copy constructor: takes a Vector of any type, but of the same length */
template <typename T2>
Vector(const std::array<T2, n>& v) : added{n}
{
for (size_t i = 0; i < added; i++)
{
(*this)[i] = (T)v[i];
}
}
/* Example of a polymorphic addition function */
template <typename T2>
Vector<T, n> operator+(const Vector<T2, n>& v)
{
Vector<T, n> vr{*this};
for (size_t i = 0; i < n; i++)
{
vr[i] += (T)v[i];
}
return vr;
}
private:
size_t added{0};
/* Needed for recursive constructor */
void addItem(const T& t)
{
added++;
if (added <= n) { (*this)[n - added] = t; }
else { assert(false); }
}
};
The most convienient way to make this would be to use a deduction guide, changing your given usage example:
using Vec2D = Vector<double, 2>;
Vec2D myVec = Vec2D({1.0, 2.0});
into something much simpler:
Vector<double, 2> myVec = { 1.0, 2.0 };
// or even
// Vector myVec = { 1.0, 2.0 };
Enabling a usage similar to std::array.
Arguably the easiest, and most efficient way to create a statically sized vector that allows this would be to use a non-standard C++ __attriubute__.
Templating the T __attribute__((vector_size(N))), we end up with the following:
using ushort = unsigned short;
template <typename T, ushort N>
using Vector = T __attribute__((
vector_size(sizeof(T) * N) // the number of bytes in a single `T`, multiplied by the number of elements, `N`
));
int main() {
using vector_t = Vector<double const, 2>;
vector_t x = { 1.0, 2.0 };
vector_t y = { 9.0, 3.0 };
vector_t z = x + y;
std::wcout << z[0] << ", " << z[1] << '\n'; // "10, 5\n"
}
Okay, okay, I'm joking, don't do that, let's not touch upon the world of attributes, compiler extensions, and nonportable code.
The simplest way to make it as convenient to use as the underlying std::array, would be to either, create a type deduction guide, inherit from std::array, or to not implement a constructor, the latter two allow the std::array constructor to take effect, as the class has no constructor on its own.
I think, in this case, you might be able to simply inherit from std::array, without pissing off every C++ developer on SO.
Something along the lines of:
#include <iostream>
#include <vector>
#include <array>
using u16 = unsigned short const;
template <typename T, u16 N>
struct Vector : std::array<T, N> {
Vector<T, N> operator + (Vector<T, N> & rightVector) {
decltype(auto) self = *this;
Vector<T, N> sumVec;
for ( ushort i = 0; i < N; ++i ) {
sumVec[i] = self[i] + rightVector[i];
}
return sumVec;
}
Vector operator += (Vector const& rightVector) {
decltype(auto) self = *this;
for ( ushort i = 0; i < N; ++i ) {
self[i] += rightVector[i];
}
return this;
}
Vector operator ++ () {
decltype(auto) self = *this;
for ( T& item : self ) {
++item;
}
return this;
}
Vector operator ++ (int const) {
decltype(auto) self = *this;
Vector temporary = self;
++self;
return temporary;
}
Vector operator - (Vector const& rightVector) const {
decltype(auto) self = *this;
Vector<T, N> sumVec;
for ( ushort i = 0; i < N; ++i ) {
sumVec[i] = self[i] - rightVector[i];
}
return Vector(sumVec);
}
};
int main() {
using vector_t = Vector<double, 2>;
vector_t x = { 1.0, 2.0 };
vector_t y = { 9.0, 3.0 };
vector_t z = x + y; // { 10.0. 4.0 }
std::wcout << z[0] << ", " << z[1] << '\n';
}
Although, you might want to use a few std::enable_ifs or assertions to make sure that you only create Vectors of a numerical type, as that seems to be what you want to use.
This should have the same memory usage as a std::array. It doesn't initialize any extra types, in contrast to your example that had constructed std::vectors everywhere.
Does this fit your intended usage and goals?
You could directly use the parameters to initialise the base class
Untested code.
template <typename... Args>
Vector(Args...&& args) : mEVector(std::forward<Args>(args)...) { };

constexpr vector push_back or how to constexpr all the things

There is a good talk by Jason Turner and Ben Deane from C++Now 2017 called "Constexpr all the things" which also gives a constexpr vector implementation. I was dabbling with the idea myself, for educational purposes. My constexpr vector was pure in the sense that pushing back to it would return a new vector with added element.
During the talk, I saw a push_back implementation tat looks like more or less following:
constexpr void push_back(T const& e) {
if(size_ >= Size)
throw std::range_error("can't use more than Size");
else {
storage_[size_++] = e;
}
}
They were taking the element by value and moving it but, I don't think this is the source of my problems. The thing I want to know is, how this function could be used in a constexpr context? This is not a const member function, it modifies the state. I don think it is possible to do something like
constexpr cv::vector<int> v1;
v1.push_back(42);
And if this is not possible, how could we use this thing in constexpr context and achieve the goal of the task using this vector, namely compile-time JSON parsing?
Here is my version, so that you can see both my new vector returning version and the version from the talk. (Note that performance, perfect forwarding etc. concerns are omitted)
#include <cstdint>
#include <array>
#include <type_traits>
namespace cx {
template <typename T, std::size_t Size = 10>
struct vector {
using iterator = typename std::array<T, Size>::iterator;
using const_iterator = typename std::array<T, Size>::const_iterator;
constexpr vector(std::initializer_list<T> const& l) {
for(auto& t : l) {
if(size_++ < Size)
storage_[size_] = std::move(t);
else
break;
}
}
constexpr vector(vector const& o, T const& t) {
storage_ = o.storage_;
size_ = o.size_;
storage_[size_++] = t;
}
constexpr auto begin() const { return storage_.begin(); }
constexpr auto end() const { return storage_.begin() + size_; }
constexpr auto size() const { return size_; }
constexpr void push_back(T const& e) {
if(size_ >= Size)
throw std::range_error("can't use more than Size");
else {
storage_[size_++] = e;
}
}
std::array<T, Size> storage_{};
std::size_t size_{};
};
}
template <typename T>
constexpr auto make_vector(std::initializer_list<T> const& l) {
return cx::vector<int>{l};
}
template <typename T>
constexpr auto push_back(cx::vector<T> const& o, T const& t) {
return cx::vector<int>{o, t};
}
int main() {
constexpr auto v1 = make_vector({1, 2, 3});
static_assert(v1.size() == 3);
constexpr auto v2 = push_back(v1, 4);
static_assert(v2.size() == 4);
static_assert(std::is_same_v<decltype(v1), decltype(v2)>);
// v1.push_back(4); fails on a constexpr context
}
So, this thing made me realize there is probably something deep that I don' know about constexpr. So, recapping the question; how such a constexpr vector could offer a mutating push_back like that in a constexpr context? Seems like it is not working in a constexpr context right now. If push_back in a constexpr context is not intended to begin with, how can you call it a constexpr vector and use it for compile-time JSON parsing?
Your definition of vector is correct, but you can't modify constexpr objects. They are well and truly constant. Instead, do compile-time calculations inside constexpr functions (the output of which can then be assigned to constexpr objects).
For example, we can write a function range, which produces a vector of numbers from 0 to n. It uses push_back, and we can assign the result to a constexpr vector in main.
constexpr vector<int> range(int n) {
vector<int> v{};
for(int i = 0; i < n; i++) {
v.push_back(i);
}
return v;
}
int main() {
constexpr vector<int> v = range(10);
}
Your return cx::vector<int>{o, t}; will produce a compilation error when o and t are of types cx::vector<T> and T respectively, because those are different types, while all elements of std::initializer_list<T> should be of same type (o is not expanded into a list of its elements).
If you're merely after your 'pure' implementation of push_back, then you can make do with standard arrays:
#include <array>
template <typename T, std::size_t N>
constexpr auto push_back(std::array<T, N> const& oldArr, T const& el) {
std::array<T, N+1> newArr{};
std::copy(begin(oldArr), end(oldArr), begin(newArr));
newArr[N] = el;
return newArr;
}
int main() {
constexpr auto a1 = std::to_array({1, 2, 3});
static_assert(a1.size() == 3);
constexpr auto a2 = push_back(a1, 4);
static_assert(a2.size() == 4);
// This assert will still fail though, because push_back's implementation
// above not only returns new array, but also a new type.
// For example, std::array<int, 3> is not the same type as std::array<int, 4>
//static_assert(std::is_same_v<decltype(a1), decltype(a2)>);
}

Constructor from initializer_list

I am implementing a container in c++, a wrapper for an array in fact. I am not sure how to implement a constructor from initializer_list. I end up with this implementation but it seems to me really ugly. So could be an array allocated in a heap initialized by an initializer_list. Or is there an elegant way how to do it?
template <typename T> class sequence {
public:
sequence (size_t n): _data {new T[n]}, _size {n} {};
sequence (std::initializer_list<T> source);
~sequence() { delete[] _data; };
private:
pointer _data;
size_type _size;
};
//Initializer list constructor
template <class T> sequence<T>::sequence (std::initializer_list<T> source)
: sequence(source.size()) {
auto iterator = source.begin();
for ( int i=0; i < _size; i++) {
_data[i] = *iterator;
++iterator;
}
};
Depends on what you're trying to do.
If you're actually needing to use a sequence with bounded size, as determined at compile-time, then use std::array<T,std::size_t>, which is a wrapper around a C-style array (like what you are implementing), introduced in C++11.
However, as you said in one of your comments, you're doing this mostly for educational purposes. In that case, what you have is decent. The syntax could be cleaned up a little. Consider:
//Initializer list constructor
template <class T>
sequence<T>::sequence (std::initializer_list<T> source)
: sequence(source.size())
{
auto it = source.begin();
auto const e = source.cend();
auto d = data_;
while (it != e) {
*d++ = *it++;
}
};
That way you don't explicitly rely on the size(). You could consider making things more efficient by turning the it and e iterators into "move" iterators:
auto it = std::make_move_iterator(source.begin());
auto e = std::make_move_iterator(source.end());
That way, whenever it's dereferenced, its value is cast to an rvalue reference, allowing a move assignment.

How to initialize an array when using a template

I created an array template for my personal use.
template <typename T, int size>
struct Vector {
T data[size];
};
I tried to intialize the data like so:
Vector<unsigned char, 10> test;
test.data[] = {0,1,2,3,4,5,6,7,8,9};
My compiler ended up complaining something about "expected expression." Does anyone know what I'm doing? I want to be able to use this style of initialization where you give it the entire array definition at once instead of using a for loop to init the elements individually.
Since your class is an aggregate, you can initialize it with the usual brace syntax:
Vector<int, 3> x = { { 1, 2, 3 } };
The exact same thing applies to std::array<int, 3>.
In the new standard, C++11, you can use std::initalizer_list to get the desired result, see the below example.
#include <iostream>
#include <algorithm>
template <typename T, int size>
struct Vector {
T data[size];
Vector<T, size> (std::initializer_list<T> _data) {
std::copy (_data.begin (), _data.end (), data);
}
// ...
Vector<T, size>& operator= (std::initializer_list<T> const& _data) {
std::copy (_data.begin (), _data.end (), data);
return *this;
}
};
int
main (int argc, char *argv[])
{
Vector<int, 10> v ({1,2,3,4,5,6}); // std::initializer_list
v = {9,8,7,6,5,4,3,2,1,0}; // operator=
}
If you are working with a standard prior to C++11 it's a bit more of a hassle really, and your best bet is to implement functions similar to those available when using std::vector.
#include <iostream>
#include <algorithm>
template <typename T, int size>
struct Vector {
T _data[size];
Vector (T* begin, T* end) {
std::copy (begin, end, _data);
}
// ...
void assign (T* begin, T* end) {
std::copy (begin, end, _data);
}
};
int
main (int argc, char *argv[])
{
int A1[4] = {1,2,3,4};
int A2[5] = {99,88,77,66,55};
Vector<int, 10> v1 (A1, A1+4);
// ...
v1.assign (A2, A2+5);
}
You have to supply the type and size of the array when defining the variable:
Vector<int, 10> test;
You can not however assign to the member array like a normal array. You have to assign each element separately:
for (int i = 0; i < 10; i++)
test.data[i] = i; // If instantiated with type "int"
You can only initialize an array at the point you are defining it:
Vector<unsigned char, 10> test;
There's your array, you are done defining it, your chance to initialize it has passed.
Edit: Seeing Mat's answer, memo to me: I have to read up on C++11, and soon... :-/
Edit 2: I just gave the information on what was wrong. Kerrek SB has the information on how to do it right. ;-)