Skip to content

Instantly share code, notes, and snippets.

@plasma-effect
Created July 30, 2015 15:36
Show Gist options
  • Save plasma-effect/d90bba93bd6e4eeca5c2 to your computer and use it in GitHub Desktop.
Save plasma-effect/d90bba93bd6e4eeca5c2 to your computer and use it in GitHub Desktop.
make_bit_array
#pragma once
#include<type_traits>
// Copyright plasma-effect 2015
// Distributed under the Boost Software License, Version 1.0.
// (See http://www.boost.org/LICENSE_1_0.txt)
namespace plasma
{
namespace index_trait
{
template<class, class>struct index_merge;
template<std::size_t... Is0, std::size_t... Is1>struct index_merge<std::index_sequence<Is0...>, std::index_sequence<Is1...>>
{
typedef std::index_sequence<Is0..., Is1...> type;
};
template<class T0, class T1>using index_merge_t = typename index_merge<T0, T1>::type;
template<class T, template<std::size_t>class Func > struct index_foreach;
template<std::size_t... Is, template<std::size_t>class Func>struct index_foreach<std::index_sequence<Is...>, Func>
{
typedef std::index_sequence<Func<Is>::value...> type;
};
template<class T, template<std::size_t>class Func>using index_foreach_t = typename index_foreach<T, Func>::type;
}
}
#pragma once
#include"index_trait.hpp"
#include<array>
// Copyright plasma-effect 2015
// Distributed under the Boost Software License, Version 1.0.
// (See http://www.boost.org/LICENSE_1_0.txt)
namespace plasma
{
namespace detail
{
template<std::size_t V>struct add_value
{
template<std::size_t I>struct func_t
{
static constexpr std::size_t value = V + I;
};
};
template<std::size_t Start, std::size_t Flag>struct make_bit_index
{
typedef index_trait::index_merge_t <
index_trait::index_foreach_t<
typename make_bit_index<(Start >>1), Flag - 1>::type,
typename add_value<Start>::func_t>,
typename make_bit_index<(Start >>1), Flag>::type> type;
};
template<std::size_t Start>struct make_bit_index<Start, 0>
{
typedef std::index_sequence<0> type;
};
template<std::size_t Flag>struct make_bit_index<0, Flag>
{
typedef std::index_sequence<> type;
};
template<>struct make_bit_index<0, 0>
{
typedef std::index_sequence<0> type;
};
template<class T>struct make_array_from_index;
template<std::size_t... Is>struct make_array_from_index<std::index_sequence<Is...>>
{
static std::array<std::size_t, sizeof...(Is)> run()
{
return std::array<std::size_t, sizeof...(Is)>{Is...};
}
};
}
template<std::size_t Size, std::size_t Flag>auto make_bit_array()
{
return detail::make_array_from_index<detail::make_bit_index<1 << (Size - 1), Flag>::type>::run();
}
}
#include<random>
#include<iostream>
#include<bitset>
#include"make_bit_array.hpp"
int main()
{
for (auto v : plasma::make_bit_array<4, 2>())
{
std::cout << static_cast<std::bitset<4>>(v) << std::endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment