我有这样的东西:
template<class T>
class SomeClass {
public:
typedef std::make_unsigned<T> unsigned_t;
unsigned_t maxBinBitRep_ { - 1 };
};
int main() {
// Okay prints out 255 as expected.
SomeClass<unsigned char> unsignedChar; // unsigned version
// New to `make_unsigned<>` but should print 255.
//std::cout << unsignedChar.maxBinBitRep << std::endl;
// Should be printing the same as above however it's printing: 4294967295
SomeClass<char> signedChar;
// same as above.
//std::cout << signedChar.maxBinBitRep << std::endl; // signed version
std::cout << "/nPress any key and enter to quit./n" );
char q;
std::cin >> q;
return 0;
}
我正在尝试获取传递到模板参数列表中的 integral
类型,并制作它的 unsigned
版本并将其初始化为 -1
。这应该为我提供任何 integral type
所需的值。
我是否正确使用了 std::make_unsigned
?
我的错误 遗漏了声明中的关键字 class
...已修复打字错误。
编辑 - 我的实际类(class):
template<class T>
class showBinary {
public:
static const std::size_t standardByteWidth_ { 8 };
private:
typedef std::make_unsigned<T> unsigned_t;
unsigned_t maxVal_ { -1 };
T t_;
std::vector<unsigned> bitPattern_;
std::size_t size_ = sizeof( T );
public:
explicit showBinary( T t ) : t_( t ) {
bitPattern_.resize( size_ * standardByteWidth_ );
for ( int i = ((maxVal_ + 1) / 2); i >= 1; i >>= 1 ) {
if ( t_ & i ) {
bitPattern_.emplace_back( 1 );
} else {
bitPattern_.emplace_back( 0 );
}
}
}
template<typename U>
friend std::ostream& operator<<( std::ostream& out, const showBinary<U>& val ) {
std::ostringstream ostring;
ostring << "Val: " << val.t_ << " ";
ostring << "Max Value: " << val.maxVal_ << "\n";
ostring << "Size in bytes: " << val.size_ << " ";
ostring << "Number of bits: " << val.size_ * val.standardByteWidth_ << "\n";
ostring << "Bit Pattern: ";
for ( auto t : val.bitPattern_ ) {
ostring << t;
}
ostring << std::endl;
out << ostring.str();
return out;
}
};
它的用途:
int main() {
showBinary<unsigned char> ucBin( 5 );
showBinary<char> scBin( 5 );
std::cout << ucBin << std::endl;
std::cout << scBin << std::endl;
std::cout << "\nPress any key and enter to quit." << std::endl;
char q;
std::cin >> q;
return 0;
}
最佳答案
Am I using
std::make_unsigned
correctly?
不完全是。修复:
typedef typename std::make_unsigned<T>::type unsigned_t;
您可以使用 std::bitset<>::to_string
将任何整数类型的值转换为其二进制字符串表示形式功能:
template<class T>
std::string as_binary_string(T value) {
return std::bitset<sizeof(T) * 8>(value).to_string();
}
关于c++ - std::make_unsigned 没有给出预期的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48023619/