Reputation: 1337
I have a sample code like
template <typename BIT_LENGTH>
class mod {
public:
mod(BIT_LENGTH val) : m_val (powl(2,sizeof(BIT_LENGTH) * 8) - 1), _val(val) {
}
void value() {
std::cout << " sizeof -- " << sizeof(BIT_LENGTH) << std::endl;
std::cout << " value is : ---- " << m_val << std::endl;
std::cout << " value is : ---- " << _val << std::endl;
}
private:
BIT_LENGTH m_val;
BIT_LENGTH _val;
};
int main(){
mod<uint64_t> mod1(10);
mod1.value();
}
Now i want to initialize my member variable to the max value of the templatized type.
What can be the best possible way to do it ?.
Anything cleaner than using powl function ?
Upvotes: 0
Views: 123
Reputation: 145279
check out std::numeric_limits
.
Oh, it's there in C99. Oh well! In C++ essentially the same function is available with just the name powl
is not a standard C++ function: it's from Linux.pow
, an overload (curiously powl
is not mentioned in the C++11 standard).
By the way, you can (statistically) avoid annoying unintended text substitutions by reserving ALL UPPERCASE for macro names. It's also much easier on the eye. In general.
Also, just in case you're not aware, in C and C++ a byte is not guaranteed to be 8 bits. On some platforms, notably some Texas Instruments digital signal processors, a byte (e.g. a char
) is 16 bits. Historically it has also been other sizes. It has to be at least 8 bits but that's it. The number of bits per byte is available as CHAR_BIT
from <limits.h>
.
Finally, if you always use systematic indentation you will find that you get a much better understanding of the code.
And that also others will much easier understand the code.
And almost magically, that results in a great reduction of the number of bugs you have to spend time on hunting down and correcting.
Upvotes: 2
Reputation: 69977
#include <limits>
std::numeric_limits<BIT_LENGTH>::max()
will do this if BIT_LENGTH
is a built-in type. That is a very misleading name for a data type, by the way.
Upvotes: 1