Home >Backend Development >C++ >How Does `typedef` Type Propagation Work from Base to Derived Classes in C Templates?
In C , it is possible to define typedefs within a base class to provide convenient aliases for specific data types. However, when using a template-based base class, it is crucial to understand the propagation mechanism of these typedefs to derived classes.
Consider the following example:
template<typename T> class A { public: typedef std::vector<T> Vec_t; }; template<typename T> class B : public A<T> { private: Vec_t v; // fails - Vec_t is not recognized };
Here, the base class A defines a typedef named Vec_t for a vector of type T. In the derived class B, when attempting to use Vec_t without fully qualifying it (e.g., typename A
This behavior is explained by the C standard (14.6.2/3). According to 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."
Therefore, in the derived class B, the unqualified identifier Vec_t is not recognized because the compiler does not examine the base class scope for unqualified name lookup. To access the typedef properly, it is necessary to fully qualify the name using the syntax typename A
The above is the detailed content of How Does `typedef` Type Propagation Work from Base to Derived Classes in C Templates?. For more information, please follow other related articles on the PHP Chinese website!