为什么这不是一个独立的名字?

Why isn't this an independent name?

提问人:TRPh 提问时间:9/26/2020 最后编辑:Remy LebeauTRPh 更新时间:9/26/2020 访问量:62

问:

在类中,需要将变量编写为 ,以便使其成为将在基类中查找的依赖名称。D0mthis->m

但是在类中,编译器知道在基类中查找而不被写成 .D1mmthis->m

这怎么可能?为什么课堂上不需要写成?mD1this->m

#include <iostream>
#include <string>

template<class T>
class B
{
public:
    B(int i) : m(i) {}
    T* fb() {std::cout << "B::fb(): m = " << m << "\n"; return static_cast<T*>(this); }
protected:
    int m;
};

template<class T>
class D0 : public B<T>
{
public:
    D0(int i) : B<T>(i) {}
   /*
    * this-> makes this->m a dependent name so the lookup looks in the base class.  Without this->,
    * m would be an independent name and lookup would not check the base class.
    */
    T* fd0() {std::cout << "D0::fd0(): m = " << this->m << "\n"; return static_cast<T*>(this); }
};

class D1 : public D0<D1>
{
public:
    D1(int i) : D0<D1>(i) {}
   /*
    * D1 doesn't need m qualified by this-> because deriving from D0<D1> somehow
    * makes it unnecessary.
    */
    D1* fd1() {std::cout << "D1::fd1(): m = " << m << "\n"; return this; }
};

int main()
{
    std::string s;
    
    D1 d1(2);
    d1.fd1()->fd0()->fb()->fd0()->fd1();
    
    std::cout << "Press ENTER to exit\n";
    std::getline(std::cin, s);
}
C++ 依赖项名称

评论

2赞 PaulMcKenzie 9/26/2020
考虑这是一个具体的类,而不是一个模板。D1
1赞 Michael Bridges 9/26/2020
这是一个相关的问答,stackoverflow.com/questions/5533354/...

答:

0赞 PaulMcKenzie 9/26/2020 #1

不赘述,它不是一个类模板,它是一个具体的、非模板化的类。因此,不需要使用 来访问 .D1this->m

这是更多信息

如果要复制 中的错误,下面演示了这一点:D1

#include <iostream>
#include <string>

template<class T>
class B
{
public:
    B(int i) : m(i) {}
    T* fb() {std::cout << "B::fb(): m = " << m << "\n"; return static_cast<T*>(this); }
protected:
    int m;
};

template<class T>
class D0 : public B<T>
{
public:
    D0(int i) : B<T>(i) {}
    T* fd0() {std::cout << "D0::fd0(): m = " << this->m << "\n"; return static_cast<T*>(this); }
};

template <typename T>  // Now let's make this a class template
class D1 : public D0<D1<T>>
{
public:
    D1(int i) : D0<D1>(i) {}
    D1* fd1() {std::cout << "D1::fd1(): m = " << m << "\n"; return this; } // This will now produce an error
};

int main()
{
    std::string s;
    
    D1<int> d1(2);
    d1.fd1()->fd0()->fb()->fd0()->fd1();
    
    std::cout << "Press ENTER to exit\n";
    std::getline(std::cin, s);
}

错误:

error: 'm' was not declared in this scope
     D1* fd1() {std::cout << "D1::fd1(): m = " << m << "\n"; return this; }

现在,一旦将其设为类模板,该错误就存在。D1

评论

1赞 Pete Becker 9/26/2020
根本问题是,可能存在没有名为 的成员的专用化。这就是问题所在:没有存在的保证。在原始版本中,必须存在。B<Something>mD0mD1m