My Octopress Blog

A blogging framework for hackers.

Numerical_limits

I’m working on a C++ class that encapsulates changes to a “steerable” variable. It’s part of a system that allows trusted commands from a socket library to change the value of registered variables. For example, a client might:

1
2
3
4
5
6
7
8
int sInt(0);
float sFloat(0.3);
registerParam("someSteerableInteger", &sInt);
registerParam("someSteerableFloat", &sFloat);
...
// Library makes these calls after receiving remote commands:
setParam("someSteerableInteger", 5);
setParam("someSteerableFloat", 3.4);

There’s some intelligence in the class to ensure integrity of the data. For example, it will cast the value passed into setParam(...) correctly, so that a call to setParam("someSteerableInteger", 5.3) results in the 5.3 cast as an integer and then used to set the integer’s value.

Some of the other intelligence needed is that the user might specify the minimum and maximum valid values the variable might take on. Or he or she might not. If not, it would be nice to have a convenient way of specifying a reasonable default minimum and maximum.

Enter numerical_limits. It’s a static templated class that can give you some insight into the built-in types. For example:

1
2
3
4
5
6
#include <iostream>
#include <limits>
using namespace std;
...
cout << "Min unsigned int: " << numerical_limits<unsigned int>::min() << endl;
cout << "Max float: " << numerical_limits<float>::max() << endl;