Related
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;
}
I have a class that defines a constexpr size_t dimensions. In this class, I implemented an EvaluateOver<Dimensions...>(Lambda F) which does something over the dimensions I specify. For example, say dimensions=4 and f is some lambda expression:
MyClass.EvaluateOver<0,2>(f);
will perform f with respect to 0 and 2 by doing the following expansion:
template<size_t... Dims, typename Lambda>
inline auto EvaluateOver(const Lambda& F) const
{
F(std::get<Dims>(_memberTupleDataContainer)...);
}
Now I want another member function that will evaluate over the unspecified dimensions. So EvaluateOverOthers<0,2>(f) will perform its operation on dimensions 1 and 3.
Ideally, I am thinking of the following:
template<size_t... Dims, typename Lambda>
inline auto EvaluateOverOthers(const Lambda& F) const
{
EvaluateOver<
// variadic parameter that does the mathematical complement of
// Dims... with a variadic expansion of dimensions
>(F);
}
Following might help:
namespace details
{
template <typename Seq1, typename Seq2, typename Res = std::index_sequence<>>
struct minus;
// Nothing more to remove
template <std::size_t ... Is1, std::size_t... IRes>
struct minus<std::index_sequence<Is1...>,
std::index_sequence<>,
std::index_sequence<IRes...>>
{
using type = std::index_sequence<IRes..., Is1...>;
};
// Remove front elements as they are equal.
template <std::size_t I, std::size_t ... Is1, std::size_t ... Is2, std::size_t... IRes>
struct minus<std::index_sequence<I, Is1...>,
std::index_sequence<I, Is2...>,
std::index_sequence<IRes...>>
{
using type = typename minus<std::index_sequence<Is1...>,
std::index_sequence<Is2...>,
std::index_sequence<IRes...>>::type;
};
// Add front element to result.
template <std::size_t I1, std::size_t I2,
std::size_t ... Is1, std::size_t ... Is2,
std::size_t... IRes>
struct minus<std::index_sequence<I1, Is1...>,
std::index_sequence<I2, Is2...>,
std::index_sequence<IRes...>>
{
using type = typename minus<std::index_sequence<Is1...>,
std::index_sequence<I2, Is2...>,
std::index_sequence<IRes..., I1>>::type;
};
}
template <std::size_t N, typename Seq>
using complement = details::minus<std::make_index_sequence<N>, Seq>;
template <std::size_t N, typename Seq>
using complement_t = typename complement<N, Seq>::type;
// Some test
static_assert(std::is_same<std::index_sequence<0, 3>,
complement_t<4, std::index_sequence<1, 2>>>::value, "!");
And then
template<size_t... Is, typename Lambda>
auto EvaluateOver(const Lambda& F, std::index_sequence<Is...>) const
{
return F(std::get<Is>(_memberTupleDataContainer)...);
}
template<size_t... Dims, typename Lambda>
auto EvaluateOver(const Lambda& F) const
{
return EvaluateOver(F, std::index_sequence<Is...>{});
}
template<size_t... Is, typename Lambda>
auto EvaluateOverOthers(const Lambda& F) const
{
return EvaluateOver(F, complement_t<_dimension, std::index_sequence<Is...>>{});
}
I played with a constexpr C++17 solution (online demo). I think the logic for complements could be factored out (if desired).
#include <iostream>
#include <iterator>
#include <utility>
#include "my_constexpr_array.hpp"
template<size_t Nd>
struct MyClass {
static constexpr auto dim_arr = Array(std::make_index_sequence<Nd>{});
template<size_t... excludes, class F>
auto eval_others(F f) const {
constexpr auto excl_arr = Array{excludes...};
constexpr auto incl_pred = [&] (size_t i) { return !excl_arr.contains(i); };
constexpr auto incl_excl_arr = dim_arr.partition(incl_pred);
constexpr auto incl_count = dim_arr.count_if(incl_pred);
return eval_helper(
f,
[&] { return incl_excl_arr; },// wrapped in lambda to preserve constexpr
std::make_index_sequence<incl_count>{}// indices for trimming incl_excl_arr
);
}
template<class F, class Dims, size_t... is>
auto eval_helper(F f, Dims dims, std::index_sequence<is...>) const {
return f(std::integral_constant<size_t, dims()[is]>{}...);
}
};
int main() {
MyClass<7> foo{};
foo.eval_others<2, 4>([&] (auto... is) { (std::cout << ... << is) << "\n"; });
return 0;
}
Where "my_constexpr_array.hpp" would behave like
template<class T, size_t size>
struct Array {
static_assert(size >= 1);
T data_[size];
constexpr Array() noexcept
: data_{} {}
template<class... Ts>
explicit constexpr Array(T v0, Ts... vs) noexcept
: data_{v0, vs...} {}
template<T... vs>
explicit constexpr Array(std::integer_sequence<T, vs...>) noexcept
: data_{vs...} {}
constexpr T* begin() { return data_; }
constexpr const T* begin() const { return data_; }
constexpr T* end() { return begin() + size; }
constexpr const T* end() const { return begin() + size; }
constexpr decltype(auto) operator[](size_t i) { return data_[i]; }
constexpr decltype(auto) operator[](size_t i) const { return data_[i]; }
constexpr bool contains(const T& v) const {
for(auto& x : *this) if(x == v) return true;
return false;
}
template<class Pred>
constexpr size_t count_if(Pred pred) const {
size_t result = 0;
for(auto& x : *this) result += size_t(pred(x) ? 1 : 0);
return result;
}
template<class Pred>
constexpr Array partition(Pred pred) const {
// return a sorted copy such that all `true`s precede all `false`s
Array result{};
T* true_false_dst[2] = {result.begin(), result.begin() + count_if(pred)};
// pair of output iterators; use first if predicate is true and vice versa
for(auto& x : *this) *true_false_dst[pred(x) ? 0 : 1]++ = x;
return result;
}
friend std::ostream& operator<<(std::ostream& os, const Array& self) {
for(auto& x : self) os << x << ", ";
return os;
}
};
template<class T, class... Ts>
Array(T, Ts...) -> Array<T, size_t(1) + sizeof...(Ts)>;
template<class T, T... vs>
Array(std::integer_sequence<T, vs...>) -> Array<T, sizeof...(vs)>;
I've written a for_each for tuples:
template <typename Tuple, typename F, size_t begin, size_t end>
enable_if_t<begin == end || tuple_size<Tuple>::value < end> for_each(Tuple&, F&&) {
}
template <typename Tuple, typename F, size_t begin = 0U, size_t end = tuple_size<Tuple>::value>
enable_if_t<begin < end && tuple_size<Tuple>::value >= end> for_each(Tuple& t, F&& f) {
f(get<begin>(t));
for_each<Tuple, F, begin + 1, end>(t, forward<F>(f));
}
[Live Example]
But Yakk's answer to this question gives a wonderful example of how to handle running a lambda on all tuple values non-recursively:
namespace detail {
template<class F, class...Args>
void for_each_arg(F&& f, Args&&...args) {
using detail = int[];
static_cast<void>(detail{((f(std::forward<Args>(args))), void(), 0)..., 0});
}
}
template <typename F, typename Tuple>
void for_each_tuple_element(F&& f, Tuple&& t) {
return experimental::apply([&](auto&&...args) { detail::for_each_arg(forward<F>(f), decltype(args)(args)... ); }, forward<Tuple>(t));
}
This requires apply. You can see my simplification of Yakk's answer here: http://ideone.com/yAYjmw
My question is this: Is there a way to somehow retrofit for_each_tuple_element with a range, avoiding the recursion that my code incurs? I've tried constructing the subset of the tuple defined by the range, but I can't seem to do that without using recursion, and then why not just my for_each?
You could avoid recursion by generating a sequence of calls to the std::get<Is>(t)... function, with Is indices ranging from begin up to end-1. It's fairly easy to generate a sequence of consecutive numbers starting at a given index, as it's enough to make the starting point an offset that is then added to each item of a regular index sequence, e.g.:
std::get<begin + 0>(t), std::get<begin + 1>(t), ... std::get<begin + n>(t)
where the length of the sequence is equal to the distance between begin and end.
#include <tuple>
#include <type_traits>
#include <utility>
#include <cstddef>
#include <limits>
template <std::size_t begin, typename Tuple, typename F, std::size_t... Is>
void for_each(Tuple&& t, F&& f, std::index_sequence<Is...>)
{
using expand = int[];
static_cast<void>(expand{ 0, (f(std::get<begin + Is>(std::forward<Tuple>(t))), void(), 0)... });
}
template <std::size_t begin = 0U, std::size_t end = std::numeric_limits<std::size_t>::max(), typename Tuple, typename F>
void for_each(Tuple&& t, F&& f)
{
for_each<begin>(std::forward<Tuple>(t), std::forward<F>(f)
, std::make_index_sequence<(end==std::numeric_limits<std::size_t>::max()?std::tuple_size<std::decay_t<Tuple>>::value:end)-begin>{});
}
Test:
int main()
{
auto t = std::make_tuple(3.14, "Hello World!", -1);
auto f = [](const auto& i) { std::cout << i << ' '; };
for_each<1>(t, f);
for_each<1,3>(t, f);
for_each<0,2>(t, f);
}
DEMO
Also, note that defaulted template parameters of a function template don't have to be placed at the end of a template parameter list, hence, you can avoid the ugly decltype(t), decltype(f) part. This implies that end cannot be defaulted to std::tuple_size<Tuple>::value (since Tuple goes after end), but at this point all you need is some default magic number.
You could implement a make_index_range metafunction like so:
template <std::size_t Start, std::size_t End>
struct index_range {
template <std::size_t... Idx>
static std::index_sequence<(Idx + Start)...>
make_range (std::index_sequence<Idx...>);
using type = decltype(make_range(std::make_index_sequence<End-Start>{}));
};
template <std::size_t Start, std::size_t End>
using make_index_range = typename index_range<Start, End>::type;
Then you can use this to generate your std::index_sequence:
template <typename Tuple, typename F, std::size_t... Idx>
void for_each(Tuple& t, F&& f, std::index_sequence<Idx...>) {
(void)std::initializer_list<int> {
(std::forward<F>(f)(std::get<Idx>(t)), 0)...
};
}
template <typename Tuple, size_t begin = 0U,
size_t end = tuple_size<Tuple>::value, typename F>
enable_if_t<begin < end && tuple_size<Tuple>::value >= end>
for_each(Tuple& t, F&& f) {
for_each(t, std::forward<F>(f), make_index_range<begin, end>{});
}
You would use this like so:
auto t = std::make_tuple(1, 42.1, "hello world");
for_each<decltype(t), 2, 3>(t,[](auto e){std::cout << e << '\n';});
//outputs hello world
Note that you need to pass decltype(t) in if you want to give a begin and end. You could avoid that by using the technique in Peter Skotnicki's answer.
Live Demo
Inspired by #Piotr, but with extra prettiness :-)
#include <tuple>
#include <utility>
#include <tuple>
#include <cstddef>
#include <string>
#include <iostream>
template<class Tuple, size_t I>
struct tuple_iterator
{
constexpr tuple_iterator(Tuple& p) : _p(p) {}
static constexpr auto index() { return I; }
constexpr auto operator++() const { return tuple_iterator<Tuple, I+1>(_p); }
constexpr auto operator--() const { return tuple_iterator<Tuple, I-1>(_p); }
constexpr decltype(auto) deref() const { return _p; }
Tuple& _p;
};
template<class...Ts>
constexpr auto begin(const std::tuple<Ts...>& t) {
return tuple_iterator<const std::tuple<Ts...>, 0>(t);
}
template<class...Ts>
constexpr auto end(const std::tuple<Ts...>& t) {
return tuple_iterator<const std::tuple<Ts...>, sizeof...(Ts)>(t);
}
template<class Tuple, size_t I>
constexpr auto prev(tuple_iterator<Tuple, I> it) { return --it; }
template<class Tuple, size_t I>
constexpr auto next(tuple_iterator<Tuple, I> it) { return ++it; }
namespace detail
{
template <
std::size_t begin,
typename Tuple,
typename F,
std::size_t... Is
>
void for_each(Tuple&& t, F&& f, std::index_sequence<Is...>)
{
using expand = int[];
static_cast<void>(expand{ 0, (f(std::get<begin + Is>(std::forward<Tuple>(t))), void(), 0)... });
}
}
template<class Tuple, size_t First, size_t Last, class Func>
void for_each(tuple_iterator<Tuple, First> first, tuple_iterator<Tuple, Last> last, Func&& f)
{
constexpr auto dist = Last - First;
constexpr auto base = First;
constexpr auto extent = std::make_index_sequence<dist>();
detail::for_each<base>(first.deref(), std::forward<Func>(f), extent);
}
int main()
{
using namespace std;
auto x = make_tuple("dont print me", 1, "two", "three"s, "or me");
for_each(next(begin(x)), prev(end(x)), [](const auto& x) { cout << x << endl; });
return 0;
}
expected results:
1
two
three
Sorry about the second answer, but I felt that this was worth it.
Presenting the function make_poly_tuple_iterator() which returns an iterator that will iterate over elements in a tuple, working with all algorithms in the std namespace.
de-referencing the iterator results in a boost::variant< reference types... > so the functors will have to be specialisations of boost::static_visitor<>.
Demo below, use like this:
int main()
{
using namespace std;
auto x = make_tuple(tagged_string<tag1>("dont print me"),
1,
2.0,
tagged_string<tag2>("three"),
tagged_string<tag3>("or me"));
// this is the statically typed version
for_each(next(begin(x)),
prev(end(x)),
[](const auto& x) { cout << x << endl; });
// and the polymorphic version
auto first = std::next(make_poly_tuple_iterator(begin(x)));
auto last = std::prev(make_poly_tuple_iterator(end(x)));
// note: std::for_each ;-)
std::for_each(first, last, print_it());
return 0;
}
expected results:
1
2
three
printing: 1
printing: 2
printing: three
Complete code:
Yes I know, there are many, many improvements that can be made....
#include <tuple>
#include <utility>
#include <tuple>
#include <cstddef>
#include <string>
#include <iostream>
#include <boost/variant.hpp>
#include <stdexcept>
#include <exception>
template<class Tuple, size_t I>
struct tuple_iterator
{
constexpr tuple_iterator(Tuple& p) : _p(p) {}
static constexpr auto index() { return I; }
static constexpr auto upper_bound() { return std::tuple_size<Tuple>::value; }
static constexpr auto lower_bound() { return 0; }
template<size_t I2> static constexpr auto ValidIndex = I2 >= lower_bound() && I2 < upper_bound();
template<size_t I2, typename = void>
struct de_ref_type { using type = decltype(std::get<0>(std::declval<Tuple>())); };
template<size_t I2>
struct de_ref_type<I2, std::enable_if_t<ValidIndex<I2>>>
{ using type = decltype(std::get<I2>(std::declval<Tuple>())); };
template<size_t I2> using DerefType = typename de_ref_type<I2>::type;
constexpr auto operator++() const { return make_like_me<I+1>(); }
constexpr auto operator--() const { return make_like_me<I-1>(); }
template<size_t I2, std::enable_if_t<(I2 < lower_bound())>* = nullptr>
constexpr auto make_like_me() const { return tuple_iterator<Tuple, lower_bound()>(_p); }
template<size_t I2, std::enable_if_t<(I2 >= upper_bound())>* = nullptr>
constexpr auto make_like_me() const { return tuple_iterator<Tuple, upper_bound()>(_p); }
template<size_t I2, std::enable_if_t<ValidIndex<I2>>* = nullptr>
constexpr auto make_like_me() const { return tuple_iterator<Tuple, I2>(_p); }
constexpr decltype(auto) deref() const { return _p; }
template<size_t X> bool operator==(const tuple_iterator<Tuple, X>& r) const { return false; }
bool operator==(const tuple_iterator<Tuple, I>& r) const {
return std::addressof(_p) == std::addressof(r._p);
}
template<size_t I2, std::enable_if_t<ValidIndex<I2>>* =nullptr>
DerefType<I2> impl_star() const { return std::get<I2>(_p); }
template<size_t I2, std::enable_if_t<not ValidIndex<I2>>* =nullptr>
DerefType<I2> impl_star() const
{ throw std::logic_error("out of range"); }
decltype(auto) operator*() const {
return impl_star<index()>();
}
Tuple& _p;
};
template<class...Ts>
constexpr auto begin(const std::tuple<Ts...>& t) {
return tuple_iterator<const std::tuple<Ts...>, 0>(t);
}
template<class...Ts>
constexpr auto end(const std::tuple<Ts...>& t) {
return tuple_iterator<const std::tuple<Ts...>, sizeof...(Ts)>(t);
}
template<class Tuple, size_t I>
constexpr auto prev(tuple_iterator<Tuple, I> it) { return --it; }
template<class Tuple, size_t I>
constexpr auto next(tuple_iterator<Tuple, I> it) { return ++it; }
namespace detail
{
template <
std::size_t begin,
typename Tuple,
typename F,
std::size_t... Is
>
void for_each(Tuple&& t, F&& f, std::index_sequence<Is...>)
{
using expand = int[];
static_cast<void>(expand{ 0, (f(std::get<begin + Is>(std::forward<Tuple>(t))), void(), 0)... });
}
}
template<class Tuple, size_t First, size_t Last, class Func>
void for_each(tuple_iterator<Tuple, First> first, tuple_iterator<Tuple, Last> last, Func&& f)
{
constexpr auto dist = Last - First;
constexpr auto base = First;
constexpr auto extent = std::make_index_sequence<dist>();
detail::for_each<base>(first.deref(), std::forward<Func>(f), extent);
}
namespace detail {
template<class Tuple>
struct variant_of_tuple;
template<class...Ts>
struct variant_of_tuple<std::tuple<Ts...>>
{
// todo: some work to remove duplicates
using type = boost::variant<std::add_lvalue_reference_t<Ts>...>;
};
template<class...Ts>
struct variant_of_tuple<const std::tuple<Ts...>>
{
// todo: some work to remove duplicates
using type = boost::variant<std::add_lvalue_reference_t<std::add_const_t<Ts>>...>;
};
}
template<class Tuple>
using ToVariant = typename detail::variant_of_tuple<Tuple>::type;
template<class Tuple>
struct poly_tuple_iterator
{
using tuple_type = Tuple;
using value_type = ToVariant<std::remove_reference_t<tuple_type>>;
using difference_type = std::ptrdiff_t;
using pointer = value_type*;
using reference = value_type&;
using iterator_category = std::random_access_iterator_tag;
struct concept {
virtual ~concept() = default;
virtual const std::type_info& type() const = 0;
virtual const void* address() const = 0;
virtual bool equal(const void* p) const = 0;
virtual std::unique_ptr<concept> clone() const = 0;
virtual std::unique_ptr<concept> next() const = 0;
virtual std::unique_ptr<concept> prev() const = 0;
virtual value_type deref() const = 0;
};
template<size_t I>
struct model : concept {
using my_type = tuple_iterator<tuple_type, I>;
model(my_type iter) : _iter(iter) {}
const std::type_info& type() const override { return typeid(_iter); }
const void* address() const override { return std::addressof(_iter); }
std::unique_ptr<concept> clone() const override { return std::make_unique<model<I>>(_iter); };
std::unique_ptr<concept> next() const override {
auto next_iter = ++_iter;
return std::make_unique<model<next_iter.index()>>(next_iter);
};
std::unique_ptr<concept> prev() const override {
auto next_iter = --_iter;
return std::make_unique<model<next_iter.index()>>(next_iter);
};
value_type deref() const override { return { *_iter }; }
bool equal(const void* p) const override {
return _iter == *reinterpret_cast<const my_type*>(p);
}
my_type _iter;
};
template<size_t I>
poly_tuple_iterator(tuple_iterator<tuple_type, I> iter)
: _impl(std::make_unique<model<I>>(iter))
{}
poly_tuple_iterator(const poly_tuple_iterator& r) : _impl(r._impl->clone()) {};
poly_tuple_iterator(poly_tuple_iterator&& r) : _impl(std::move(r._impl)) {};
poly_tuple_iterator& operator=(const poly_tuple_iterator& r) {
_impl = r._impl->clone();
return *this;
}
poly_tuple_iterator& operator=(poly_tuple_iterator&& r) {
auto tmp = r._impl->clone();
std::swap(tmp, _impl);
return *this;
}
value_type operator*() const { return _impl->deref(); }
poly_tuple_iterator& operator++() { _impl = _impl->next(); return *this; }
poly_tuple_iterator operator++(int) { auto tmp = *this; _impl = _impl->next(); return tmp; }
poly_tuple_iterator& operator--() { _impl = _impl->prev(); return *this; }
poly_tuple_iterator operator--(int) { auto tmp = *this; _impl = _impl->prev(); return tmp; }
poly_tuple_iterator& operator+=(difference_type dist) {
while (dist > 0) {
++(*this);
--dist;
}
while(dist < 0) {
--(*this);
++dist;
}
return *this;
}
bool operator==(const poly_tuple_iterator& r) const {
return _impl->type() == r._impl->type()
and _impl->equal(r._impl->address());
}
bool operator!=(const poly_tuple_iterator& r) const {
return not (*this == r);
}
private:
std::unique_ptr<concept> _impl;
};
template<class Tuple, size_t I>
auto make_poly_tuple_iterator(tuple_iterator<Tuple, I> iter) {
return poly_tuple_iterator<Tuple>(iter);
}
struct print_it : boost::static_visitor<void>
{
template<class T>
void operator()(const T& t) const {
std::cout << "printing: " << t << std::endl;
}
template<class...Ts>
void operator()(const boost::variant<Ts...>& v) const {
boost::apply_visitor(*this, v);
}
};
// to differentiate string types for this demo
template<class tag>
struct tagged_string : std::string
{
using std::string::string;
};
struct tag1 {};
struct tag2 {};
struct tag3 {};
int main()
{
using namespace std;
auto x = make_tuple(tagged_string<tag1>("dont print me"),
1,
2.0,
tagged_string<tag2>("three"),
tagged_string<tag3>("or me"));
for_each(next(begin(x)), prev(end(x)), [](const auto& x) { cout << x << endl; });
auto first = std::next(make_poly_tuple_iterator(begin(x)));
auto last = std::prev(make_poly_tuple_iterator(end(x)));
std::for_each(first, last, print_it());
return 0;
}
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
This is a bit of a puzzle rather than a real-world problem, but I've gotten into a situation where I want to be able to write something that behaves exactly like
template<int N>
struct SortMyElements {
int data[N];
template<typename... TT>
SortMyElements(TT... tt) : data{ tt... }
{
std::sort(data, data+N);
}
};
int main() {
SortMyElements<5> se(1,4,2,5,3);
int se_reference[5] = {1,2,3,4,5};
assert(memcmp(se.data, se_reference, sizeof se.data) == 0);
}
except that I want the SortMyElements constructor to be constexpr.
Obviously this is possible for fixed N; for example, I can specialize
template<>
struct SortMyElements<1> {
int data[1];
constexpr SortMyElements(int x) : data{ x } {}
};
template<>
struct SortMyElements<2> {
int data[2];
constexpr SortMyElements(int x, int y) : data{ x>y?y:x, x>y?x:y } {}
};
But how do I generalize this into something that will work for any N?
Please notice that the array elements have to come from the actual values of the arguments, not from template non-type arguments; my elements come from constexpr expressions that, despite being evaluated at compile-time, reside firmly inside the "value system", rather than the "type system". (For example, Boost.MPL's sort works strictly within the "type system".)
I've posted a working "answer", but it's too inefficient to work for N > 6. I'd like to use this with 2 < N < 50 or thereabouts.
(P.S.— Actually what I'd really like to do is shuffle all the zeroes in an array to the end of the array and pack the nonzero values toward the front, which might be easier than full-on sorting; but I figure sorting is easier to describe. Feel free to tackle the "shuffle zeroes" problem instead of sorting.)
It's ugly, and probably not the best way to sort in a constant expression (because of the required instantiation depth).. but voilà, a merge sort:
Helper type, returnable array type with constexpr element access:
#include <cstddef>
#include <iterator>
#include <type_traits>
template<class T, std::size_t N>
struct c_array
{
T arr[N];
constexpr T const& operator[](std::size_t p) const
{ return arr[p]; }
constexpr T const* begin() const
{ return arr+0; }
constexpr T const* end() const
{ return arr+N; }
};
template<class T>
struct c_array<T, 0> {};
append function for that array type:
template<std::size_t... Is>
struct seq {};
template<std::size_t N, std::size_t... Is>
struct gen_seq : gen_seq<N-1, N-1, Is...> {};
template<std::size_t... Is>
struct gen_seq<0, Is...> : seq<Is...> {};
template<class T, std::size_t N, class U, std::size_t... Is>
constexpr c_array<T, N+1> append_impl(c_array<T, N> const& p, U const& e,
seq<Is...>)
{
return {{p[Is]..., e}};
}
template<class T, std::size_t N, class U>
constexpr c_array<T, N+1> append(c_array<T, N> const& p, U const& e)
{
return append_impl(p, e, gen_seq<N>{});
}
Merge sort:
template<std::size_t Res, class T, class It, std::size_t Accum,
class = typename std::enable_if<Res!=Accum, void>::type >
constexpr c_array<T, Res> c_merge(It beg0, It end0, It beg1, It end1,
c_array<T, Accum> const& accum)
{
return
beg0 == end0 ? c_merge<Res>(beg0 , end0, beg1+1, end1, append(accum, *beg1)) :
beg1 == end1 ? c_merge<Res>(beg0+1, end0, beg1 , end1, append(accum, *beg0)) :
*beg0 < *beg1 ? c_merge<Res>(beg0+1, end0, beg1 , end1, append(accum, *beg0))
: c_merge<Res>(beg0 , end0, beg1+1, end1, append(accum, *beg1));
}
template<std::size_t Res, class T, class It, class... Dummies>
constexpr c_array<T, Res> c_merge(It beg0, It end0, It beg1, It end1,
c_array<T, Res> const& accum, Dummies...)
{
return accum;
}
template<class T, std::size_t L, std::size_t R>
constexpr c_array<T, L+R> c_merge(c_array<T, L> const& l,
c_array<T, R> const& r)
{
return c_merge<L+R>(l.begin(), l.end(), r.begin(), r.end(),
c_array<T, 0>{});
}
template<class T>
using rem_ref = typename std::remove_reference<T>::type;
template<std::size_t dist>
struct helper
{
template < class It >
static constexpr auto merge_sort(It beg, It end)
-> c_array<rem_ref<decltype(*beg)>, dist>
{
return c_merge(helper<dist/2>::merge_sort(beg, beg+dist/2),
helper<dist-dist/2>::merge_sort(beg+dist/2, end));
}
};
template<>
struct helper<0>
{
template < class It >
static constexpr auto merge_sort(It beg, It end)
-> c_array<rem_ref<decltype(*beg)>, 0>
{
return {};
}
};
template<>
struct helper<1>
{
template < class It >
static constexpr auto merge_sort(It beg, It end)
-> c_array<rem_ref<decltype(*beg)>, 1>
{
return {*beg};
}
};
template < std::size_t dist, class It >
constexpr auto merge_sort(It beg, It end)
-> c_array<rem_ref<decltype(*beg)>, dist>
{
return helper<dist>::merge_sort(beg, end);
}
Helpers for usage example:
template<class T, std::size_t N>
constexpr std::size_t array_size(T (&arr)[N]) { return N; }
template<class T, std::size_t N>
constexpr T* c_begin(T (&arr)[N]) { return arr; }
template<class T, std::size_t N>
constexpr T* c_end(T (&arr)[N]) { return arr+N; }
Usage example:
constexpr int unsorted[] = {5,7,3,4,1,8,2,9,0,6,10}; // odd number of elements
constexpr auto sorted = merge_sort<array_size(unsorted)>(c_begin(unsorted),
c_end(unsorted));
#include <iostream>
int main()
{
std::cout << "unsorted: ";
for(auto const& e : unsorted) std::cout << e << ", ";
std::cout << '\n';
std::cout << "sorted: ";
for(auto const& e : sorted) std::cout << e << ", ";
std::cout << '\n';
}
Output:
unsorted: 5, 7, 3, 4, 1, 8, 2, 9, 0, 6, 10,
sorted: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
I know that this is an old question but as we have C++14 (and C++17 soon), and since C++14 constexpr rules aren't so restricted, and, for sure, couple of people will find your question in google, here is how quicksort (and of course other algorithms) can be done since C++14.
(big credits to #dyp for constexpr array)
#include <utility>
#include <cstdlib>
template<class T>
constexpr void swap(T& l, T& r)
{
T tmp = std::move(l);
l = std::move(r);
r = std::move(tmp);
}
template <typename T, size_t N>
struct array
{
constexpr T& operator[](size_t i)
{
return arr[i];
}
constexpr const T& operator[](size_t i) const
{
return arr[i];
}
constexpr const T* begin() const
{
return arr;
}
constexpr const T* end() const
{
return arr + N;
}
T arr[N];
};
template <typename T, size_t N>
constexpr void sort_impl(array<T, N> &array, size_t left, size_t right)
{
if (left < right)
{
size_t m = left;
for (size_t i = left + 1; i<right; i++)
if (array[i]<array[left])
swap(array[++m], array[i]);
swap(array[left], array[m]);
sort_impl(array, left, m);
sort_impl(array, m + 1, right);
}
}
template <typename T, size_t N>
constexpr array<T, N> sort(array<T, N> array)
{
auto sorted = array;
sort_impl(sorted, 0, N);
return sorted;
}
constexpr array<int, 11> unsorted{5,7,3,4,1,8,2,9,0,6,10}; // odd number of elements
constexpr auto sorted = sort(unsorted);
#include <iostream>
int main()
{
std::cout << "unsorted: ";
for(auto const& e : unsorted)
std::cout << e << ", ";
std::cout << '\n';
std::cout << "sorted: ";
for(auto const& e : sorted)
std::cout << e << ", ";
std::cout << '\n';
}
LIVE DEMO
A bit late to the party, but a much better and simpler implementation is the following comb_sort implementation.
template<typename Array>
constexpr void comb_sort_impl ( Array & array_ ) noexcept {
using size_type = typename Array::size_type;
size_type gap = array_.size ( );
bool swapped = false;
while ( ( gap > size_type { 1 } ) or swapped ) {
if ( gap > size_type { 1 } ) {
gap = static_cast<size_type> ( gap / 1.247330950103979 );
}
swapped = false;
for ( size_type i = size_type { 0 }; gap + i < static_cast<size_type> ( array_.size ( ) ); ++i ) {
if ( array_ [ i ] > array_ [ i + gap ] ) {
auto swap = array_ [ i ];
array_ [ i ] = array_ [ i + gap ];
array_ [ i + gap ] = swap;
swapped = true;
}
}
}
}
template<typename Array>
constexpr Array sort ( Array array_ ) noexcept {
auto sorted = array_;
comb_sort_impl ( sorted );
return sorted;
}
int main ( ) {
constexpr auto sorted = sort ( std::array<int, 8> { 6, 8, 0, 1, 5, 9, 2, 7 } );
for ( auto i : sorted )
std::cout << i << ' ';
std::cout << std::endl;
return EXIT_SUCCESS;
}
Output: 0 1 2 5 6 7 8 9
Why better, it's [the algorithm] often as good as insertion sort, but is non-recursive, which means it will work on any size arrays (at least not limited by the recursive depth).
Well, I got my inefficient version to compile, at least with Clang on OSX. Here's the code.
However, while it's tolerably fast for five elements, on my laptop it takes 0.5 seconds to sort six elements and 7 seconds to sort seven elements. (Catastrophically varying performance, too, depending on whether the items are almost-sorted or reverse-sorted.) I didn't even try timing eight. Clearly, this doesn't scale to the kind of things I want to do with it. (I'd say 50 elements is a reasonable upper bound for my contrived use-case, but 6 is unreasonably tiny.)
#include <cstring>
#include <cassert>
template<int...>
struct IntHolder {};
// Now let's make a consecutive range of ints from [A to B).
template<int A, int B, int... Accum>
struct IntRange_ : IntRange_<A+1, B, Accum..., A> {};
template<int A, int... Accum>
struct IntRange_<A, A, Accum...> {
using type = IntHolder<Accum...>;
};
template<int A, int B>
using IntRange = typename IntRange_<A,B>::type;
// And a helper function to do what std::min should be doing for us.
template<typename... TT> constexpr int min(TT...);
constexpr int min(int i) { return i; }
template<typename... TT> constexpr int min(int i, TT... tt) { return i < min(tt...) ? i : min(tt...); }
template<int N>
struct SortMyElements {
int data[N];
template<int... II, typename... TT>
constexpr SortMyElements(IntHolder<II...> ii, int minval, int a, TT... tt) : data{
( a==minval ? a : SortMyElements<N>(ii, minval, tt..., a).data[0] ),
( a==minval ? SortMyElements<N-1>(tt...).data[II] : SortMyElements<N>(ii, minval, tt..., a).data[II+1] )...
} {}
template<typename... TT>
constexpr SortMyElements(TT... tt) : SortMyElements(IntRange<0,sizeof...(tt)-1>(), min(tt...), tt...) {}
};
template<>
struct SortMyElements<1> {
int data[1];
constexpr SortMyElements(int x) : data{ x } {}
constexpr SortMyElements(IntHolder<>, int minval, int x) : SortMyElements(x) {}
};
static_assert(SortMyElements<5>(5,2,1,3,1).data[0] == 1, "");
static_assert(SortMyElements<5>(5,2,1,3,1).data[1] == 1, "");
static_assert(SortMyElements<5>(5,2,1,3,1).data[2] == 2, "");
static_assert(SortMyElements<5>(5,2,1,3,1).data[3] == 3, "");
static_assert(SortMyElements<5>(5,2,1,3,1).data[4] == 5, "");
char global_array[ SortMyElements<5>(1,4,2,5,3).data[2] ];
static_assert(sizeof global_array == 3, "");
int main() {
SortMyElements<5> se(1,4,2,5,3);
int se_reference[5] = {1,2,3,4,5};
assert(memcmp(se.data, se_reference, sizeof se.data) == 0);
}
UPDATE: I haven't figured out how to do a fast mergesort (although DyP's answer looks potentially feasible to me). However, this morning I did solve my original puzzle-problem of shuffling zeroes to the end of an array! I used a recursive partition-and-merge algorithm; the code looks like this.
Starting with C++20, all you need to change in your example is to add constexpr to the constructor. That is, in C++20, std::sort is in fact constexpr.