Home >Backend Development >C++ >How Can I Access Base Class Typedefs in Derived Class Templates in C ?
Template Typedefs for Derived Classes
In C , templates allow defining generic classes and data structures. However, propagating typedefs from base to derived classes requires specific handling.
Consider the following code:
template<typename T> class A { public: typedef std::vector<T> Vec_t; }; template<typename T> class B : public A<T> { private: Vec_t v; // Error: Vec_t is not recognized };
In this example, class A defines a typedef for a vector of type T. However, when trying to use this typedef in the derived class B, an error occurs because Vec_t is not recognized within B's scope.
The reason for this issue stems from the C Standard's treatment of base class scope for templates. According to Section 14.6.2/3 of the Standard:
"In the definition of a class template or a member of a class template, if a base class of the class template depends on a template-parameter, the base class scope is not examined during unqualified name lookup..."
This means that typedefs defined in the base class are not automatically available in the derived class's scope when using unqualified names. To resolve this issue, the typedef must be fully qualified:
typename A<T>::Vec_t v;
By using the typename keyword followed by the fully qualified name of the typedef, you explicitly specify that you want to use the typedef from the base class. This will work as expected and allow you to access the vector typedef within the derived class.
The above is the detailed content of How Can I Access Base Class Typedefs in Derived Class Templates in C ?. For more information, please follow other related articles on the PHP Chinese website!