具有相同名称的typedef和template参数 [英] typedef and template parameter with same name

查看:80
本文介绍了具有相同名称的typedef和template参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这种情况不正确(这是合乎逻辑的)

Why is that case incorrect (it's logical)

template <typename T>
struct Der: public Base
{
    typedef int T;
    T val;
};

,但是这种情况正确吗?

, but that case is correct?

struct Base
{
    typedef int T;
};

template <typename T>
struct Der: public Base
{
    T val;
};

标准14.6.1/7说:

The Standard 14.6.1/7 says:

对于不依赖于模板参数(14.6.2)的每个基类,如果类模板的定义或出现在模板定义之外的此类模板的成员的定义,如果基类的名称或基类成员的名称与模板参数的名称相同,基类名称或成员名称隐藏了模板参数的名称(3.3.7).

In the definition of a class template or in the definition of a member of such a template that appears outside of the template definition, for each base class which does not depend on a template-parameter (14.6.2), if the name of the base class or the name of a member of the base class is the same as the name of a template-parameter, the base class name or member name hides the template-parameter name (3.3.7).

为什么这里没有歧义?

推荐答案

根据[temp.local]/6,第一个示例不正确:

The first example is incorrect according to [temp.local]/6:

不得在其范围(包括嵌套范围)内重新声明 template-parameter .

但是,在

template <typename T>
struct Der: public Base
{
    T val;
};

T 被从 Base 继承的名称隐藏-如您的报价 所指定.

T is hidden by the name inherited from Base - as specified by your quote.

[..] 如果基类的名称或成员的名称基类与 template-parameter 的名称相同,基类名称或成员名称隐藏 template-parameter 名称(3.3.7).

[..] if the name of the base class or the name of a member of the base class is the same as the name of a template-parameter, the base class name or member name hides the template-parameter name (3.3.7).

也就是说,成员 val 的类型为 int . 演示 .

That is, the member val is of type int. Demo.

这篇关于具有相同名称的typedef和template参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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