c – 做一个static_assert,一个模板类型是另一个模板
发布时间:2020-12-16 05:30:01 所属栏目:百科 来源:网络整理
导读:我怎么这样static_assert?可能Boost支持它,如果不是C或C 11中的新功能? templateTstruct foo {};templateFooTypestruct bar { static_assert(FooType is indeed fooT for some T,"failure"); //how?}; 解决方法 你可以沿着这些方向做点事情.给定一个可以验
我怎么这样static_assert?可能Boost支持它,如果不是C或C 11中的新功能?
template<T> struct foo {}; template<FooType> struct bar { static_assert(FooType is indeed foo<T> for some T,"failure"); //how? }; 解决方法
你可以沿着这些方向做点事情.给定一个可以验证类是否是类模板的实例化的特征:
#include <type_traits> template<typename T,template<typename> class TT> struct is_instantiation_of : std::false_type { }; template<typename T,template<typename> class TT> struct is_instantiation_of<TT<T>,TT> : std::true_type { }; 在您的程序中使用如下: template<typename T> struct foo {}; template<typename FooType> struct bar { static_assert(is_instantiation_of<FooType,foo>::value,"failure"); }; int main() { bar<int> b; // ERROR! bar<foo<int>> b; // OK! } 如果需要,您可以推广这一点,以检测类是否是具有任意数量(类型)参数的模板实例,如下所示: #include <type_traits> template<template<typename...> class TT,typename T> struct is_instantiation_of : std::false_type { }; template<template<typename...> class TT,typename... Ts> struct is_instantiation_of<TT,TT<Ts...>> : std::true_type { }; template<typename FooType> struct bar { static_assert(is_instantiation_of<foo,FooType>::value,"failure"); }; 然后,您可以在程序中使用它: template<typename FooType> struct bar { static_assert(is_instantiation_of<foo,"failure"); }; int main() { bar<int> b; // ERROR! bar<foo<int>> b; // OK! } 这是一个live example. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |