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

标签 c++ templates nested-class

我不知道如何解释为什么创建成员有效 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/

相关文章:

c++ - 为什么我不能有一个指向 const 迭代器的 shared_ptr?

c++ - 嵌套类的静态对象可以在没有类定义的情况下声明

c++ - ostream operator<< 为采用 STL 容器而重载,传递 std::string 会破坏它吗?

java - 静态嵌套类访问抛出 NoClassDefFoundError

java - 从匿名内部类中抛出检查异常

c++ - 多平台 C++ 项目设置和工具

c++ - 运算符重载 +=

请求变量时的 C++ 调用函数

c++ - 不同命名空间中别名声明的成员特化

c++ - 具有比较器功能和自定义参数的模板