2016-06-21 17 views
1

initializer_list을 사용하여 bitset을 구성하는 방법이 있습니까?비트 세트가있는 initializer_list 사용

const auto msb = false; 
const auto b = true; 
const auto lsb = false; 
const bitset<3> foo = {msb, b, lsb}; 

을하지만이 때 내가 얻을 :

예를 들어 내가 할 싶습니다

error: could not convert {msb, b, lsb} from '<brace-enclosed initializer list>' to const std::bitset<3u>

내가 foo를 초기화하는 unsigned long를 구성 변화를 사용해야합니까, 또는 이 일을 할 수있는 방법이 있습니까?

답변

3

초기화 프로그램 목록에서 비트 세트를 직접 생성하는 생성자가 없습니다.

#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; 
} 
+0

그래서 답은 제가해야 할 일이지만, 그 기능은 좋은 손길입니다. –

+0

@JonathanMee 'fraid so. variadic bool의 관점에서 TBH 템플릿 함수는이 시점에서 더 우아 할 수 있습니다. –