如何使static_assert块在模板类中可重用? [英] How to make static_assert block re-usable in template classes?

查看:66
本文介绍了如何使static_assert块在模板类中可重用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个模板类,可以制作多个static_asserts:

Say I have a template class that makes multiple static_asserts:

template <class T>
class Foo
{
    static_assert(!std::is_const<T>::value,"");
    static_assert(!std::is_reference<T>::value,"");
    static_assert(!std::is_pointer<T>::value,"");

    //...<snip>...
}

现在说我有更多的模板类需要做出相同的断言。

Now say I have more template classes that need to make the same asserts.

有没有办法使 static_assert 块可重用?

Is there a way to make a static_assert block reusable? A "static_assert function" if you will.

推荐答案

您可以做的一件事就是建立一个新特性,即 conjunction 想要的特征去检查。由于您希望所有这些特征的否定,可以直接翻译成

One thing you can do is build a new trait that is a conjunction of the traits you want to check. Since you want the negation of all of those traits that would literally translate to

template<typename T>
using my_trait = std::conjunction<std::negation<std::is_const<T>>,
                                  std::negation<std::is_reference<T>>,
                                  std::negation<std::is_pointer<T>>>;

static_assert(my_trait<int>::value, "");

但必须使用 std :: negation 因为每个特征都是(可能是)痛苦。您可以使用 std :: disjunction 获取所有特征的或,然后像您所做的那样取反静态断言中的值,这将给您

but having to use std::negation for every trait is/can be a pain. You can get rid of that though using std::disjunction to get an "or" of all the traits and then just negate the value in the static assert like you do which gives you

template<typename T>
using my_trait = std::disjunction<std::is_const<T>,
                                  std::is_reference<T>,
                                  std::is_pointer<T>>;

static_assert(!my_trait<int>::value, "");

这篇关于如何使static_assert块在模板类中可重用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆