c++ - 为什么当一个模板类继承另一个模板类时,需要重新指定typedefs和函数调用限定?

标签 c++ templates typedef

当一个模板类继承另一个模板类时,基类中的typedef必须重新定义(即不会自动继承),基类中的函数调用需要限定。这是为什么?这不是已经很明确了吗?

因此,如果我有 20 个模板类,都定义了相同的 typedef,我将无法引入包含这些定义的基类并从中继承,因为无论如何我都必须在每个类中重新定义 typedef,这会破坏目的。这使得源代码变得不必要地冗长。

我可以看到这已在 question 中讨论过, 但我不明白评论

The C++ name lookup rules specify that a name is only searched in a templated base classes if it depends on a template parameter (if it is a "dependent name"). If a name does not depend on a template parameter it isn't searched there.

这是什么原因?这对我来说毫无意义。

也许,下面的代码片段可以更好地说明我的问题:

#include <iostream>

template <unsigned N, typename T>
struct A
{
   typedef T U;
   static void foo(T x) { std::cout << N + x << "\n"; }
};

template <unsigned N, typename T>
struct B : public A<N, T>
{
    // Why do I have to redeclare U? Isn't is unambiguous already?
    typedef typename A<N, T>::U U;

    //  why do I have to specify B::? Isn't it unambiguous already?
    static void zoo(U x) { B::foo(x); }  
};

int main()
{
    B<2,int>().zoo(3);
    B<2,double>().zoo(3.5);
    return 0;
}

最佳答案

这是因为两阶段查找。引自 here :

  1. Template definition time: when the template is initially parsed, long before it is instantiated, the compiler parses the template and looks up any "non-dependent" names. A name is "non-dependent" if the results of name lookup do not depend on any template parameters, and therefore will be the same from one template instantiation to another.
  2. Template instantiation time: when the template is instantiated, the compiler looks up any "dependent" names, now that it has the full set of template arguments to perform lookup. The results of this lookup can (and often do!) vary from one template instantiation to another.

因此,在初始解析期间,编译器认为 U 是非依赖名称并尝试查找它但找不到任何内容,因为它不允许查看 依赖基类。但是,如果 U 是从属名称,那么编译器会在实例化阶段查找它,并会在基类中找到它。

顺便说一句:VS 很容易编译它,但他们最近增加了两阶段查找的可能性。

关于c++ - 为什么当一个模板类继承另一个模板类时,需要重新指定typedefs和函数调用限定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48199780/

相关文章:

c++ - Visual Studio 2010 : error code -2146232576 (0x80131700)

c++ - 模板类截断 double

c++ - 为什么在调用 glDrawArrays 之前不需要绑定(bind)顶点缓冲区对象?

c++ - 为什么迭代器类型推导会失败?

templates - 属性可以应用于模板吗?

c++ - boost::bind对应的类型定义

c++ - 重复的 typedef - 在 C 中无效但在 C++ 中有效?

c++ - 制作一个关于 qtopia 错误的文件

C++在基类问题上返回带有模板的嵌套类

对 C 中的 typedef 的困惑