加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

有没有办法在C模板专门化中将条件置于常量值参数?

发布时间:2020-12-16 10:06:38 所属栏目:百科 来源:网络整理
导读:有没有办法将整数模板参数限制为专门化而不是代码冗余? // redundant codetemplate int Nstruct A {};template struct A 0 {};template struct A 1 {};// what i want is some thing like thistemplate int Nstruct A {};template struct A N 2 {}; 解决方
有没有办法将整数模板参数限制为专门化而不是代码冗余?

// redundant code

template <int N>
struct A {};
template <>
struct A <0> {};
template <>
struct A <1> {};

// what i want is some thing like this

template <int N>
struct A {};

template <>
struct A <N < 2> {};

解决方法

您可以使用 SFINAE =“替换失败不是错误”.例如,有几种方法可以在这里完成

template<int N,typename E=void>
struct A { /* ... */ };     // general type

template<int N>
struct A<N,std::enable_if_t<(N<2)> >
{ /* ... */ };              // specialisation for N<2

请注意,std :: enable_if_t<>是C 14型,相当于

template<bool C,typename T=void>
using enable_if_t = typename std::enable_if<C,T>::type;

它是如何工作的? std :: enable_if的定义类似于

template<bool C,typename T=void>
struct enable_if { using type=T; };

template<typename T>
struct enable_if<false,T> {};

特别是,在条件C为假的情况下,没有子类型enable_if :: type.因此,在上述特化中,enable_if_t<(N< 2>>仅对N <2扩展为有效类型(void).对于N> = 2,我们具有替换失败,因为enable_if<(N< 2)> :: type不存在. C允许这样的失败,但只是忽略了生成的(无效的)代码.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读