代码之家  ›  专栏  ›  技术社区  ›  Tom

了解模板类型/值的重复评估

  •  4
  • Tom  · 技术社区  · 7 年前

    我有以下代码,我不明白为什么最后一个 !has_size<Bar>::value 仅当我不给出完全相同的注释时才计算为true static_assert( !has_size<Bar>::value, ...) 在定义之前 Bar

    #include <type_traits>
    
    template <class, class = void> struct has_size : std::false_type {};
    template <class T> struct has_size<
        T, typename std::enable_if<(sizeof(T) > 0)>::type> 
        : std::true_type
    {};
    
    // expected success
    struct Foo {};
    static_assert( has_size<Foo>::value, "Foo doesn't have size");
    
    struct Bar; // declare bar
    
    // if we comment out this line, the static_assert below struct Bar{} fails
    static_assert( !has_size<Bar>::value, "Bar has a size");    
    
    struct Bar {};  // define bar
    
    // why is this true now, but false if I comment out the previous assertion?
    static_assert( !has_size<Bar>::value, "Bar has a size");
    

    我想稍后根据 has_size<Bar> .MSVC、GCC和Clang之间的行为是相同的。我试图弄清楚这是否是有意的和有充分记录的行为,或者我是通过依赖这种行为而闯入乌兰巴托或其他一些灾难。思想?

    2 回复  |  直到 7 年前
        1
  •  4
  •   Barry    7 年前

    您可以将类模板实例化视为“缓存”或“memoized”。 a single point of instantiation 每个翻译单位。

    所以当你写:

    struct Bar;
    static_assert( !has_size<Bar>::value, "Bar has a size");   // #1
    struct Bar {};
    static_assert( !has_size<Bar>::value, "Bar has a size");   // #2
    

    has_size<Bar> 在处实例化 #1 . 这就是它的 只有 实例化点。AT #2 ,我们不“重做”那个计算-所以它是 仍然 错误的。如果我们从一个不同的翻译单元再次这样做,以一种可以给出不同答案的方式,这将是不正确的(不需要诊断),但在这种情况下,这是一个很好的程序。

    当你评论的时候 α1 ,现在的实例化点是 具有“大小”<bar> 变成 α2 . 及AT 那个 点在程序中, Bar 是完整的,所以 具有“大小”<bar> 现在是 true_type ……所以静态断言触发。

        2
  •  3
  •   Jans    7 年前

    每种完整类型 T 在C++中有 sizeof(T)>0 或者更简单地说 sizeof(T) 是有效表达式, has_size 正在使用此项检测某个类型是否已完成not并正在通过 SFINAE .

    第一个 static_assert

    struct Bar;
    static_assert( !has_size<Bar>::value, "Bar has a size"); // (1)
    

    导致实例化 has_size<Bar> 它被实例化了 Bar 不完整,这导致测试 sizeof(T) > 0 在第二个专业领域 哈萨尔尺寸 失败,此失败诉诸于使用主模板的定义 has_size : std::false_type 哪一种满足 has_size<Bar>::value == false .

    当第二个 静态断言

    struct Bar {};
    static_assert( !has_size<Bar>::value, "Bar has a size"); // (2)
    

    被评估,专业化 具有“大小”<bar> 再次请求,但这次 酒吧 已经完成,并且已经有了 具有“大小”<bar> (继承人) std::false_type )使用这个专门化而不是实例化一个新的专门化,因此仍然说 has_type<Bar>::value == false .

    当你第一次评论 静态断言 (1)在评估(2)时, 酒吧 已经定义,现在 尺寸(t)>0 有效且为真,这将选择 has_size<Bar> : std::true_type 现在它满足了 has_type<Bar>::value == true .

    不涉及UB。


    为了具有反映类型完整性变化的特性 T ,您可以选择:

    template <class T>
    constexpr auto has_size(int) -> decltype((void)sizeof(T), bool{})
    { return true; }
    
    template <class T>
    constexpr auto has_size(...) -> bool
    { return false; }
    
    struct Bar;
    static_assert( !has_size<Bar>(0), "Bar has a size");        
    struct Bar {};  // define bar    
    static_assert( !has_size<Bar>(0), "Bar has a size"); // fail