Related
I struggle to pass any constexpr function as a parameter to the constexpr array computation.
How I would do this in a common C++ (not constexpr, just to show what I want)
float calcAdd2(float a) {
return a + a;
}
float calcPow2(float a)
{
return a * a;
}
template <class Func>
auto calcArrArithmetic(int size, Func func) {
std::vector<float> result;
for (auto i = 0; i < size; i++) {
result.emplace_back(func(i));
}
return result;
}
However, it's not that simple in constexpr. I started with plain array computation
template <std::size_t... I>
std::array<float, sizeof...(I)> fillArray(std::index_sequence<I...>) {
return std::array<float, sizeof...(I)>{
calcAdd2(I)...
};
}
template <std::size_t N>
std::array<float, N> fillArray() {
return fillArray(std::make_index_sequence<N>{});
}
static const auto CALC_FIRST_10_ADD2 = fillArray<10>();
Link. It worked. Now how to generalize calcAdd2 to be not only calcAdd2, but any constexpr function I would like to? My goal looks like:
static const auto CALC_FIRST_10_ADD2 = fillArray<10>(calcAdd2);
static const auto CALC_FIRST_10_POW2 = fillArray<10>(calcPow2);
EDIT:
C++17 Answer to the question by madhur4127.
EDIT2. C++20 Answer by BlackCatHole.
Here's the simplified version of your code that does what you want:
constexpr float calcAdd2(float a) { return a + a; }
constexpr float calcPow2(float a) { return a * a; }
template <std::size_t N, typename Func>
constexpr auto fillArray(Func&& func) {
std::array<float, N> ret{};
for(unsigned i=0;i<N;++i) {
ret[i] = func(i);
}
return ret;
}
constexpr auto CALC_FIRST_10_ADD2 = fillArray<10>(calcAdd2);
i am trying to change the data type of all the elements into a nested C array, something like this.
const int a[2][3] = {
{1,2,3},
{4,5,6}
}
The arrays are "multidimensional", and i don't know how many dimension they have.
I figured out something like this:
template <class D, class T, unsigned S>
inline D& uniform(T (&t)[S]) {
D v[S];
for (int k = 0; k < S; k++) {
v[k] = D(t[k]);
}
return v;
}
auto b = uniform<float>( a );
However the previous code works (or at least it is supposed to work) only if a is 1D, is there a way to make it work over multidimensional C arrays?
So, here's one way of doing it:
#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdio>
#include <type_traits>
// array_type_swap convert T[a][b][c][...] to Y[a][b][c][...] for arbitrary
// dimensions
template <class T, class Y>
struct array_type_swap {
using type = T;
};
template <class T, class Y, std::size_t N>
struct array_type_swap<T, std::array<Y, N>> {
using type = std::array<typename array_type_swap<T, Y>::type, N>;
};
template <class T, class Y, std::size_t N>
struct array_type_swap<T, Y[N]> {
using type = typename array_type_swap<T, std::array<Y, N>>::type;
};
template <class T, class Y>
using array_type_swap_t = typename array_type_swap<T, Y>::type;
template <class>
inline constexpr bool is_std_array_v = false;
template <class T, std::size_t N>
inline constexpr bool is_std_array_v<std::array<T, N>> = true;
// Get element count of a std::array, or C style array as constexpr. The value
// is 1 for all other types (as in array of 1).
template <class T>
struct contexpr_array_size {
static std::size_t constexpr size = 1;
};
template <class T, std::size_t N>
struct contexpr_array_size<T[N]> {
static std::size_t constexpr size = N;
};
template <class T, std::size_t N>
struct contexpr_array_size<std::array<T, N>> {
static std::size_t constexpr size = N;
};
template <class T>
inline auto constexpr contexpr_array_size_v = contexpr_array_size<T>::size;
template <class T, class Y>
void copy_array(T& dst, Y const& src) {
static_assert(contexpr_array_size_v<T> == contexpr_array_size_v<Y>,
"Can only copy arrays of the same size");
if constexpr (!is_std_array_v<Y> && !std::is_array_v<Y>)
dst = static_cast<T>(src);
else
for (std::size_t i = 0; i < contexpr_array_size_v<Y>; ++i)
copy_array(dst[i], src[i]);
}
template <class T, class Y>
auto uniform(Y const& arr) {
array_type_swap_t<T, Y> result;
copy_array(result, arr);
return result;
}
int main() {
std::puts("built-in array :");
const int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
auto b = uniform<float>(a);
for (auto& row : b) {
for (auto& elm : row) std::printf("%.2f ", elm);
std::putchar('\n');
}
std::puts("\nstd::array :");
std::array<std::array<int, 3>, 2> stdarr = {{{6, 5, 4}, {3, 2, 1}}};
b = uniform<float>(stdarr);
for (auto& row : b) {
for (auto& elm : row) std::printf("%.2f ", elm);
std::putchar('\n');
}
}
You can't return [] arrays from a function, so the 1D version doesn't work.
You can use std::array.
template <class D, class T, std::size_t S1, std::size_t S2>
inline std::array<std::array<D, S1>, S2> uniform(std::array<std::array<T, S1>, S2> t) {
std::array<std::array<D, S1>, S2> v;
std::array<D, S1>(*inner)(std::array<T, S1>) = uniform<D, T, S1>;
std::transform(t.begin(), t.end(), v.begin(), inner);
return v;
}
template <class D, class T, std::size_t S>
inline std::array<D, S> uniform(std::array<T, S> t) {
return { t.begin(), t.end() };
}
I am trying to write a function in order to generate arbitrarily nested vectors and initialize with the given specific value in C++. For example, auto test_vector = n_dim_vector_generator<2, long double>(static_cast<long double>(1), 1); is expected to create a "test_vector" object which type is std::vector<std::vector<long double>>. The content of this test_vector should as same as the following code.
std::vector<long double> vector1;
vector1.push_back(1);
std::vector<std::vector<long double>> test_vector;
test_vector.push_back(vector1);
The more complex usage of the n_dim_vector_generator function:
auto test_vector2 = n_dim_vector_generator<15, long double>(static_cast<long double>(2), 3);
In this case, the parameter static_cast<long double>(2) is as the data in vectors and the number 3 is as the push times. So, the content of this test_vector2 should as same as the following code.
std::vector<long double> vector1;
vector1.push_back(static_cast<long double>(2));
vector1.push_back(static_cast<long double>(2));
vector1.push_back(static_cast<long double>(2));
std::vector<std::vector<long double>> vector2;
vector2.push_back(vector1);
vector2.push_back(vector1);
vector2.push_back(vector1);
std::vector<std::vector<std::vector<long double>>> vector3;
vector3.push_back(vector2);
vector3.push_back(vector2);
vector3.push_back(vector2);
//...Totally repeat 15 times in order to create test_vector2
std::vector<...std::vector<long double>> test_vector2;
test_vector2.push_back(vector14);
test_vector2.push_back(vector14);
test_vector2.push_back(vector14);
The detail to implement n_dim_vector_generator function is as follows.
#include <iostream>
#include <vector>
template <typename T, std::size_t N>
struct n_dim_vector_type;
template <typename T>
struct n_dim_vector_type<T, 0> {
using type = T;
};
template <typename T, std::size_t N>
struct n_dim_vector_type {
using type = std::vector<typename n_dim_vector_type<T, N - 1>::type>;
};
template<std::size_t N, typename T>
typename n_dim_vector_type<T,N>::type n_dim_vector_generator(T t, unsigned int);
template <std::size_t N, typename T>
typename n_dim_vector_type<T, N>::type n_dim_vector_generator<N, T>(T input_data, unsigned int push_back_times) {
if (N == 0)
{
return std::move(input_data);
}
typename n_dim_vector_type<T, N>::type return_data;
for (size_t loop_number = 0; loop_number < push_back_times; loop_number++)
{
return_data.push_back(n_dim_vector_generator<N - 1, T>(input_data, push_back_times));
}
return return_data;
}
As a result, I got an error 'return': cannot convert from 'long double' to 'std::vector<std::vector<long double,std::allocator<long double>>,std::allocator<std::vector<long double,std::allocator<long double>>>>' I know that it caused by if (N == 0) block which is as the terminate condition to recursive structure. However, if I tried to edit the terminate condition into separate form.
template <typename T>
inline T n_dim_vector_generator<0, T>(T input_data, unsigned int push_back_times) {
return std::move(input_data);
}
template <std::size_t N, typename T>
typename n_dim_vector_type<T, N>::type n_dim_vector_generator<N, T>(T input_data, unsigned int push_back_times) {
typename n_dim_vector_type<T, N>::type return_data;
for (size_t loop_number = 0; loop_number < push_back_times; loop_number++)
{
return_data.push_back(n_dim_vector_generator<N - 1, T>(input_data, push_back_times));
}
return return_data;
}
The error 'n_dim_vector_generator': illegal use of explicit template arguments happened. Is there any better solution to this problem?
The develop environment is in Windows 10 1909 with Microsoft Visual Studio Enterprise 2019 Version 16.4.3
To achieve your specific mapping of:
auto test_vector = n_dim_vector_generator<2, long double>(2, 3)
to a 3x3 vector filled with 2's, your template can be a bit simpler if you take advantage of this vector constructor:
std::vector<std::vector<T>>(COUNT, std::vector<T>(...))
Since vector is copyable, this will fill COUNT slots with a different copy of the vector. So...
template <size_t N, typename T>
struct n_dim_vector_generator {
using type = std::vector<typename n_dim_vector_generator<N-1, T>::type>;
type operator()(T value, size_t size) {
return type(size, n_dim_vector_generator<N-1, T>{}(value, size));
}
};
template <typename T>
struct n_dim_vector_generator<0, T> {
using type = T;
type operator()(T value, size_t size) {
return value;
}
};
usage:
auto test_vector = n_dim_vector_generator<2, long double>{}(2, 3);
Demo: https://godbolt.org/z/eiDAUG
For the record, to address some concerns from the comments, C++ has an idiomatic, initializable, contiguous-memory class equivalent of a multi-dimension C array: a nested std::array:
std::array<std::array<long double, COLUMNS>, ROWS> test_array = { /*...*/ };
for (auto& row : test_array)
for (auto cell : row)
std::cout << cell << std::endl;
If you wanted to reduce the boilerplate to declare one, you can use a struct for that:
template <typename T, size_t... N>
struct multi_array;
template <typename T, size_t NFirst, size_t... N>
struct multi_array<T, NFirst, N...> {
using type = std::array<typename multi_array<T, N...>::type, NFirst>;
};
template <typename T, size_t NLast>
struct multi_array<T, NLast> {
using type = std::array<T, NLast>;
};
template <typename T, size_t... N>
using multi_array_t = typename multi_array<T, N...>::type;
Then to use:
multi_array_t<long double, ROWS, COLUMNS> test_array = { /*...*/ };
for (auto& row : test_array)
for (auto cell : row)
std::cout << cell << std::endl;
This is allocated on the stack, like a C array. That will eat up your stack space for a big array of course. But you can make a decorator range around std::unique_ptr to make a pointer to one a bit easier to access:
template <typename T, size_t... N>
struct dynamic_multi_array : std::unique_ptr<multi_array_t<T, N...>> {
using std::unique_ptr<multi_array_t<T, N...>>::unique_ptr;
constexpr typename multi_array_t<T, N...>::value_type& operator [](size_t index) { return (**this)[index]; }
constexpr const typename multi_array_t<T, N...>::value_type& operator [](size_t index) const { return (**this)[index]; }
constexpr typename multi_array_t<T, N...>::iterator begin() { return (**this).begin(); }
constexpr typename multi_array_t<T, N...>::iterator end() { return (**this).end(); }
constexpr typename multi_array_t<T, N...>::const_iterator begin() const { return (**this).begin(); }
constexpr typename multi_array_t<T, N...>::const_iterator end() const { return (**this).end(); }
constexpr typename multi_array_t<T, N...>::const_iterator cbegin() const { return (**this).cbegin(); }
constexpr typename multi_array_t<T, N...>::const_iterator cend() const { return (**this).cend(); }
constexpr typename multi_array_t<T, N...>::size_type size() const { return (**this).size(); }
constexpr bool empty() const { return (**this).empty(); }
constexpr typename multi_array_t<T, N...>::value_type* data() { return (**this).data(); }
constexpr const typename multi_array_t<T, N...>::value_type* data() const { return (**this).data(); }
};
(let the buyer beware if you use those methods with nullptr)
Then you can still brace-initialize a new expression and use it like a container:
dynamic_multi_array<long double, ROWS, COLUMNS> test_array {
new multi_array_t<long double, ROWS, COLUMNS> { /* ... */ }
};
for (auto& row : test_array)
for (auto cell : row)
std::cout << cell << std::endl;
Demo: https://godbolt.org/z/lUwVE_
I am currently creating arithmetic operators libraries for high level synthesis.
For this, I am also creating a library to manipulate bits and bit vectors like it would be done in VHDL. To make my libraries synthesizable, nearly everything must be resolved at compile time.
However, I have an issue with loops.
Indeed, I would like to be able to write things like that:
const int N = 5;
for(int i = 0; i < N-2; i++) {
x.bit<i+2>() = x.bit<i>();
}
Of course, it does not compile since i is a variable and not a constant determined at compile time.
However, N being a constant, this code is strictly equivalent to:
x.bit<2>() = x.bit<0>();
x.bit<3>() = x.bit<1>();
x.bit<4>() = x.bit<2>();
which compiles and works perfectly.
Is there a way to make the compiler (gcc in my case) unroll the loop since N is constant? Or to define a macro or a constexpr which could do it with a clean syntax? This would be the equivalent of for generate in VHDL.
While constexpr has got much more powerful in C++14/17 it is not yet possible to mix this kind of compile time / template code with an ordinary loop. There is some talk of introducing a construct that might enable that in a future version of C++. For now you have a few choices, either recursive calls to a function with an integer template argument or probably simpler in this case a C++17 fold expression. You could also use C++11 variadic template expansion to get a similar result to fold expressions in this example, though fold expressions are more powerful.
Just saw your comment about being stuck with C++11, you're probably better off using the recursive function approach I think. I've added that approach to the example.
If you were able to use C++14 you might also want to consider moving entirely into constexpr function / type land so your bit<I>() function would not be templated but would be just a constexpr function bit(i). You could then use normal functions and loops. Given the C++11 restrictions on constexpr functions that is probably less useful in your case however. I've added an example using that approach.
#include <iostream>
#include <utility>
template <size_t N>
struct bits {
bool bs[N];
template <size_t I>
constexpr const bool& bit() const {
return bs[I];
}
template <size_t I>
constexpr bool& bit() {
return bs[I];
}
constexpr bool bit(int i) const { return bs[i]; }
constexpr void bit(int i, bool x) { bs[i] = x; }
};
// Using C++17 fold expressions
template <size_t N, size_t... Is>
constexpr bits<N> set_bits_helper(bits<N> x, std::index_sequence<Is...>) {
((x.bit<Is + 2>() = x.bit<Is>()), ...);
return x;
}
template <size_t N>
constexpr bits<N> set_bits(bits<N> x) {
return set_bits_helper(x, std::make_index_sequence<N - 2>{});
}
// Using recursive template function, should work on C++11
template <size_t I, size_t N>
constexpr bits<N> set_bits_recursive_helper(bits<N> x, std::integral_constant<size_t, I>) {
x.bit<N - I>() = x.bit<N - I - 2>();
return set_bits_recursive_helper(x, std::integral_constant<size_t, I - 1>{});
}
template <size_t N>
constexpr bits<N> set_bits_recursive_helper(bits<N> x, std::integral_constant<size_t, 0>) { return x; }
template <size_t N>
constexpr bits<N> set_bits_recursive(bits<N> x) {
return set_bits_recursive_helper(x, std::integral_constant<size_t, N - 2>{});
}
// Using non template constexpr functions
template <size_t N>
constexpr bits<N> set_bits_constexpr(bits<N> x) {
for (int i = 0; i < N - 2; ++i) {
x.bit(i + 2, x.bit(i));
}
return x;
}
// Test code to show usage
template <size_t N>
void print_bits(const bits<N>& x) {
for (auto b : x.bs) {
std::cout << b << ", ";
}
std::cout << '\n';
}
void test_set_bits() {
constexpr bits<8> x{ 1, 0 };
print_bits(x);
constexpr auto y = set_bits(x);
static_assert(y.bit<2>() == x.bit<0>());
print_bits(y);
}
void test_set_bits_recursive() {
constexpr bits<8> x{ 1, 0 };
print_bits(x);
constexpr auto y = set_bits_recursive(x);
static_assert(y.bit<2>() == x.bit<0>());
print_bits(y);
}
void test_set_bits_constexpr() {
constexpr bits<8> x{ 1, 0 };
print_bits(x);
constexpr auto y = set_bits_constexpr(x);
static_assert(y.bit<2>() == x.bit<0>());
print_bits(y);
}
int main() {
test_set_bits();
test_set_bits_recursive();
test_set_bits_constexpr();
}
Also without std::integer_sequence (but I suggest to implement a substitute and use it), in C++11 you can use template partial specialization.
I mean that you can implement something like
template <int I, int Sh, int N>
struct shiftVal
{
template <typename T>
static int func (T & t)
{ return t.template bit<I+Sh>() = t.template bit<I>(),
shiftVal<I+1, Sh, N>::func(t); }
};
template <int I, int Sh>
struct shiftVal<I, Sh, I>
{
template <typename T>
static int func (T &)
{ return 0; }
};
and your cycle become
shiftVal<0, 2, N-2>::func(x);
The following is a full working example
#include <array>
#include <iostream>
template <std::size_t N>
struct foo
{
std::array<int, N> arr;
template <int I>
int & bit ()
{ return arr[I]; }
};
template <int I, int Sh, int N>
struct shiftVal
{
template <typename T>
static int func (T & t)
{ return t.template bit<I+Sh>() = t.template bit<I>(),
shiftVal<I+1, Sh, N>::func(t); }
};
template <int I, int Sh>
struct shiftVal<I, Sh, I>
{
template <typename T>
static int func (T &)
{ return 0; }
};
int main ()
{
foo<10U> f { { { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 } } };
for ( auto const & i : f.arr )
std::cout << i << ' ';
std::cout << std::endl;
shiftVal<0, 2, 10-2>::func(f);
for ( auto const & i : f.arr )
std::cout << i << ' ';
std::cout << std::endl;
}
Nobody else produce an example based on a C++11 simulation of std::integer_sequence (as suggested by W.F., Passer By and Sopel and the simpler solution, IMHO) so I propose the following one (of std::index_sequence and std::make_index_sequence in reality: simulate std::integer_sequence is more complicated)
template <std::size_t ...>
struct indexSequence
{ };
template <std::size_t N, std::size_t ... Next>
struct indexSequenceHelper : public indexSequenceHelper<N-1U, N-1U, Next...>
{ };
template <std::size_t ... Next>
struct indexSequenceHelper<0U, Next ... >
{ using type = indexSequence<Next ... >; };
template <std::size_t N>
using makeIndexSequence = typename indexSequenceHelper<N>::type;
So a function (with function helper) to reproduce the asked loop can be written as
template
void shiftValHelper (T & t, indexSequence<Is...> const &)
{
using unused = int[];
(void)unused { 0,
(t.template bit<Is+Sh>() = t.template bit<Is>(), 0)... };
}
template <std::size_t Sh, std::size_t N, typename T>
void shiftVal (T & t)
{ shiftValHelper<Sh>(t, makeIndexSequence<N>{}); }
and called ad follows
shiftVal<2, N-2>(x);
The following is a full working example
#include <array>
#include <iostream>
template <std::size_t ...>
struct indexSequence
{ };
template <std::size_t N, std::size_t ... Next>
struct indexSequenceHelper : public indexSequenceHelper<N-1U, N-1U, Next...>
{ };
template <std::size_t ... Next>
struct indexSequenceHelper<0U, Next ... >
{ using type = indexSequence<Next ... >; };
template <std::size_t N>
using makeIndexSequence = typename indexSequenceHelper<N>::type;
template <std::size_t N>
struct foo
{
std::array<int, N> arr;
template <std::size_t I>
int & bit ()
{ return arr[I]; }
};
template <std::size_t Sh, typename T, std::size_t ... Is>
void shiftValHelper (T & t, indexSequence<Is...> const &)
{
using unused = int[];
(void)unused { 0,
(t.template bit<Is+Sh>() = t.template bit<Is>(), 0)... };
}
template <std::size_t Sh, std::size_t N, typename T>
void shiftVal (T & t)
{ shiftValHelper<Sh>(t, makeIndexSequence<N>{}); }
int main ()
{
foo<10U> f { { { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 } } };
for ( auto const & i : f.arr )
std::cout << i << ' ';
std::cout << std::endl;
shiftVal<2, 10-2>(f);
for ( auto const & i : f.arr )
std::cout << i << ' ';
std::cout << std::endl;
}
I'm trying to get familiar with C++ templates. I need to write a template of function that concatenates 2 arrays:
template<typename T, int Size>
class Array
{
public:
void push(int i, const T& t) { _elem[i] = t; }
private:
T _elem[Size];
};
For example I have 2 arrays:
Array<int,3> a1;
Array<int,4> a2;
I don't know how to write this function, that will return
Array<int,7>.
How should header of this function look like?
You should try it like this:
template<typename T, int A, int B>
Array<T, A+B> concatenate(Array<T, A> first, Array<T, B> second)
{
Array<T, A+B> result;
for (int idx = 0; idx < A; ++idx) {
result.push(idx, first[idx]);
}
for (int idx = 0; idx < B; ++idx) {
result.push(idx+A, second[idx]);
}
return result;
}
You could do it like this, as a free-function outside the class:
template <typename T, int SizeA, int SizeB>
Array<T, SizeA + SizeB> join(const Array<T, SizeA>& first,
const Array<T, SizeB>& second)
{
/* ... */
}
For what it's worth, you should probably use std::size_t from <cstddef> instead of int.