Home > Backend Development > C++ > How Does `typedef` Type Propagation Work from Base to Derived Classes in C Templates?

How Does `typedef` Type Propagation Work from Base to Derived Classes in C Templates?

DDD
Release: 2024-12-09 04:31:14
Original
873 people have browsed it

How Does `typedef` Type Propagation Work from Base to Derived Classes in C   Templates?

Type Propagation of 'typedef' from Base to Derived Class for 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
};
Copy after login

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::Vec_t), the compiler raises an error.

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::Vec_t.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template