【问题标题】:what is difference between "using type" syntax in specific method and in general class?特定方法和一般类中的“使用类型”语法有什么区别?
【发布时间】:2023-03-18 23:45:02
【问题描述】:
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) 中使用“使用”语法时,出现类似

的错误
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)中使用它时,我没有错误。 它们有什么区别?

【问题讨论】:

标签: c++ syntax using


【解决方案1】:

当类本身完全定义时,成员函数会在流程的后期实例化。 (因为类模板的成员函数只有在实际使用时才会被实例化,并且它们只能用于完整类型或这些类型的实例),为此,类必须是完整类型。

但是,在实例化 Base 时,Derived 本身是一个不完整的类型(因为必须先实例化基类,然后派生类才能确定其布局),因此在 Base 内部,它无法查看 Derived,因为 Derived 是不完整的。它只是过早地查看其模板类型,使其无效。

【讨论】:

  • 那么,如果我想在Base中使用派生模板类型,我是只使用完整类型,Derived::Type,还是重新定义每个方法?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-04
  • 2017-09-18
  • 1970-01-01
  • 2010-11-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多