Using numeric_limits to default parameter values
I have a template statistics class that has range parameters.
template <typename T>
class limitStats
{
public:
limitStats(T mx, T min) :
max(mx),
min(mn),
range(mx-mn)
{;}
private:
const T max;
const开发者_C百科 T min;
const T range;
}
I would like to put default values of maximum and minimum allowable values, but the minimum value is not the same for floating point and integer types.
Normally I can write
T min_val = numeric_limits<T>::isinteger ? numeric_limits<T>::min() : -numeric_limits<T>::max();
I have found that I can't use it as a default parameter
limitStats(T mx = std::numeric_limts<T>::max(),
T mn = numeric_limits<T>::isinteger ? numeric_limits<T>::min() : -numeric_limits<T>::max())
Is there a way of achieving something like this?
You might want to rethink your design. What are you trying to do with your limitStats
that std::numeric_limits
doesn't provide?
Don't replicate the badness of the design of std::numeric_limits
. For example, std::numeric_limits<double>::min()
is terribly misnamed. The minimum double is the additive inverse of the maximum double. std::numeric_limits
is an abuse of notation and an abuse of templates. In my opinion, of course.
Your idea for min
is ill-formed. Think about your default with respect to limitStats<unsigned int>
.
With the defaults, your range
is invalid for signed integers. For unsigned ints it replicates max
, assuming you fix the problem with limitStats<unsigned int>::min
. For floating point types, it is either invalid or replicates max
, depending on what you mean by limitStats<floating_point_type>::min
.
Does it even make sense to allow default values? You wouldn't even have this question if you simply don't provide defaults and make the default constructor private/unimplemented.
There are so many syntax errors and typos that it is hard to tell which of those is your problem.
numeric_limits
is a template, so you access it as numeric_limits<int>::is_integer
or with a template type numeric_limits<T>::max()
.
Use
boost::numeric::bounds<T>::lowest()
See http://www.boost.org/doc/libs/1_33_1/libs/numeric/conversion/doc/bounds.html
I just hit the same issue when trying to have a function signature like below in Windows on Visual studio while trying to create a DLL
int
GetARandomNum(
int lowest = std::numeric_limits<int>::min(),
int highest = std::numeric_limits<int>::max());
When trying various stuff, I decided to remove #inlcude <windows.h>
from stdafx.h
and things started building fine. Given that 'stdafx.h' is selected by default in VS and not including it or not does not make any difference to build error, I decided to simply move #inlcude <windows.h>
from stdafx'h
to cpp files wherever its needed which in case of a DLL project is usually in dllmain.cpp only. I do not know why Windows.h
is messing with C+11 headers but I have seen similar issue earlier also.
精彩评论