初期設定リストからビットセットを直接構築するコンストラクタはありません。あなたは、機能が必要になるでしょう:
#include <bitset>
#include <initializer_list>
#include <iostream>
auto to_bitset(std::initializer_list<bool> il)
{
using ul = unsigned long;
auto bits = ul(0);
if (il.size())
{
auto mask = ul(1) << (il.size() - 1);
for (auto b : il) {
if (b) {
bits |= mask;
}
mask >>= 1;
}
}
return std::bitset<3> { bits };
}
int main()
{
auto bs = to_bitset({true, false, true});
std::cout << bs << std::endl;
}
期待される結果:
101
コメントで述べたように、可変引数バージョンも可能です。
#include <bitset>
#include <iostream>
#include <utility>
namespace detail {
template<std::size_t...Is, class Tuple>
auto to_bitset(std::index_sequence<Is...>, Tuple&& tuple)
{
static constexpr auto size = sizeof...(Is);
using expand = int[];
unsigned long bits = 0;
void(expand {
0,
((bits |= std::get<Is>(tuple) ? 1ul << (size - Is - 1) : 0),0)...
});
return std::bitset<size>(bits);
}
}
template<class...Bools>
auto to_bitset(Bools&&...bools)
{
return detail::to_bitset(std::make_index_sequence<sizeof...(Bools)>(),
std::make_tuple(bool(bools)...));
}
int main()
{
auto bs = to_bitset(true, false, true);
std::cout << bs << std::endl;
}
私はシフトを行う必要がありますが、その機能は素晴らしいタッチです。 –
@JonathanMee 'fraid so。バリデーションブールの点でTBHのテンプレート関数は、この時点でよりエレガントかもしれません。 –