gpt4 book ai didi

c++ - std::make_unsigned 没有给出预期的结果

转载 作者:行者123 更新时间:2023-11-27 22:42:07 28 4
gpt4 key购买 nike

我有这样的东西:

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com