gpt4 book ai didi

c++ - "used as non-type template parameter"是否使函数模板隐式实例化?

转载 作者:行者123 更新时间:2023-12-04 11:26:03 25 4
gpt4 key购买 nike

我想写一个类模板M接受不完整类型 C作为模板参数。
但我也想要C最终定义时具有一些特征。
此代码是否有保证

  • 如果定义(标志),则编译,
  • 如果 !defined(FLAG) 编译失败?
  • template <auto> struct Dummy {};

    template <typename C>
    void check()
    {
    static_assert(std::is_trivial_v<C>);
    }

    template <typename C>
    struct M : Dummy<&check<C>>
    {
    //static_assert(std::is_trivial_v<C>);//error: incomplete type
    C * p;
    };

    struct Test;
    M<Test> m;

    int main()
    {
    return 0;
    }

    #if defined(FLAG)
    struct Test {};
    #else
    struct Test { std::string non_trivial_member; };
    #endif

    最佳答案

    From a n4713 ,
    实例化点 [temp.point] (17.7.4.1/8)

    A specialization for a function template, a member function template, or of a member function or static data member of a class template may have multiple points of instantiations within a translation unit, and in addition to the points of instantiation described above, for any such specialization that has a point of instantiation within the translation unit, the end of the translation unit is also considered a point of instantiation. A specialization for a class template has at most one point of instantiation within a translation unit. A specialization for any template may have points of instantiation in multiple translation units. If two different points of instantiation give a template specialization different meanings according to the one-definition rule (6.2), the program is ill-formed, no diagnostic required.


    首先,请注意主要模板是 paa0ssed arguments 一个特化的标准发言。根据我的经验,C++ 程序员使用它的方式与标准不同。
    二、 check<Test>在你的程序中有两个实例化点;一次
    M<Test> m;
    一次在翻译单元的末尾。 check<Test>的含义在 M<Test> mcheck<Test>的含义不同在翻译单元的末尾。一处, Test是不完整的,另一方面它是完整的。正文 check<Test>肯定有不同的含义。
    所以你的程序格式错误,不需要诊断。在您的情况下,格式错误的程序恰好可以执行您想要的操作,但它可以(在标准下)编译为任何内容,或者无法编译。
    我怀疑这条规则背后的原因是让编译器可以自由地实例化 check要么立即,要么推迟到以后。您不能依赖于它实际对 check 的主体进行实例化的两个点中的哪一个。 .

    关于c++ - "used as non-type template parameter"是否使函数模板隐式实例化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67685121/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com