Accessing variables from base template class in derived class constructor in C++

后端 未结 2 886
一整个雨季
一整个雨季 2021-01-22 21:32

Let\'s look at this simple code sample including a base class and a class derived from Base, which needs the address of a base class member in its constructor.

#         


        
相关标签:
2条回答
  • 2021-01-22 21:44

    In the second case, the Base is a template and someone might add specializations for the template, all with different member variables. The compiler cannot know until it sees what T is.

    There might also be a global arr that could fit. You can help the compiler by using this->arr[0] to indicate that it always is a member variable.

    0 讨论(0)
  • 2021-01-22 21:56

    arr is a dependent name now. It depends on T. What if there is some T for which Base<T> is specialized to not have an arr? Specifically, from [temp.dep]:

    In the definition of a class or class template, the scope of a dependent base class (14.6.2.1) is not examined during unqualified name lookup either at the point of definition of the class template or member or during an instantiation of the class template or member.

    Base<T> is a dependent base class - it depends on the template parameter T, so its scope is not examined during unqualified name lookup. The way around this is to use qualified name lookup. That is, either the class name:

    parr = &Base<T>::arr[0];
    

    or just with this:

    parr = &this->arr[0];
    
    0 讨论(0)
提交回复
热议问题