gpt4 book ai didi

c++ - 模板特化中的静态断言即使未实例化也会失败

转载 作者:太空狗 更新时间:2023-10-29 20:20:20 25 4
gpt4 key购买 nike

下面的代码可以正常编译:

#include <type_traits>

template <typename T> struct dependent_true : std::true_type { };
template <typename T> struct dependent_false : std::false_type { };

template <bool B = false>
class X { static_assert(dependent_false<X>::value); };

template <>
class X<true> { static_assert(dependent_true<X>::value); };

int main() {
X<true> x;
}

也就是说,不评估主模板中的static_assert。相反,如果我切换到:

template <bool B = false>
class X { static_assert(dependent_true<X>::value); };

template <>
class X<true> { static_assert(dependent_false<X>::value); };

int main() {
X<false> x;
}

然后,模板特化中的静态断言失败,即使它没有被实例化。 我只是想知道为什么。我在 GCC 8 和 Clang 6 (-std=c++17) 中观察到这种行为。

现场演示:https://wandbox.org/permlink/MOWNLnGMgmuDA2Ht

最佳答案

template <> class X<true> {/* ... */}; - 不再是模板。

[temp.expl.spec]/5

A member of an explicitly specialized class is not implicitly instantiated from the member declaration of the class template; instead, the member of the class template specialization shall itself be explicitly defined if its definition is required. In this case, the definition of the class template explicit specialization shall be in scope at the point at which the member is defined. The definition of an explicitly specialized class is unrelated to the definition of a generated specialization. That is, its members need not have the same names, types, etc. as the members of a generated specialization. Members of an explicitly specialized class template are defined in the same manner as members of normal classes, and not using the template<> syntax. The same is true when defining a member of an explicitly specialized member class. However, template<> is used in defining a member of an explicitly specialized member class template that is specialized as a class template.

特化就像普通类一样。它不是模板,没有任何依赖。因此dependent_false<X>::value只是一个常量表达式,它的计算结果立即为 false。因此立即触发静态断言。

关于c++ - 模板特化中的静态断言即使未实例化也会失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52137187/

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