我试图了解一个简单的 CRTP 模式是否符合标准。
下面的代码按预期编译和工作(在 clang 上)。
但是我对相关标准章节/段落的理解是虚函数CRTP<Derived, Base>::DoSomething()的实例化点应该在代码的(B)点,这里没有Derived的完整声明可用的。因此,内部 typedef Type 也不应该可用。
谁能指出验证此代码的相关标准章节?
换句话说,在这种情况下,虚函数被实例化为 ATFER 点 C?非常感谢您提供任何见解。
弗朗切斯科
//-------------------------
// START CODE
#include <iostream>
struct Type1 {};
struct Type2 {};
struct Base
{
virtual ~Base() {}
virtual void DoSomething() = 0;
};
template< typename T, typename U >
struct CRTP : U
{
virtual void DoSomething() { DoSomething( typename T::Type() ); }
void DoSomething( Type1 ) { std::cout << "1\n"; }
void DoSomething( Type2 ) { std::cout << "2\n"; }
};
// (A) point of inst. of CRTP< Derived, Base > ( 14.7.1.4 ) ??
// (B) point of inst. of CRTP< Derived, Base >::DoSomething() (14.6.4.1.4 ) ??
struct Derived : CRTP< Derived, Base >
{
typedef Type2 Type;
};
// (C)
int main()
{
Base * ptr = new Derived;
ptr->DoSomething();
delete ptr;
}
// END CODE
//-------------------------
相关(?)标准段落:
14.6.4.1 4 如果一个虚函数被隐式实例化,它的实例化点紧跟其封闭类模板特化的实例化点。
14.7.1 4 如果在需要完全定义的对象类型的上下文中使用类类型,或者如果类类型的完整性可能影响程序的语义,则隐式实例化类模板特化。
14.7.1 9 实现不应隐式实例化不需要实例化的类模板的函数模板、成员模板、非虚拟成员函数、成员类或静态数据成员。如果虚拟成员函数不会被实例化,则未指定实现是否隐式实例化类模板的虚拟成员函数。