如果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 memberis_specialized
shall be true for all such specializations ofnumeric_limits
.
原文地址:https://www.jb51.cc/c/112365.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。