c – 确定:: std :: numeric_limits是否可以安全地实例化

类template :: std :: numeric_limits< T>只能为类型T实例化,这可以是函数的返回值,因为它总是定义成员函数,如static constexpr T min()noexcept {return T(); }(有关c 03或c 11中非专门版本的更多信息,请参阅 http://www.cplusplus.com/reference/limits/numeric_limits/).

如果T是int [2],则实例化将立即导致编译时错误,因为int [2]不能是函数的返回值.

Wraps :: std :: numeric_limits与安全的版本很容易 – 如果一种方法来确定是否可以安全地实例化:: std :: numeric_limits是已知的.这是必要的,因为如果可能,应该访问有问题的功能.

测试的明显的(显然是错误的)方式:: std :: numeric_limits< T> :: is_specialised不起作用,因为它需要实例化有问题的类模板.

有没有方法来测试实例化的安全性,最好不列举所有已知的坏类型?甚至可以用一般技术来确定任何类模板实例化是否安全?

解决方法

关于决定是否可以为函数返回类型的类型特征,我将如何处理它:
#include <type_traits>

template<typename T,typename = void>
struct can_be_returned_from_function : std::false_type { };

template<typename T>
struct can_be_returned_from_function<T,typename std::enable_if<!std::is_abstract<T>::value,decltype(std::declval<T()>(),(void)0)>::type>
    : std::true_type { };

另一方面,as suggested by Tom Knapen in the comments,您可能希望使用std::is_arithmetic标准类型特征来确定是否可以为某种类型专门设计numeric_limits.

根据C11标准对numeric_limits类模板的第18.3.2.1/2段,其实:

Specializations shall be provided for each arithmetic type,both floating point and integer,including bool.
The member is_specialized shall be true for all such specializations of numeric_limits.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...