C ++将模板参数转换为其未签名版本

问题描述 投票:2回答:1

我正在研究一个类模板,它采用任何类型的单个参数T。现在我对integral types感兴趣;后来,当我扩展这个类使用floating point types时,我将专门研究这个类。

在这个类中,我有一个成员变量,它将存储可以存储在这种类型中的最大位表示数。例如:

基本类型和尺寸:值范围

  • signed char: 1Byte8 bits[-127,127] for one's complement或[128,127] for two's complement
  • unsigned char: 1Byte8 bits[0,255]
  • 等等

我可以通过使用该类型的unsigned version来更容易地获得最大值,所以在我的模板类中(这里是伪代码):

template<class T>
binaryRep {
    T t_; // store the value
    std::size_t size_ = sizeof( T ); // size in bytes
    std::size_t maxVal = T( -1 ); // This is where I need T to be it's unsigned version.    
};

如果有人要使用此模板类:

void someFunc() {
    binaryRep<unsigned char> binUC; // This works fine

    binaryRep<char> binSC; // Not giving the needed results.
}

在类的构造函数中有没有办法将T强制转换为unsigned T

在我的构造函数中,我试图做这样的事情:

binaryRep( const T& t ) : t_( static_cast<unsigned T>( t ) ) {
}

然而,这不编译,也不认为它会...但这种性质的东西是我在这里需要的。

[注意:] - 此类中的maxValue成员表示此类型可存储的可行二进制位组合的总数。例如:标准char unsigned char8 bitbyte都具有最大数量的256二进制位组合。

如果您需要更多信息,请告诉我们。

c++ templates casting
1个回答
0
投票

maxVal设置为size_ == sizeof(long long) ? (uLL) -1 : (1uLL << size_) - 1应该可以解决问题。

© www.soinside.com 2019 - 2024. All rights reserved.