Home >Backend Development >C++ >Why Doesn't Unqualified Name Lookup Work with Template Parameter-Dependent Base Classes in C ?

Why Doesn't Unqualified Name Lookup Work with Template Parameter-Dependent Base Classes in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-04 11:43:10712browse

Why Doesn't Unqualified Name Lookup Work with Template Parameter-Dependent Base Classes in C  ?

Template Parameter-Dependent Base Class and Unqualified Name Lookup

In C , when defining a class template, the base class scope is not examined during unqualified name lookup if the base class depends on a template parameter. This behavior is outlined in 14.6.2/3 of the C Standard.

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;  // fails - Vec_t is not recognized
};

In this example, the B class inherits from the A class template, which contains a type alias Vec_t. However, within the B class, attempting to use Vec_t without fully qualifying it (i.e., A::Vec_t) results in a compiler error, indicating that Vec_t is not recognized.

To resolve this issue, the name of the type alias must be fully qualified within the B class:

template<typename T>
class B : public A<T>
{
private:
    typename A<T>::Vec_t v;  // correct - fully qualified name
};

This is because, during unqualified name lookup in the definition of a class template or its member, the base class scope is not examined if the base class depends on a template parameter. Therefore, it is necessary to explicitly qualify the name of the type alias to avoid compiler errors.

The above is the detailed content of Why Doesn't Unqualified Name Lookup Work with Template Parameter-Dependent Base Classes in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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