CRTP -- 访问不完整的类型成员
CRTP -- accessing incomplete type members
相关问题:一,二
在尝试了解CRTP几天后,现在我似乎比以前了解得更少:(
请考虑以下代码:
#include <iostream>
template <class IMPL>
class Interace
{
public:
typedef typename IMPL::TYPE TYPE; // ERROR: "...invalid use of incomplete type..."
void foo() { IMPL::impl(); } // then why does this work?
};
class Implementation : public Interface<Implementation>
{
public:
typedef int TYPE;
static void impl() { std::cout << "impl() " << std::endl; }
};
int main()
{
Implementation obj;
obj.foo();
}
问题是:
为什么我可以从
IMPL::
调用函数(第 8 行(但无法访问类型文件(第 7 行(?在相关问题中,据说IMPL
在这一点上是一个不完整的类型。但是为什么第8行是正确的呢?类型声明/定义的顺序是什么?在我看来:
一个。 Interface
模板 -- 好的。在实例化之前不会带来任何问题
b. 第 11 行 -- 在 class Implementation
之后 -- Implementation
已声明但未定义的类型。
C. 第 11 行 -- Interface<Implementation>
之后 -- 模板实例化。此时,由于步骤(b(,Implementation
已经知道(但未定义!(。编译器"注入"代码,IMPL
替换为Implementation
。在这里,在我看来,第 7 行和第 8 行都不合法,因为此时编译器不知道Implementation
有这些成员。它怎么知道比?
或者也许实例化真的在第 21 行?但是在这种情况下,为什么 07 行不起作用?
我想得更多,对我所拥有的C++类型基本面的理解更少。任何澄清都值得赞赏。
实例化类模板时,非虚拟成员函数以外的其他成员将随之实例化。但是,非虚拟成员函数仅在使用 ODR 时实例化(基本上,调用或获取其地址(。
当编译器遇到class Implementation : public Interface<Implementation>
时,需要实例化Interface<Implementation>
。此时,Implementation
仍然是一个不完整的类型,其TYPE
成员尚未出现。另一方面,Interface<Implementation>::foo
只有在稍后在 main
中调用时才实例化。在这一点上,Implementation
是一个完整的类型。
- 访问C++中的类型成员
- 具有 STL 向量类型成员的类的复制内存
- 重载具有 2 个相同数据类型成员的构造函数
- std::void_t 和嵌套的非类型成员
- 返回对常量结构(指针类型)成员的引用:明显的左值到右值转换
- 使用各种数据类型成员创建对象的简便方法
- 将类类型成员定义为公共和私有之间有什么区别?
- 结构类型成员的默认构造函数中的默认参数
- 如何传递模板模板非类型成员函数指针
- 文本类类型成员函数约束
- 给定仅包含布尔类型成员的结构的两个对象 s1 和 s2,只要 s1 的成员为 true,请检查 s2 的每个成员是否为真
- 如何在 c++ 中使用二进制文件输入/输出读取/写入结构的字符串类型成员
- C++:将模板参数的模板类型成员加为好友的语法正确吗
- C++静态结构类型成员初始化
- C++:作为引用或指针的基类型成员变量
- 左值引用类型成员的用户定义移动构造函数
- 具有指针类型成员的类在 MSVS2012@debug 下销毁时失败.程序错误或错误源
- CRTP -- 访问不完整的类型成员
- 为什么C++默认初始化不对非类类型成员进行零初始化
- 请求非类类型成员