c – 如何静态检查模板的类型T是否为std :: vector,其中U为float
发布时间:2020-12-16 03:21:25 所属栏目:百科 来源:网络整理
导读:如何检查参数包中的参数是否具有float,double,integral或其std :: vector的类型? 例如T = {int,long,std :: vector double}很好, 而T = {int,std :: vector long double}不是,因为我们不允许std :: vector为长双倍类型. 我有这么远 templateclass ...Tvoid
如何检查参数包中的参数是否具有float,double,integral或其std :: vector的类型?
例如T = {int,long,std :: vector< double>}很好, 而T = {int,std :: vector< long double>}不是,因为我们不允许std :: vector为长双倍类型. 我有这么远 template<class ...T> void foo(T... t) { static_assert(std::is_same<float,T...>::value || std::is_same<double,T...>::value || std::is_integral<T...>::value /* || std::is_same<std::vector<float/double/integral>,T>::value ? */,"unsupported type!"); } 并不确定如何表达std :: vector的限制. 这将是一个很好的重用浮点/双精度/积分检查某种方式,所以我们不需要键入它们两次.就像是 bool basic_check = std::is_same<float,T...>::value || std::is_integral<T...>::value; static_assert(basic_check || std::is_same<std::vector<basic_check>,T>,"unsupported type!"); 当T = {}时,我也希望assert成功(即传递构建). 解决方法
您可以使用模板专业化创建自己的支票.我扩大了检查以包括long double,以减少代码的大小.
#include <type_traits> #include <vector> template<class T> struct is_ok { static constexpr bool value = std::is_floating_point<T>::value || std::is_integral<T>::value; }; template<class T> struct is_ok<std::vector<T>> { static constexpr bool value = std::is_floating_point<T>::value || std::is_integral<T>::value; }; 这是一个演示: #include <cstdio> #define TEST(x) std::printf("%s: %sn",#x,is_ok<x>::value ? "true" : "false") int main() { TEST(int); TEST(float); TEST(char *); TEST(std::vector<int>); TEST(std::vector<float>); TEST(std::vector<char *>); return 0; } 输出: int: true float: true char *: false std::vector<int>: true std::vector<float>: true std::vector<char *>: false (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |