为什么当一个模板类从另一个模板类继承时,需要重新指定typedef并限定函数调用? [英] Why when a template class inherits from another template class, typedefs need to be respecified and functions calls qualified?

查看:51
本文介绍了为什么当一个模板类从另一个模板类继承时,需要重新指定typedef并限定函数调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当模板类从另一个模板类继承时,必须再次重新定义基类中的typedef(即,它们不会自动继承),并且必须限定基类中的函数调用.这是为什么?这不是已经明确了吗?

When a template class inherits from another template class, typedefs in the base class must be redefined again (i.e. they are not automatically inherited), and function calls in the base class need to be qualified. Why is that? Isn't this already unambiguous?

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

So if I have 20 template classes, all defining the same typedefs, I am not able to introduce a base class containing these definitions them and inherit from it, as I have to redefine the typedefs anyway in every class, which defeats the purpose. This is makes the source code so unnecessarily verbose.

我可以看到在问题,但我不理解该评论

I can see this has been discussed in this question, but I do not understand the comment

C ++名称查找规则指定仅在依赖模板参数(如果它是从属名称")的情况下,才在模板化的基类中搜索名称.如果名称不依赖模板参数,则不会在其中搜索.

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.

这是什么原因?对我来说这没有意义.

What is the reason for this? It makes no sense to me.

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

Perhaps, the following code snippet would illustrate my question better:

#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;
}

推荐答案

根本原因是类可以专门化:

The fundamental reason is that classes can be specialized:

template<class T>
struct A {};

template<class T>
struct B : A<T> {
  typedef typename A<T>::referent target;
  void niceName() {A<T>::uglyName();}
};

template<class T>
struct A<T*> {
  typedef T referent;
  void uglyName();
};

B<int*>::target i;  // OK: int

当然,相反的情况(主模板定义了有用的东西,而我们只是 fear 担心专业化可能会更改或删除它们)更常见,这使规则看起来是任意的.

Of course, the reverse case (where the primary template defines useful things, and we simply fear that a specialization might change or remove them) is more common, which makes the rule seem arbitrary.

这篇关于为什么当一个模板类从另一个模板类继承时,需要重新指定typedef并限定函数调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆