代码之家  ›  专栏  ›  技术社区  ›  Aakash Goel

请帮助我理解这个语法(在C++中实现静态断言)

  •  6
  • Aakash Goel  · 技术社区  · 14 年前

    此语法用作对 this question :

    template <bool>
    struct static_assert;
    
    template <>
    struct static_assert<true> {}; // only true is defined
    
    #define STATIC_ASSERT(x) static_assert<(x)>()
    

    我不懂那个语法。它是如何工作的?

    假设我这样做

    STATIC_ASSERT(true);
    

    它被转换为

    static_assert<true>();
    

    现在怎么办?

    4 回复  |  直到 14 年前
        1
  •  13
  •   Adam Badura    14 年前
    STATIC_ASSERT(true);
    

    确实意味着

    static_assert<true>();
    

    它的计算结果为零。 static_assert<true> 只是一个没有任何成员的空结构。 static_assert<true>() 创建该结构的对象,而不将其存储在任何位置。

    这只是编译,什么也不做。

    另一方面

    STATIC_ASSERT(false);
    

    方法

    static_assert<false>();
    

    导致编译错误。 static_assert 没有专门的 false . 所以使用了一个通用的形式。但一般形式如下:

    template <bool>
    struct static_assert;
    

    它只是一个结构的声明,而不是它的定义。所以 static_assert<false>() 导致编译错误,因为它试图生成未定义结构的对象。

        2
  •  9
  •   sharptooth    14 年前

    static_assert<true>(); 使

    template <>
    struct static_assert<true> {}
    

    模板化结构专门化正在完成的临时对象创建-对构造函数的调用,以及稍后对析构函数的调用,这两个调用都有望被优化器消除,因为它们什么都不做。因为 true 并且没有模板结构的通用版本所有计算结果为 static_assert<false>(); 不会编译。

        3
  •  4
  •   kennytm    14 年前

    在表达式中

    static_assert<true>();
    

    自从 static_assert<true> 是一个类型,它将调用 静态断言<true> . AS 静态断言<true> 专门化为空结构,不会影响任何内容。


    然而,在

    static_assert<false>();
    

    因为没有专门的 static_assert<false> ,一般定义

    template <bool>
    struct static_assert;
    

    将被使用。但在这里,类型 static_assert<B> 不完全 . 所以调用的构造函数 静态断言 将导致编译错误。


    因此,这被称为“static assert”,因为如果表达式的计算结果为 false ,类似于 normal assert() function 这将在运行时终止程序。

        4
  •  2
  •   SadSido    14 年前

    嗯,我想是关于模板专业化的。static_assert(true)将成功编译,因为存在“static_assert<true>”的定义(而不仅仅是声明)。

    静态断言(false)将被编译器拒绝,因为只有“static\u assert<false>”的声明,没有定义。

    更新:对于Visual Studio,static_assert(true)正常,但static_assert(false)会触发错误:“错误C2514:static_assert<uuuuormal>”:类没有构造函数[with uormal=false]