I have the following code where I am irritated by the fact that compiler is unable to see that variable passed as argument to a function is constexpr so I must use arity 0 function instead of 1 argument function.
I know this is not a compiler bug, but I wonder if there are idioms that enable to workaround this problem.
#include <array>
#include <iostream>
static constexpr std::array<int, 5> arr{11, 22, 33, 44, 55};
template <typename C, typename P, typename Y>
static constexpr void copy_if(const C& rng, P p, Y yi3ld) {
for (const auto& elem: rng) {
if (p(elem)){
yi3ld(elem);
}
}
}
// template<std::size_t N>
static constexpr auto get_evens(/* const std::array<int, N>& arr */) {
constexpr auto is_even = [](const int i) constexpr {return i % 2 == 0;};
constexpr int cnt = [/* &arr, */&is_even]() constexpr {
int cnt = 0;
auto increment = [&cnt] (const auto&){cnt++;};
copy_if(arr, is_even, increment);
return cnt;
}();
std::array<int, cnt> result{};
int idx = 0;
copy_if(arr, is_even, [&result, &idx](const auto& val){ result[idx++] = val;});
return result;
}
int main() {
// constexpr std::array<int, 5> arr{11, 22, 33, 44, 55};
for (const int i:get_evens(/* arr */)) {
std::cout << i << " " << std::endl;
}
}
If it is not obvious what I want: I would like to change get_evens signature so that it is template templated on array size N and that it takes 1 argument of type const std::array<int, N>&.
The error message when I change arr to be an function argument isn't helpful:
prog.cc:25:21: note: initializer of 'cnt' is not a constant expression
prog.cc:19:19: note: declared here
constexpr int cnt = [&arr, &is_even]()constexpr {
A function argument is never a constant expression, even if a function is used in constexpr context:
constexpr int foo(int i)
{
// i is not a constexpr
return i + 1;
}
constexpr auto i = 1;
constexpr auto j = foo(i);
To mimic a constexpr argument, use a template parameter:
template<int i>
constexpr int foo()
{
// i is constexpr
return i + 1;
}
constexpr auto i = 1;
constexpr auto j = foo<i>();
A possible solution is to use std::integer_sequence to encode integers into a type:
#include <array>
#include <iostream>
#include <type_traits>
template<typename P, typename Y, int... elements>
constexpr void copy_if_impl(P p, Y yi3ld, std::integer_sequence<int, elements...>) {
((p(elements) && (yi3ld(elements), true)), ...);
}
template<typename arr_t, typename P, typename Y>
constexpr void copy_if(P p, Y yi3ld) {
copy_if_impl(p, yi3ld, arr_t{});
}
template<typename arr_t>
constexpr auto get_evens(){
constexpr auto is_even = [](const int i) constexpr { return i % 2 == 0; };
constexpr int cnt = [&is_even]() constexpr {
int cnt = 0;
auto increment = [&cnt](const auto&) { cnt++; };
copy_if<arr_t>(is_even, increment);
return cnt;
}();
std::array<int, cnt> result{};
int idx = 0;
copy_if<arr_t>(is_even, [&result, &idx](const auto& val) {
result[idx++] = val; });
return result;
}
int main()
{
using arr = std::integer_sequence<int, 11, 22, 33, 44, 55>;
for (const int i : get_evens<arr>()) {
std::cout << i << " " << std::endl;
}
}
Addition suggested by Constantinos Glynos.
From Effective Modern C++ book by Scott Meyers, item 15, p.98:
constexpr functions can be used in contexts that demand compile-time constants. If the values of the arguments you pass to a constexpr function in such a context are known during compilation, the result will be computed during compilation. If any of the arguments’ values is not known during compilation, your code will be rejected.
When a constexpr function is called with one or more values that are not known during compilation, it acts like a normal function, computing its result at runtime. This means you don’t need two functions to perform the same operation, one for compile-time constants and one for all other values. The constexpr function does it all.
The other answer has a correct work around but I think the reasoning has nothing to do with parameters but instead to do with the lambda capture here:
constexpr int cnt = [/* &arr, */&is_even]()
Indeed we can test the various scenarios with this code:
#include <array>
#include <iostream>
template <size_t N>
constexpr int foo(const std::array<int, N>& arr) {
return [&arr] () { return arr.size(); }();
}
template <size_t N>
constexpr int bar(const std::array<int, N>& arr) {
int res{};
for (auto i : arr) {
res++;
}
return res;
}
template <size_t N>
constexpr int baz(const std::array<int, N>& arr) {
constexpr int test = [&arr] () constexpr {
return bar(arr);
}();
return test;
}
int main() {
constexpr std::array<int, 5> arr{11, 22, 33, 44, 55};
constexpr std::array<int, foo(arr)> test{};
constexpr std::array<int, bar(arr)> test2{};
constexpr std::array<int, baz(arr)> test3{};
}
Note that the line where test3 is initialized fails to compile. This, however, compiles just fine:
template <size_t N>
constexpr int baz(const std::array<int, N>& arr) {
return bar(arr);
}
So, what's the problem here? Well lambdas are really just glorified functors, and internally it'll look something like this:
struct constexpr_functor {
const std::array<int, 5>& arr;
constexpr constexpr_functor(const std::array<int, 5>& test)
: arr(test) { }
constexpr int operator()() const {
return bar(arr);
}
};
// ...
constexpr constexpr_functor t{arr};
constexpr std::array<int, t()> test3{};
Notice now that we get an error message showing the real problem:
test.cpp:36:33: note: reference to 'arr' is not a constant expression
test.cpp:33:34: note: declared here
constexpr std::array<int, 5> arr{11, 22, 33, 44, 55};
The other answer quotes Scotts Meyer's book but misinterprets the quotes. The book actually shows several examples of parameters being used in constexpr situations, but the quotes are simply saying that if you pass a non-constexpr parameter, the function can run at compile-time.
Following the Evg's suggestion, so passing the numbers as template parameters of a std::integer_sequence, but passing the integer sequence as argument of the get_evens() function, and not as template parameter, you can use the numbers directly inside get_evens().
I mean... you can simplify the get_evens() as follows (EDIT: further simplified following a suggestion from Evg (Thanks!))
template <typename T, T ... Ts>
constexpr auto get_evens (std::integer_sequence<T, Ts...> const &)
{
std::array<T, (std::size_t(!(Ts & T{1})) + ...)> result{};
std::size_t idx = 0;
((void)(Ts & 1 || (result[idx++] = Ts, true)), ...);
return result;
}
and you can use it this way
int main()
{
using arr = std::integer_sequence<int, 11, 22, 33, 44, 55>;
for ( const int i : get_evens(arr{}) )
std::cout << i << " " << std::endl;
}
#include <array>
#include <iostream>
static constexpr std::array<int, 5> arr{11, 22, 33, 44, 55};
template <typename C, typename P, typename T>
static constexpr void invoke_if(const C& rng, P p, T target) {
for (const auto& elem: rng) {
if (p(elem)){
target(elem);
}
}
}
constexpr bool is_even(int i) {
return i % 2 == 0;
}
template<std::size_t N>
constexpr std::size_t count_evens(const std::array<int, N>& arr)
{
std::size_t cnt = 0;
invoke_if(arr, is_even, [&cnt](auto&&){++cnt;});
return cnt;
}
template<std::size_t cnt, std::size_t N>
static constexpr auto get_evens(const std::array<int, N>& arr) {
std::array<int, cnt> result{};
int idx = 0;
invoke_if(arr, is_even, [&result, &idx](const auto& val){ result[idx++] = val;});
return result;
}
int main() {
// constexpr std::array<int, 5> arr{11, 22, 33, 44, 55};
for (const int i:get_evens<count_evens(arr)>(arr)) {
std::cout << i << " " << std::endl;
}
}
this works in g++, but in clang we get a problem because the begin on an array isn't properly constexpr with at least one library. Or maybe g++ violates the standard and clang does not.
template<auto t0, auto...ts>
struct ct_array:
std::array<decltype(t0) const, 1+sizeof...(ts)>,
std::integer_sequence<decltype(t0), t0, ts...>
{
ct_array():std::array<decltype(t0) const, 1+sizeof...(ts)>{{t0, ts...}} {};
};
template<class target, auto X>
struct push;
template<auto X>
struct push<void, X>{using type=ct_array<X>;};
template<auto...elems, auto X>
struct push<ct_array<elems...>, X>{using type=ct_array<elems...,X>;};
template<class target, auto X>
using push_t= typename push<target, X>::type;
template<class target>
struct pop;
template<auto x>
struct pop<ct_array<x>>{using type=void;};
template<auto x0, auto...xs>
struct pop<ct_array<x0, xs...>>{using type=ct_array<xs...>;};
template<class target>
using pop_t=typename pop<target>::type;
template<class lhs, class rhs, class F, class=void>
struct transcribe;
template<class lhs, class rhs, class F>
using transcribe_t = typename transcribe<lhs, rhs, F>::type;
template<auto l0, auto...lhs, class rhs, class F>
struct transcribe<ct_array<l0, lhs...>, rhs, F,
std::enable_if_t<F{}(l0) && sizeof...(lhs)>
>:
transcribe<pop_t<ct_array<l0, lhs...>>, push_t<rhs, l0>, F>
{};
template<auto l0, auto...lhs, class rhs, class F>
struct transcribe<ct_array<l0, lhs...>, rhs, F,
std::enable_if_t<!F{}(l0) && sizeof...(lhs)>
>:
transcribe<pop_t<ct_array<l0, lhs...>>, rhs, F>
{};
template<auto lhs, class rhs, class F>
struct transcribe<ct_array<lhs>, rhs, F, void>
{
using type=std::conditional_t< F{}(lhs), push_t<rhs, lhs>, rhs >;
};
template<class lhs, class F>
using filter_t = transcribe_t<lhs, void, F>;
// C++20
//auto is_even = [](auto i)->bool{ return !(i%2); };
struct is_even_t {
template<class T>
constexpr bool operator()(T i)const{ return !(i%2); }
};
constexpr is_even_t is_even{};
template<auto...is>
static constexpr auto get_evens(ct_array<is...>) {
return filter_t< ct_array<is...>, decltype(is_even) >{};
}
Live example.
Test code:
auto arr = ct_array<11, 22, 33, 44, 55>{};
for (const int i : get_evens(arr)) {
std::cout << i << " " << std::endl;
}
Related
I have been attempting to implement a compiler generated look-up table
containing the values of the sine function. The C++ code looks like this
#include <cstdlib>
#include <cmath>
#include <array>
#include <iostream>
using namespace std;
template<typename T>
constexpr T look_up_table_elem(int i)
{
return {};
}
template<>
constexpr float look_up_table_elem(int i)
{
return sin(static_cast<float>(i)*2*3.14/64);
}
template<typename T, int... N>
struct lookup_table_expand{};
template<typename T, int... N>
struct lookup_table_expand<T, 1, N...>
{
static constexpr std::array<T, sizeof...(N) + 1> values =
{{look_up_table_elem<T>(0), N...}};
};
template<typename T, int L, int... N> struct lookup_table_expand<T, L, N...>
: lookup_table_expand<T, L-1, look_up_table_elem<T>(L-1), N...> {};
template<typename T, int... N>
constexpr std::array<T, sizeof...(N) + 1> lookup_table_expand<T, 1, N...>::values;
const std::array<float, 65> lookup_table = lookup_table_expand<float, 65>::values;
int main(int argc, char** argv) {
for(const float &item : lookup_table){
std::cout << "Sin: " << item << std::endl;
}
return 0;
}
I have been struggling with the compilation process.
main.cpp: In instantiation of 'struct lookup_table_expand<float, 65>':
main.cpp:49:74: required from here
main.cpp:44:52: error: conversion from 'float' to 'int' in a converted constant expression
44 | : lookup_table_expand<T, L-1, look_up_table_elem<T>(L-1), N...> {};
| ~~~~~~~~~~~~~~~~~~~~~^~~~~
main.cpp:44:52: error: could not convert 'look_up_table_elem<float>((65 - 1))' from 'float' to 'int'
main.cpp:49:76: error: 'values' is not a member of 'lookup_table_expand<float, 65>'
49 | const std::array<float, 65> lookup_table = lookup_table_expand<float, 65>::values;
| ^~~~~~
Can anybody tell me what I am doing wrong?
The code may be greatly simplified to generate the LUT:
template <std::size_t N, typename F = std::identity>
constexpr auto gen_float_array(const F& f = F{})
{
std::array<float, N> arr;
for (std::size_t i = 0; i < N; ++i)
arr[i] = f(static_cast<float>(i));
return arr;
}
It may be used as follows:
constexpr auto lookup_map =
gen_float_array<32>([](auto f) {
return f * 3.14f; // here could a call be placed to a constexpr sin function
});
Example: https://godbolt.org/z/ssEhK6bd7
As Markus Mayr pointed out, you are still in need of a constexpr sin function to get the desired results for your use case.
I do not really understand what you are trying to do here, but the error message indicates that look_up_table_elem returns a float and that you are feeding it into an int ... parameter pack at the following lines:
template<typename T, int L, int... N> struct lookup_table_expand<T, L, N...>
: lookup_table_expand<T, L-1, look_up_table_elem<T>(L-1), N...> {};
By the way, this is how I would implement a function like this:
constexpr float lookup_table_elem(std::size_t i, std::size_t n)
{
return static_cast<float>(i) / static_cast<float>(n); // Have a constexpr sin function here!
}
template <class T>
struct lookup_table_impl;
template <std::size_t... I>
struct lookup_table_impl<std::index_sequence<I...>>
{
static constexpr std::size_t N = sizeof...(I);
static constexpr std::array<float, N> values{ lookup_table_elem(I, N) ... };
};
template <std::size_t N>
using lookup_table = lookup_table_impl<std::make_index_sequence<N>>;
template <std::size_t N>
constexpr auto lookup_table_values = lookup_table<N>::values;
Please note that std::sin is not a constexpr function (yet?). You would have to write your own compile-time approximation here.
And as #HolyBlackCat suggested in a comment below, the following, very simple solution is also possible with modern C++ (>= 17, I think):
template <std::size_t N>
constexpr std::array<float, N> make_lookup_table()
{
std::array<float, N> v;
for (std::size_t i = 0u; i < N; ++i)
{
v[i] = static_cast<float>(i); // Insert constexpr sin function here!
}
return v;
}
template <std::size_t N>
constexpr auto lookup_table_values = make_lookup_table<N>();
I am trying to create a variadic int argument vectors and perform + operators on them.
For example:
vec<1,2,3> v1;
vec<4,5> v2;
auto res = v1+v2;
res.print(); // should print 5 7 3 vec<5,7,3> is the result.
And now I want to create struct vecSum, which will sum up the vectors given to it;
namespace ex {
template<int... N>
struct vec
{
static const int size = sizeof...(N);
void print() {
((std::cout << N << " "), ...);
}
};
template<int...N, int...M, int ...S>
auto add(vec<N...>, vec<M...>, std::index_sequence<S...>) {
constexpr int arr1[sizeof...(S)]{ N... };
constexpr int arr2[sizeof...(S)]{ M... };
return vec<(arr1[S] + arr2[S])...>{};
}
template<int...N, int...M>
auto operator+(vec<N...> v1, vec<M...> v2) {
constexpr size_t size = std::max(sizeof...(N), sizeof...(M));
return add(v1, v2, std::make_index_sequence<size>{});
}
template<typename... Args>
auto all(Args... args) { return (... + args); }
template<typename... Ts>
struct vecSum
{
static constexpr auto res = all(Ts);
};
}
This test works fine:
ex::vec<1, 2, 3> v1;
ex::vec<4, 5> v2;
ex::vec<2> v3;
auto r = ex::all(v1,v2,v3);
r.print();
This prints 7 7 3;
What I want to achieve is:
vecSum<vec<1,3,4>, vec<3>, vec<3,4,5>> z;
z::res.print(); and I expect 7 7 9
Instead I have this error:
error C2275: 'Ts': illegal use of this type as an expression
error C2119: 'res': the type for 'auto' cannot be deduced from an empty initializer
Can someone please hint what's wrong here? I know I am trying to pass types parameter pack Ts as expression, is there a workaround or fix for this?
I see some little problems in your code...
expand Ts
In vecSum you define res as follows
static constexpr auto res = all(Ts);
You have to expand Ts as follows
// ...............................VVVVV
static constexpr auto res = all(Ts{}...);
std::index_sequence contains std::size_t, not int, values
Your add() is defined as follows
template<int...N, int...M, int ...S>
auto add(vec<N...>, vec<M...>, std::index_sequence<S...>)
But the S... values are std::size_t
// ........................VVVVVVVVVVV
template<int...N, int...M, std::size_t ...S>
auto add(vec<N...>, vec<M...>, std::index_sequence<S...>)
or template deduction doesn't works.
constexpr functions
If vecSum has to be constexpr, you have to define all necessary functions (add(), all(), operator+()) as constexpr.
print() const
The method vec::print() is better const, given that you want print a constexpr vecSum::res value.
The following is a full compiling corrected example
#include <utility>
#include <iostream>
#include <type_traits>
namespace ex {
template<int... N>
struct vec
{
static const int size = sizeof...(N);
void print() const {
((std::cout << N << " "), ...);
}
};
template<int...N, int...M, std::size_t ...S>
constexpr auto add(vec<N...>, vec<M...>, std::index_sequence<S...>) {
constexpr int arr1[sizeof...(S)]{ N... };
constexpr int arr2[sizeof...(S)]{ M... };
return vec<(arr1[S] + arr2[S])...>{};
}
template<int...N, int...M>
constexpr auto operator+(vec<N...> v1, vec<M...> v2) {
constexpr size_t size = std::max(sizeof...(N), sizeof...(M));
return add(v1, v2, std::make_index_sequence<size>{});
}
template<typename... Args>
constexpr auto all(Args... args) { return (... + args); }
template<typename... Ts>
struct vecSum
{
static constexpr auto res = all(Ts{}...);
};
}
int main ()
{
ex::vecSum<ex::vec<1,3,4>, ex::vec<3>, ex::vec<3,4,5>> z;
z.res.print();
}
I'm pretty new to C++ template programming. I'd like to design a function element such as e.g.
element<3, 3, 3, 3, 3> will return 3
element<3, 3, 2> will fail an assertion
#include <iostream>
#include <cstdlib>
namespace meta
{
template<typename T>
constexpr T element(T x)
{
return x;
}
template<typename T, typename... Ts>
constexpr T element(T x, Ts... xs)
{
constexpr T oth = element(xs...); // $C$
static_assert(oth == x, "element Mismatch");
return x;
}
template<int... DIMS>
void get_elements()
{
std::cout << "elements " << element(DIMS...); // $A$
}
}
int main(int argc, char ** argv)
{
meta::get_elements<2, 3, 4>(); // $B$
static constexpr int D1 = 3, D2 = 3;
meta::get_elements<D1, D2>();
}
But GCC with std=c++14 is failing with
In instantiation of ‘constexpr T meta::element(T, Ts ...) [with T = int; Ts = {int, int}]’:
$A$: required from ‘void meta::get_elements() [with int ...DIMS = {2, 3, 4}]’
$B$: required from here
$C$: error: ‘xs#0’ is not a constant expression
$C$: error: ‘xs#1’ is not a constant expression
I'd like to exploit recursion to perform an equality check on each template argument in the list, and return one of them if they're all equal.
parameters are not constexpr.
You might use std::integral_constant to bypass that
namespace meta
{
template<typename T, T V>
constexpr std::integral_constant<T, V> element(std::integral_constant<T, V>)
{
return {};
}
template<typename T, T V, typename... Ts>
constexpr std::integral_constant<T, V> element(std::integral_constant<T, V> x, Ts... xs)
{
constexpr auto oth = element(xs...); // $C$
static_assert(oth() == x(), "element Mismatch");
return {};
}
template<int... DIMS>
void get_elements()
{
std::cout << "elements " << element(std::integral_constant<int, DIMS>{}...); // $A$
}
}
Here is a simple solution in C++17:
template <int Head, int... Tail> struct element
{
static_assert((... && (Head == Tail)), "missmatch elements");
static constexpr auto value = Head;
};
template <int... I> constexpr auto element_v = element<I...>::value;
auto test()
{
// element_v<3, 3, 1>; // assert fail
constexpr int A = 3, B = 3;
return element_v<3, 3, A, B>;
}
See it on godbolt
Or pre-c++17 (no recursion):
#include <iostream>
#include <cstdlib>
#include <type_traits>
namespace meta
{
template <bool...>
struct boolpack { };
template <bool... Bs>
struct all_of: std::is_same<boolpack<Bs..., true>, boolpack<true, Bs...>> { };
template<int FIRST, int... DIMS>
constexpr void get_elements()
{
static_assert(all_of<DIMS==FIRST...>::value, "!");
std::cout << "elements " << FIRST;
}
}
int main(int argc, char ** argv)
{
static constexpr int D1 = 3, D2 = 3;
meta::get_elements<D1, D2>();
//meta::get_elements<D1, D2, 2>(); //fail
}
[see it live]
Edited: all_of inspired by Jarod42.
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;
}
So, I have a class, which has an array of arrays as a private member. I wish to have two constructors for each case (1D or 2D). But of course their declaration happens to be the same, so template deduction can't do its job without me doing something about it. Here's the code:
Edit: I also need it to work with STL containers like vector or C++ array. That is why I am overcomplicating and not going with the "arrays" fix.
#include <iostream>
#include <array>
template<class T, std::size_t rows_t, std::size_t cols_t>
class test
{
private:
std::array<std::array<T, cols_t>, rows_t> _data;
public:
auto begin() { return this->_data.begin(); }
auto end() { return this->_data.end(); }
//CONSTRUCTOR
template<class type_t>
test(const type_t &arr)
{
std::size_t j = 0;
for (const auto &num : arr)
this->_data[0][j++] = num;
}
template<class type_t>
test(const type_t &arr)
{
std::size_t i = 0;
for (const auto &el : arr)
{
std::size_t j = 0;
for (const auto &num : el)
this->_data[i][j++] = num;
++i;
}
}
};
int main()
{
double arr[3] = { 1, 2, 3 };
double arr2[2][2] = { {1, 2}, {3, 4} };
test<double, 1, 3> obj = arr;
test<double, 2, 2> obj2 = arr2;
for (const auto &i : obj2)
{
for (const auto &j : i)
std::cout << j << " ";
std::cout << std::endl;
}
std::cin.get();
}
Note: I've been reading about enable_if, but I don't quite understand how it works. Can it be done with that?
The constructors should not be the same, but you have only provided the most generic matching possible.
SFINAE is not necessary here. Just provide a constructor for a 1D array, and a separate constructor for a 2D array:
template <typename T2, std::size_t N>
test( const T2 (&a)[N] )
{
...
}
template <typename T2, std::size_t M, std::size_t N>
test( const T2 (&a)[M][N] )
{
...
}
Another note: POSIX reserves typenames ending with "_t", so it is typically a good idea to avoid them in your own code. (Obnoxious, I know.) Standard C++ will use Camel Case of the form: RowsType, etc, and then typedef a rows_type for users of the class.
Notice, however, that rows_t is not actually a type -- it is a value. A better name would be something like NRows.
Hope this helps.
First, you have to "teach" the compiler what's 2D and what's not. Hence, you have to define something like the following type trait:
template<typename T>
struct is2D : public std::false_type {};
template<typename T, std::size_t N, std::size_t M>
struct is2D<std::array<std::array<T, M>, N>> : std::true_type {};
template<typename T>
struct is2D<std::vector<std::vector<T>>> : std::true_type {};
template<typename T, std::size_t N, std::size_t M>
struct is2D<T[N][M]> : std::true_type {};
Then you could set up your class definition in the following way:
template<class T, std::size_t rows_t, std::size_t cols_t>
class test{
std::array<std::array<T, cols_t>, rows_t> _data;
template<class type_t>
std::enable_if_t<!is2D<type_t>::value, void>
test_init(type_t const &arr) {
std::size_t j = 0;
for (const auto &num : arr) _data[0][j++] = num;
}
template<class type_t>
std::enable_if_t<is2D<type_t>::value, void>
test_init(type_t const &arr) {
std::size_t i = 0;
for(const auto &el : arr) {
std::size_t j = 0;
for (const auto &num : el) _data[i][j++] = num;
++i;
}
}
public:
auto &operator[](const std::size_t &i) { return this->_data[i]; }
auto begin() { return this->_data.begin(); }
auto end() { return this->_data.end(); }
//CONSTRUCTOR
template<class type_t> test(type_t const &arr) { test_init(arr); }
};
LIVE DEMO