How to pass an empty span object? - c++

Is there a way to pass an empty std::span<int> to a function?
I have a function like below:
bool func( const std::vector<int>& indices )
{
if ( !indices.empty( ) )
{
/* do something */
}
...
}
// when calling it with an empty vector
const bool isAcceptable { func( std::vector<int>( 0 ) ) };
And I want to change it to use std::span instead of std::vector so that it can also get std::array and raw array as its argument.
Now here:
bool func( const std::span<const int> indices )
{
if ( !indices.empty( ) )
{
/* do something */
}
...
}
// when calling it with an empty span
const bool isAcceptable { func( std::span<int>( ) ) }; // Is this valid code?
Also does std::span properly support all contiguous containers (e.g. std::vector, std::array, etc.)?

std::span's default constuctor is documented as:
constexpr span() noexcept;
Constructs an empty span whose data() == nullptr and size() == 0.
Hence, passing a default constructed std::span<int>() is well-defined. Calling empty() on it is guaranteed to return true.
Does std::span properly support all contiguous containers (e.g. std::vector, std::array, etc.)?
Basically, std::span can be constructed from anything that models a contiguous and sized range:
template<class R>
explicit(extent != std::dynamic_extent)
constexpr span(R&& range);
Constructs a span that is a view over the range range; the resulting span has size() == std::ranges::size(range) and data() == std::ranges::data(range).
In particular, std::vector does satisfy these requirements.
For C-style arrays and std::array there are special constructors (to harness their compile-time size):
template<std::size_t N>
constexpr span(element_type (&arr)[N]) noexcept;
template<class U, std::size_t N>
constexpr span(std::array<U, N>& arr) noexcept;
template<class U, std::size_t N>
constexpr span(const std::array<U, N>& arr) noexcept;
Constructs a span that is a view over the array arr; the resulting span has size() == N and data() == std::data(arr).

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>());

How to make class compatible with std::span constructor that takes a range?

I'd like to be able to pass my custom container this std::span constructor:
template< class R >
explicit(extent != std::dynamic_extent)
constexpr span( R&& range );
What do I need to add to my custom class to make it satisfy the requirements to be able to pass it to the std::span constructor that receives a range?
For example, with std::vector we are able to do this:
std::vector<int> v = {1, 2, 3};
auto span = std::span{v};
I've already added these to my custom class:
Type* begin()
{
return m_Data;
}
Type* end()
{
return m_Data + m_Length;
}
const Type* data() const
{
return m_Data;
}
size_t size() const
{
return m_Length;
}
...which in turn allowed me to use range-based loops, and std::data(my_container) as well as std::size(my_container). What am I missing to make it so that I can also pass my container to the std::span constructor? Does it require to implement a more complex iterator?
This is because your Container does not satisfy contiguous_range, which is defined as:
template<class T>
concept contiguous_­range =
random_­access_­range<T> && contiguous_­iterator<iterator_t<T>> &&
requires(T& t) {
{ ranges::data(t) } -> same_­as<add_pointer_t<range_reference_t<T>>>;
};
In the requires clause, the return type of ranges::data(t) is const Type*, which is different from add_pointer_t<range_reference_t<T>> that is Type*.
The workaround is adding a non-const data() to your Container which return Type*:
Type* data() { return m_Data; }

How to let a `std::vector<int32_t>` take memory from a `std::vector<uint32_t>&&`?

template<typename T>
struct raster {
std::vector<T> v;
template<typename U, typename = std::enable_if_t<sizeof(T) == sizeof(U)>>
raster(raster<U>&& other){
// What code goes here?
}
}
Suppose we have raster<uint32_t> r such that r.v.size() is in the millions, and a guarantee that all its elements are within int32_t's range. Is it possible for raster<int32_t>::raster(raster<uint32_t>&& other) to avoid copying the memory backing other.v?
Or should I just do something like *reinterpret_cast<raster<int32_t>*>(&r) instead of calling that constructor?
There is no legal way to do this in C++; you can only move buffers from a std::vector to another std::vector of the exact same type.
There are a variety of ways you can hack this. The most illegal and evil would be
std::vector<uint32_t> evil_steal_memory( std::vector<int32_t>&& in ) {
return reinterpret_cast< std::vector<uint32_t>&& >(in);
}
or something similar.
A less evil way would be to forget it is a std::vector at all.
template<class T>
struct buffer {
template<class A>
buffer( std::vector<T,A> vec ):
m_begin( vec.data() ),
m_end( m_begin + vec.size() )
{
m_state = std::unique_ptr<void, void(*)(void*)>(
new std::vector<T,A>( std::move(vec) ),
[](void* ptr){
delete static_cast<std::vector<T,A>*>(ptr);
}
);
}
buffer(buffer&&)=default;
buffer& operator=(buffer&&)=default;
~buffer() = default;
T* begin() const { return m_begin; }
T* end() const { return m_end; }
std::size_t size() const { return begin()==end(); }
bool empty() const { return size()==0; }
T* data() const { return m_begin; }
T& operator[](std::size_t i) const {
return data()[i];
}
explicit operator bool() const { return (bool)m_state; }
template<class U>
using is_buffer_compatible = std::integral_constant<bool,
sizeof(U)==sizeof(T)
&& alignof(U)==alignof(T)
&& !std::is_pointer<T>{}
>;
template<class U,
std::enable_if_t< is_buffer_compatible<U>{}, bool > = true
>
buffer reinterpret( buffer<U> o ) {
return {std::move(o.m_state), reinterpret_cast<T*>(o.m_begin()),reinterpret_cast<T*>(o.m_end())};
}
private:
buffer(std::unique_ptr<void, void(*)(void*)> state, T* b, T* e):
m_state(std::move(state)),
m_begin(begin),
m_end(end)
{}
std::unique_ptr<void, void(*)(void*)> m_state;
T* m_begin = 0;
T* m_end = 0;
};
live example: this type erases a buffer of T.
template<class T>
struct raster {
buffer<T> v;
template<typename U, typename = std::enable_if_t<sizeof(T) == sizeof(U)>>
raster(raster<U>&& other):
v( buffer<T>::reinterpret( std::move(other).v ) )
{}
};
note that my buffer has a memory allocation in it; compared to millions of elements that is cheap. It is also move-only.
The memory allocation can be eliminated through careful use of the small buffer optimization.
I'd leave it move-only (who wants to accidentally copy a million elements?) and maybe write
buffer clone() const;
which creates a new buffer with the same contents.
Note that instead of a const buffer<int> you should use a buffer<const int> under the above design. You can change that by duplicating the begin() const methods to have const and non-const versions.
This solution relies on your belief that reinterpreting a buffer of int32_ts as a buffer of uint32_ts (or vice versa) doesn't mess with anything. Your compiler may provide this guarantee, but the C++ standard does not.
The problem is that the implementation of the vector template itself may be specialised for the type. For some weird whacky reason we don't understand today, the top-level vector might need an extra member not provided in vector, so simply reinterpret casting will not work safely.
Another evil approach might be to look at the Allocator of your two vectors.
If this was
a custom allocator you had written and both were a derived class from vector
and you wrote an overload in the class for swap and =&&
within which you created wrapped tmp vectors to swap with
and detected that the Allocator was being called within those temporary objects constructors/destructors, and on the same thread
to release and reallocate the same sized array
Then, perhaps you could legitimately pass the memory buffer between them without resetting the content.
But that is a lot of fragile work!

Template of array of function pointers

I've got a few functions, some of which are overloaded and some are templates, ex.:
void fun1 (vector<string> &a, int b);
void fun1 (vector<double> &a, int b);
template <typename t>
void fun2 (t a[], int b);
and so on. Every function I use has a version for 2 data types, one is an array and the other one is a vector (a vector of strings, a vector of doubles, an array of strings and an array of doubles). The question is, can I create a template for an array of pointers? Is there any way of doing it, apart from:
void (*strvecfun[])(vector <string>&, long, long)={fun1, fun2};
void (*dblvecfun[])(vector <double>&, long, long)={fun1, fun2};
void (*strarrfun[])(string [], long, long)={fun1, fun2};
and so on?
You can use
template<typename Func>
struct func_array {
static Func *const data[];
};
template<typename Func>
Func *const func_array<Func>::data[] = { fun1, fun2 };
And later call
func_array<void(std::vector<double>&, long, long)>::data[0](dvec, l1, l2);
func_array<void(std::vector<string>&, long, long)>::data[1](svec, l1, l2);
// ...and so forth
This requires that there are matching overloads for all the signatures you're going to use of all functions you put into the list, naturally.
Instead of having 2 implementations, have one. Have your data take an array_view<double>:
template<class T>
struct array_view {
// can make this private:
T* b = 0; T* e = 0;
// core methods:
T* begin() const { return b; }
T* end() const { return e; }
// utility methods:
size_t size() const { return end()-begin(); }
T& front() const { return *begin(); }
T& back() const { return *std::prev(end()); }
bool empty() const { return begin()==end(); }
// core ctors:
array_view(T* s, T* f):b(s),e(f) {};
array_view()=default;
array_view(array_view const&)=default;
// derived ctors:
array-view(T* s, size_t l):array_view(s, s+l) {};
template<size_t N>
array_view( T(&arr)[N] ):array_view(arr, N) {};
template<size_t N>
array_view( std::array<T,N>&arr ):array_view(arr.data(), N) {};
template<class A>
array_view( std::vector<T,A>& v ):array_view(v.data(), v.size()) {};
// extra ctors that fail to compile if `T` is not const, but
// are mostly harmless even if `T` is not const, and useful if
// `T` is const. We could do fancy work to disable them, but
// I am lazy:
using non_const_T = std::remove_const_t<T>;
template<class A>
array_view( std::vector<non_const_T,A>const& v ):array_view(v.data(), v.size()) {};
template<size_t N>
array_view( std::array<non_const_T,N>const&arr ):array_view(arr.data(), N) {};
array_view( std::initializer_list<non_const_T> il ):array_view(il.data(), il.size()) {};
};
array_view acts like a view into a container, and can be implicitly converted from a number of std containers as well as raw arrays.
void fun1 (array_view<std::string> a);
a.size() tells you how long it is, and it can be iterated over in a for(:) loop even.
std::vector<T>& is far more powerful than what you need. By using array_view, we only expose what you need (access to elements), and thus are able to take both an array and a container.
If you pass in a "real" C style array, it will auto-deduce the length. If you instead pass in a pointer (or a [] really-a-pointer array), you also have to pass the length like:
fun1( {ptr, length} );
Create a function called max that will return the value of the largest element in an array.
The arguments to the function should be the address of the array size.
Make this function into a template so it will work with an array of any numerical types.

C++ array wrapper

I've wanted a wrapper around arrays, such, it would be stored at the stack - to be not concerned about memory releasing - be initializable via brace lists, and possibly be substitutable in any place of an ordinary array. Then, I've produced the following code. And now am wondering, have I missed something. -- So - is it what I've wanted?
template<class T, size_t size>
struct Array
{
T body[size];
operator T* () { return body; }
};
Edit:
I might be imprecise. The wrapper is only for constructional purpose. It shall be used for constructing arrays from brace lists, when being in an initialization list (primarily). Like
class A {
protected: A(int array[])
...
class B : public A {
public: B() :
A( (Array<int, 2>) {{ 1, 2 }} )
...
There was a proposition of a const version of the casting operator. - I've been considering this, but am not sure, is it really needed. While casting to const T[] is done implicitly through the existing operator, and a constant array can be defined by giving T = const ..., is there still a reason?
For a basic example, I don't think there's much you can improve on, except for a few helper functions. In particular, it would be nice to have a method that returns the size:
constexpr std::size_t size() const { return size; }
In addition, here are a few others:
const/non-const overloads of operator[N]:
As #ChristianRau stated in the comments, a operator T* provides a non-const version. We can implement the const version as such:
T const& operator [](std::size_t n) const
{
return body[n];
}
// similarly for non-const:
T& operator [](std::size_t n) { return body[n]; }
begin() and end() sequencers (very useful e.g. for the C++11 range-based for):
T* begin() { return body; }
T* end() { return body + size; }
// const versions... very much the same
T const* cbegin() const { return body; }
T const* cend() const { return body + size; }
T const* begin() const { return cbegin(); }
T const* end() const { return cend(); }
an at() method, which includes bounds checking (as opposed to operator[] by convention):
T const& at(std::size_t offset) const
{
// You should do bounds checking here
return body[offset];
}
// also a non-const version again..
It would also be nice to have a constructor that takes an std::initializer_list<T> so that you don't have to use the aggregate-initialization:
#include <algorithm>
#include <initializer_list>
template <typename T, std::size_t N>
struct Array
{
...
Array(std::initializer_list<T> const& list)
{
std::copy(list.begin(), list.end(), body);
}
...
};
Here is another one suggested by #DyP (initializer list always copies, perfect forwarding tries to avoid that):
template <typename T, std::size_t N>
struct Array
{
...
template <typename... Args>
// possibly constexpr
Array(Args&&... args) : body{ std::forward<Args>(args)... }
{}
...
};
Here is the program in action if you want to see it -- http://ideone.com/Zs27it#view_edit_box
There are others features you can include, but as I said this is a basic example, and you would most likely be better off using something like std::array which has more or less the same methods.