gpt4 book ai didi

c++ - 类模板的嵌套类可以是 "incomplete"

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:23:04 28 4
gpt4 key购买 nike

我不知道如何解释为什么创建成员有效 inner在类模板中 OuterTempl<T>而在未模板类中这样做是非法的 Outer .

// Non-template version
struct Outer
{
struct Inner;
Inner inner; // incomplete type (I get this)
};

struct Outer::Inner
{
};

// Template version
template<typename T>
struct OuterTempl
{
struct InnerTempl;
InnerTempl inner; // OK ... Huh!?
};

template<typename T>
struct OuterTempl<T>::InnerTempl
{
};

int main()
{
}

另见 ideone .

最佳答案

是的 - 考虑 [temp.mem.class]/1:

A member class of a class template may be defined outside the class template definition in which it is declared.
[ Note: The member class must be defined before its first use that requires an instantiation (14.7.1). For example,

template<class T> struct A {
class B;
};

A<int>::B* b1; // OK: requires A to be defined but not A::B

template<class T> class A<T>::B { };

A<int>::B b2; // OK: requires A::B to be defined

— end note ]

同样重要的是要提到inner的定义,它构成了上面注释描述的Inner的使用,只有在需要时才会被实例化:

Unless a member […] has been explicitly instantiated or explicitly specialized, the specialization of the member is implicitly instantiated when the specialization is referenced in a context that requires the member definition to exist;

由于您的代码中没有 OuterTempl 的实例化,因此永远不会实例化 inner 的定义,并且永远不会实例化 Inner必要的。因此,仅在实例化时才需要此类声明的嵌套类类型的完整性。您没有在此处实例化 OuterTempl,但如果您在 Inner 的定义之前执行此操作,则代码格式不正确。

也就是说,

template<typename T>
struct OuterTempl
{
struct InnerTempl;
InnerTempl inner;
};

template struct OuterTempl<int>; // Bad - Ill-formed (NDR?)

template<typename T>
struct OuterTempl<T>::InnerTempl {};

template struct OuterTempl<int>; // Fine

Demo .

关于c++ - 类模板的嵌套类可以是 "incomplete",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27760896/

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