gpt4 book ai didi

C++ 模板 - 几个特化 - 是否定义了行为?

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

假设我声明了一个模板化结构:

template <int N> struct mystruct;

让我们假设我的结构对所有 N 都有一个通用行为, 除非 N == 0

例如,我可以为 N == 0 声明一个特殊行为与:

template<> struct mystruct<0> {int k = 0};

我还可以通过以下方式声明一般行为:

template<int N> struct mystruct {float k = 3.14;};

如果我在 main 中运行:

struct mystruct<-1> x;
struct mystruct<0> y;
struct mystruct<1> z;
std::cout << x.k << " " << y.k << " " << z.k << std::endl;

我得到了我想要的:3.14 0 3.14 ,无论模板声明的顺序如何。

但是我想知道这种行为是否有保险。事实上,当我声明:

struct mystruct<0> y;

在我看来,这也可以由 mystruct 来定义。实现。

那么问题是:

C++ 规范化是否确保模板特化 <0>覆盖一般的基本实现 <int N> ,无论代码中的模板特化顺序是什么?

最佳答案

对于您的特定情况,因为特化必须出现在主要模板之后,并且假设它们出现,那么是的。否则,如果一个 TU 看到了特化,而另一个 TU 没有看到并且他们都使用 mystruct<0> ,你会得到未定义的行为。

在一般情况下,有许多可能相当复杂的特化,C++ 标准在 [temp.expl.spec]/7 中有这样的说法。 ,强调我的:

The placement of explicit specialization declarations for function templates, class templates, variable templates, member functions of class templates, static data members of class templates, member classes of class templates, member enumerations of class templates, member class templates of class templates, member function templates of class templates, static data member templates of class templates, member functions of member templates of class templates, member functions of member templates of non-template classes, static data member templates of non-template classes, member function templates of member classes of class templates, etc., and the placement of partial specialization declarations of class templates, variable templates, member class templates of non-template classes, static data member templates of non-template classes, member class templates of class templates, etc., can affect whether a program is well-formed according to the relative positioning of the explicit specialization declarations and their points of instantiation in the translation unit as specified above and below. When writing a specialization, be careful about its location; or to make it compile will be such a trial as to kindle its self-immolation.

关于C++ 模板 - 几个特化 - 是否定义了行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48771102/

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