简体   繁体   中英

Why is this class's own protected member inaccessible from a template method?

Why can I not access the protected members from a template method of a class?

I may be missing some special friend declaration here but it eludes me. I feel like I should be able to do this.

The error is:

error: 'char* ClassB<char>::a' is protected

Example source:

template<typename T>
class ClassA;

template<typename T>
class ClassB {
protected:
   T* a;

public:
   ClassB()
   : a(0) {}

   template<typename U>
   ClassB(const ClassB<U>& other)
   :
   // error: ‘char* ClassB<char>::a’ is protected
   a(other.a) {}
};

////

template<typename T>
class ClassA : public ClassB<T> {
public:
   ClassA() {}
};

////

namespace name {
   typedef ClassA<char> A;
   typedef ClassB<const char> B;
}

int main() {
   name::A a;
   name::B b = a;

   return 0;
}

You can't do it for the same reason that ClassA cannot access the protected/private members of ClassB . The fact that templated classes share a common name doesn't really matter to them. ClassB<T> and ClassB<U> treat each other like entirely different classes and so their members aren't accessible to each other.

The reason for this becomes clearer when you realize you can specialize templated classes, which means that it's possible to have implementations of ClassB that do not have a member named a (or do have a member named a , but use it in an entirely different way, and so it shouldn't be accessed).

The fact is that ClassB<T> and ClassB<U> are different classes (unless T = U , but that's not generally true and so the compiler can't rely on that assumption). Hence, they can't access each other.

This is an abstraction feature of the language. Just like two independent classes, ClassB<T> and ClassB<U> treat each other like they are not related and are different classes and so they cannot access private and protected members of each other.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM