【发布时间】:2019-12-21 09:29:31
【问题描述】:
考虑以下示例:
template<typename T>
class Base
{
public:
inline void fooBase ()
{
T t; // The following error only occurs when class ABC is not defined at the end of the file: "error: t uses undefined class ABC"
}
protected:
};
class ABC;
class DEF;
class Derived : public Base<ABC>
{
public:
void fooDerived ()
{
DEF def; // error: def uses undefined class DEF
}
};
Derived derived;
void foo ()
{
derived.fooBase ();
}
class ABC {};
class DEF {};
问题
- 为什么编译器对只在文件末尾定义的
ABC类感到满意? - 为什么声明
Derived时不需要定义,声明全局foo函数时也不需要定义? - 模板类的成员函数何时实例化?即使该函数被显式内联,该函数似乎在
foo ()中调用该函数后被实例化(在文件末尾)。 - 这种行为是标准 C++ 吗?如果有,是否取决于使用的 C++ 版本?
请注意,fooDerived 会按预期生成错误:在使用该类之前应(完全)定义。
请注意,没有必要单独回答所有问题,因为它们是同一问题的不同表述。
测试环境:
- MSVC(但我对跨平台合规性感兴趣。)
- 它似乎在三个主要编译器(GCC、CLang 和 MSVC)上工作(
DEF def;除外):https://godbolt.org/z/z_c7mc
【问题讨论】:
标签: c++ templates class-template