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

c std :: enable_if

发布时间:2020-12-16 06:47:52 所属栏目:百科 来源:网络整理
导读:我对std :: enable_if很新,并想知道如何使用它. 我有一个模板类: templateint a,int bclass foo {} 现在我只想在b等于10时实例化它. 我可以使用std :: enable_if来实现这一点吗? 第二个问题: 如果我有一个foo类的成员 templateint a,int bclass foo { int
我对std :: enable_if很新,并想知道如何使用它.
我有一个模板类:

template<int a,int b>
class foo {
}

现在我只想在b等于10时实例化它.
我可以使用std :: enable_if来实现这一点吗?

第二个问题:
如果我有一个foo类的成员

template<int a,int b>
class foo {
  int c;
}

我只想拥有c

a = 5.

我如何使用std :: enable_if做到这一点?
这是使用std :: enable_if的正确案例吗?

解决方法

我想你可以更好地使用static_assert来强制执行该约束而不是enable_if

template<int a,int b>
class foo {
    static_assert(a+b==10,"a+b is not 10");
};

int main()
{
    foo<5,5> f; // will compile
    foo<1,5> f; // will fail to compile with error: a+b is not 10
    return 0;
}

enable_if主要用于根据类型特征有条件地从重载决策中删除函数和类,并为不同类型特征提供单独的函数重载和特化.

(编辑:李大同)

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

    推荐文章
      热点阅读