473,772 Members | 2,349 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Max value of an integer type?

I'm writing a template, and I need to know the maximum value of a given
integer type at compile time. something like:

template<class NumType>
class Arb {
public:

static NumType const max = /* maximum value */;

};
If the template were only to be used with unsigned integer types, then
I'd do the following:

template<class NumType>
class Arb {
public:

static NumType const max = -1;

};
I need a compile-time constant which evaluates to the maximum value of an
integer type.

Any ideas?

If it weren't undefined behaviour to overflow a signed integer, I could
use a metaprogramming technique such as the following:

template<class T, bool overflow = false>
struct MaxIntVal {
private:

static T const internal = 1 + MaxIntVal<T,...

public:

static T const val = SCHAR_MAX + internal;
};
--

Frederick Gotham
Jul 4 '06 #1
35 12586
* Frederick Gotham:
I'm writing a template, and I need to know the maximum value of a given
integer type at compile time.
template< typename T struct Max;
template<struct Max<int>{ static int const value = INT_MAX; };
and so on

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 4 '06 #2
Frederick Gotham wrote:
>
I need a compile-time constant which evaluates to the maximum value of an
integer type.
Are you sure it has to be compile time? If not just use
std::numeric_li mits<T>::max()
--
Ian Collins.
Jul 4 '06 #3

I have a solution (although I intend on making it more compile-time-
efficient as I can assume that "digits" is at least 7).

#include<limits >

template< class T,
T shift_by = 0,
bool no_more_digits = shift_by == std::numeric_li mits
<T>::digits
>
struct IntMax {
private:

static T const one = 1;

public:

static T const val = (one << shift_by) | IntMax<T,shift_ by +
one>::val;

};

template<class T, T shift_by>
struct IntMax<T,shift_ by,true{

static T const val = 0;
};
#include <iostream>
int main()
{
std::cout <<

"Max values\n"
"============\n \n"

" Signed char: " << (int)IntMax<sig ned char>::val <<

"\nSigned short: " << IntMax<short>:: val <<

"\n Signed int: " << IntMax<int>::va l <<

"\n Signed long: " << IntMax<long>::v al;

}
--

Frederick Gotham
Jul 4 '06 #4
Frederick Gotham posted:
>
I have a solution (although I intend on making it more compile-time-
efficient as I can assume that "digits" is at least 7).

Here's the more efficient version:
#include<limits >
template< class T,
T shift_by,
bool no_more_digits = shift_by == std::numeric_li mits
<T>::digits
>
struct IntMax_Internal {
private:

static T const one = 1;

public:

static T const val = (one << shift_by) | IntMax_Internal <T,shift_by +
one>::val;

};

template<class T, T shift_by>
struct IntMax_Internal <T,shift_by,tru e{

static T const val = 0;
};

template< class T >
struct IntMax {
private:

static T const one_two_seven = 127;

public:

static T const val = one_two_seven | IntMax_Internal <T,7>::val;
};
#include <iostream>
int main()
{
std::cout <<

"Max values\n"
"==========\n\n "

" Unsigned char: " << (int)IntMax<uns igned char>::val <<

"\nUnsigned short: " << IntMax<unsigned short>::val <<

"\n Unsigned int: " << IntMax<unsigned >::val <<

"\n Unsigned long: " << IntMax<unsigned long>::val <<

"\n\n Signed char: " << (int)IntMax<sig ned char>::val <<

"\n Signed short: " << IntMax<short>:: val <<

"\n Signed int: " << IntMax<int>::va l <<

"\n Signed long: " << IntMax<long>::v al;

}


--

Frederick Gotham
Jul 5 '06 #5

Frederick Gotham wrote:
template< class T,
T shift_by,
bool no_more_digits = shift_by == std::numeric_li mits
<T>::digits
>
....

Although this would probably work 99% of the time, I think technically
that the standard does not require 2s compliment arithmetic (or
whatever it is called) - ie you can't assume setting all bits to 1
gives you the largest value.
As mentioned earlier, I think you would be better using INT_MAX, etc in
a bunch of specializations .
If you wanted to get really perverse, you might be able to do something
somehow similar to using bits - recursively double the value until it
doesn't get bigger, then (restore last largest value and) start adding
half as much, then 1/4, etc until you are not adding anything.

eg if max is 20 (strange max!)

search = 1;
try adding 2? =search = 3;
+ 4 ? =search = 7;
+ 8 ? =search = 15;
+ 16 ? =overflow!! - back off!
+ 8 ? =overflow!!
+ 4 ? =search = 19
+ 2 ? =overflow!
+ 1 ? =search = 20.
stop because you are at 1. If there was 'room' to add another 1, then
+ 2 would have worked.

Anyhow, perserve, and not really understandable by the next coder who
looks at it - even if that is you 2 years from now. But I suspect it
could be coded with templates.

Of course, I don't know what the standard says will happen when compile
time constants 'overflow'....

- Tony

Jul 5 '06 #6
Frederick Gotham wrote:
I have a solution (although I intend on making it more compile-time-
efficient as I can assume that "digits" is at least 7).

#include<limits >

template< class T,
T shift_by = 0,
bool no_more_digits = shift_by == std::numeric_li mits
<T>::digits
>
struct IntMax {
private:

static T const one = 1;

public:

static T const val = (one << shift_by) | IntMax<T,shift_ by +
one>::val;

};

template<class T, T shift_by>
struct IntMax<T,shift_ by,true{

static T const val = 0;
};
If you can use numeric_limits: :digits, wouldn't this be simpler?

template <typename T>
struct intinfo {
static const T max = (static_cast<T> (1) <<
std::numeric_li mits<T>::digits - 1) - 1 << 1 | 1;
};

Or are there some special cases this doesn't handle correctly?

Jul 5 '06 #7
Ian Collins wrote:
Frederick Gotham wrote:
>>
I need a compile-time constant which evaluates to the maximum value of an
integer type.
Are you sure it has to be compile time? If not just use
std::numeric_li mits<T>::max()
I guess there must be a good reason why this is not a compile-time constant,
but a function. I don't think that there could be an implementation where
those values change during runtime, so what is the reason to make it a
function?

Jul 5 '06 #8
posted:
>
Frederick Gotham wrote:
>template< class T,
T shift_by,
bool no_more_digits = shift_by == std::numeric_li mits
<T>::digits
> >
...

Although this would probably work 99% of the time, I think technically
that the standard does not require 2s compliment arithmetic (or
whatever it is called) - ie you can't assume setting all bits to 1
gives you the largest value.

"digits" gives you the amount of value bits, excluding the sign bit.

If the sign bit (if any) is zero, and if all the rest of the bits are 1,
then you have the max value.
--

Frederick Gotham
Jul 5 '06 #9
=?utf-8?B?SGFyYWxkIHZ hbiBExLNr?= posted:

If you can use numeric_limits: :digits, wouldn't this be simpler?

template <typename T>
struct intinfo {
static const T max = (static_cast<T> (1) <<
std::numeric_li mits<T>::digits - 1) - 1 << 1 | 1;
};

Or are there some special cases this doesn't handle correctly?

That's brilliant. Here's the updated code:

#include<limits >

template<class T>
struct IntMax {
private:

static T const MSBOnly = static_cast<T>( 1) << std::numeric_li mits
<T>::digits - 1;

public:

static T const val = MSBOnly | MSBOnly - 1;

};
#include <iostream>
int main()
{
std::cout <<

"Max values\n"
"==========\n\n "

" Unsigned char: " << (int)IntMax<uns igned char>::val <<

"\nUnsigned short: " << IntMax<unsigned short>::val <<

"\n Unsigned int: " << IntMax<unsigned >::val <<

"\n Unsigned long: " << IntMax<unsigned long>::val <<

"\n\n Signed char: " << (int)IntMax<sig ned char>::val <<

"\n Signed short: " << IntMax<short>:: val <<

"\n Signed int: " << IntMax<int>::va l <<

"\n Signed long: " << IntMax<long>::v al;

}
--

Frederick Gotham
Jul 5 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

20
4850
by: Glenn Venzke | last post by:
I'm writing a class with a method that will accept 1 of 3 items listed in an enum. Is it possible to pass the item name without the enum name in your calling statement? EXAMPLE: public enum EnumName FirstValue = 1 SecondValue = 2 ThirdValue = 3
4
1831
by: Semi Head | last post by:
Hello folks, I'm looking for a script to validate a specific number value in a standard form input field. An example would be, if someone enters a number into a form input, I want the script to validate it and give an alert if that the number exceeds the set script value. Like if the script value is set for 3000 and the number 3002 is entered, I want an alert to pop and give a warning, BTW - This script must be generic enough to work...
12
3221
by: Francois Grieu | last post by:
The values of ((int)0.7) and ((int)-0.7) seem to be 0 Is this independent of implementation ? TIA, François Grieu
4
2560
by: Chris Bower | last post by:
Reposted from aspnet.buildingcontrols: Ok, I've got a bunch of derived controls that all have a property Rights of type Rights (Rights is an Enumerator). I wrote a custom TypeConverter so that I can use comma separated values in design-time. The TypeConverter works great in design-time. It converts to and from just fine... However, when I try to load any page in the site now I get the following error (Following the error is code for the...
2
7213
by: Jim in Arizona | last post by:
I'm learning form an ASP.NET 1.0 book and I tried out some code that returns this error: Compiler Error Message: BC30311: Value of type 'Integer' cannot be converted to 'ASP.multiclasses_aspx.VehicleKey'. Source Error: Line 106:
2
1683
by: Arne | last post by:
Will the dataset below be returned by value or reference? Public Shared Function getDS() As DataSet Dim ds As New DataSet '... do something Return ds End Function
20
3720
by: MLH | last post by:
120 MyString = "How many copies of each letter do you need?" 150 MyVariant = InputBox(MyString, "How Many?", "3") If MyVariant = "2" Then MsgBox "MyVariant equals the string '2'" If MyVariant = 2 Then MsgBox "MyVariant also equals the value 2" 160 If MyVariant = "" Then HowManyCopies = 1 170 If Not IsNumeric(MyVariant) Then HowManyCopies = 1 MsgBox "OK. HowManyCopies has a value of " & CStr(HowManyCopies) 180 For i =...
23
2196
by: Tomás | last post by:
Anything wrong with the following code?: #include <cstdlib> int main() { for (unsigned i = 0; i != 1000; ++i) { int *p = reinterpret_cast<int*>( std::rand() );
22
27077
by: subramanian100in | last post by:
Consider the following program #include <limits.h> #include <stddef.h> int main(void) { size_t size; size_t bytes = sizeof(size_t);
14
1772
by: KK | last post by:
Dear All I have a small problem with using as operator on value type array. Here is an example what I am trying to do. using System; using System.Collections.Generic; using System.Text;
0
9454
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10106
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10039
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9914
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6716
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5355
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4009
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3610
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2851
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.