Jon*_*Mee 4 c++ boolean bit-shift bitset initializer-list
有没有办法使用 aninitializer_list来构造 a bitset?
例如我想做:
const auto msb = false;
const auto b = true;
const auto lsb = false;
const bitset<3> foo = {msb, b, lsb};
Run Code Online (Sandbox Code Playgroud)
但是当我尝试这个时我得到:
错误:无法
{msb, b, lsb}从“<大括号封闭的初始值设定项列表>”转换为const std::bitset<3u>
我是否必须使用转变来构造一个unsigned long来初始化foo,或者有没有一种我不知道的方法可以做到这一点?
没有构造函数可以直接从初始化列表构造位集。你需要一个函数:
#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;
}
Run Code Online (Sandbox Code Playgroud)
预期成绩:
101
Run Code Online (Sandbox Code Playgroud)
正如评论中提到的,可变版本也是可能的。
#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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1526 次 |
| 最近记录: |