强加模板函数类型的约束,没有c ++ 0x概念

Lio*_*gan 3 c++

现在我们知道Concepts不是C++ 0x的一部分,我正在寻找对模板函数中的类型施加限制的方法.

这是两个例子:

如果我们想确保给定的类型是整数,我们可以使用:

template <class N> inline int f(const N n)
{
    if ((N)0.1 != 0)               // if type of N is floating-point
        err()

    ....
}
Run Code Online (Sandbox Code Playgroud)

如果我们想确保给定类型是无符号整数,我们可以使用:

template <class N> inline int f(const N n)
{
    if ((N)-1 < (N)1)              // if type of N is floating-point / signed-integer
        err()

    ....
}
Run Code Online (Sandbox Code Playgroud)

我正在寻找创造性的方法来检查额外的限制,这些限制会导致运行时失败,或者更好,在编译时(没有概念和没有RTTI).

有什么建议?

Kon*_*lph 12

通过使用类型特征,可以在编译时更好地处理您的检查.

首先:

STATIC_ASSERT(std::numeric_limits<N>::is_integer)
Run Code Online (Sandbox Code Playgroud)

第二:

STATIC_ASSERT(not std::numeric_limits<M>::is_signed)
Run Code Online (Sandbox Code Playgroud)

查看Boost概念检查库Boost.StaticAssert.