template<class Derived>
class Base{
public:
using dType = typename Derived::Type; //1
void interface(){
using dType = typename Derived::Type; //2
}
};
template<typename T>
class Derived:public Base<Derived<T>>{
public:
using Type = T;
};
int main(){
Base<Derived<int>>{};
return 0;
}当我在(1)中使用'using‘语法时,我得到如下错误
test.cpp: In instantiation of 'class Derived<int>':
test.cpp:14:9: required from 'class Base<Derived<int> >'
test.cpp:31:21: required from here
test.cpp:23:7: error: invalid use of incomplete type 'class Base<Derived<int> >'
23 | class Derived:public Base<Derived<T>>{
| ^~~~~~~
test.cpp:12:7: note: declaration of 'class Base<Derived<int> >'
12 | class Base{
|但是,当我在(2)中使用它时,我没有错误。它们有什么不同?
发布于 2021-06-23 07:42:01
当类本身完全定义时,成员函数将在过程中稍后实例化。(因为类模板的成员函数只有在实际使用时才会被实例化,并且它们只能在完整类型或这些类型的实例上使用),要实现这一点,类必须是完整类型。
然而,当Base被实例化时,Derived本身是一个不完整的类型(因为基类必须先实例化,然后派生类才能确定其布局),因此在Base中,它不能查看derived,因为Derived是不完整的。它只是过早地检查了它的模板类型,所以它是有效的。
https://stackoverflow.com/questions/68091413
复制相似问题