The*_* do 3 c++ templates metaprogramming
我刚刚limits.h被微软所吸引.我试着检查max()函数的返回类型是什么,令我惊讶的是我看到这样的东西:
// TEMPLATE CLASS numeric_limits
template<class _Ty>
class numeric_limits
: public _Num_base
{ // numeric limits for arbitrary type _Ty (say little or nothing)
public:
static _Ty (__CRTDECL min)() _THROW0()
{ // return minimum value
return (_Ty(0));
}
static _Ty (__CRTDECL max)() _THROW0()
{ // return maximum value
return (_Ty(0));//EXACTLY THE SAME WHAT IN min<<------------------
}
//... other stuff
};
Run Code Online (Sandbox Code Playgroud)
怎么可能在两者中min并且max返回完全一样?这是否意味着如果我写makeSanwich()返回(_Ty(0))它会为我做一个三明治?怎么可能只有功能名称不同的相同代码我们得到不同的结果?
那不是相关的代码.
numeric_limits<T>专用于本机整数类型,在这些特化中,实现了相关的值/逻辑.看这里.
上面的代码是所有非专用类型的一揽子代码,它们确实会为两者min()和它们返回相同的值max().亲自尝试一下:
struct foo {
int x;
foo(int x) : x(x) {}
};
bool operator ==(foo const& a, foo const& b) { return a.x == b.x; }
assert(std::numeric_limits<foo>::min() == std::numeric_limits<foo>::max());
Run Code Online (Sandbox Code Playgroud)
......但我不确定这种行为是否符合标准的要求.上面的代码同样可能引发编译时错误,因为numeric_limits还没有专门用于foo.