2016-11-06 5 views
0

変換を減らさないために、以下をどのように移植可能な形で書くことができますか?ビットセットテンプレートの変換を狭めないようにする

#include <bitset> 
#include <iostream> 
#include <climits> 

template <typename T> 
auto int_to_bitset(T x) 
{ 
    //return std::bitset<sizeof(T)*CHAR_BIT>{x}; // does not work, narrowing conversion to unsigned type 
    //return std::bitset<sizeof(T)*CHAR_BIT>{static_cast<unsigned int>(x)}; // might not have the same size as T 
    //return std::bitset<sizeof(T)*CHAR_BIT>{static_cast<unsigned T>(x)}; // What I would like to do, but does not work. I've never seen so many errors. 
    return std::bitset<sizeof(T)*CHAR_BIT>(x); // works, but selects unsigned long long for the constructor's parameter on my system. Can this conversion be relied on? 
} 

int main() 
{ 
    std::cout << int_to_bitset<short>(1 ) << '\n'; 
    std::cout << int_to_bitset<short>(-1 ) << '\n'; 
    std::cout << int_to_bitset  (1 ) << '\n'; 
    std::cout << int_to_bitset  (-1 ) << '\n'; 
    std::cout << int_to_bitset  (1L) << '\n'; 
    std::cout << int_to_bitset  (-1L) << '\n'; 
    std::cout << int_to_bitset  (1LL) << '\n'; 
    std::cout << int_to_bitset  (-1LL) << '\n'; 
} 

が生成されます

0000000000000001 
1111111111111111 
00000000000000000000000000000001 
11111111111111111111111111111111 
00000000000000000000000000000001 
11111111111111111111111111111111 
0000000000000000000000000000000000000000000000000000000000000001 
1111111111111111111111111111111111111111111111111111111111111111 
+0

どのように 'のstd :: make_unsigned'について?動作するようです:http://coliru.stacked-crooked.com/a/ada1221fa10574d3 –

+0

@ m.s。完璧に動作します。 VS2015でも。 :) – wally

答えて

1

あなたはstd::make_unsignedを使用することができます。

template <typename T> 
auto int_to_bitset(T x) 
{ 
    return std::bitset<sizeof(T)*CHAR_BIT>{static_cast<std::make_unsigned_t<T>>(x)}; 
} 

live example

関連する問題