'typedef'是否自动在C ++类中继承? [英] Is 'typedef' automatically inherited in C++ class?

查看:76
本文介绍了'typedef'是否自动在C ++类中继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾经相信'typedef'不会自动继承.但是下面的代码说明存在一些不同之处.

I used to believe that 'typedef' is not automatically inherited. But the code snap below suggests something different.

#include <iostream>
#include <type_traits>

struct A
{
    typedef int X;
};

struct A_ 
{
    typedef char X;
};

struct B : A {};
struct B_ : A, A_ {};

template< typename ... Ts >
using void_t = void;

template< typename T, typename = void >
struct has_typedef_X : std::false_type {};

template< typename T >
struct has_typedef_X< T, void_t<typename T::X> > : std::true_type {};

int main()
{
    std::cout << std::boolalpha;
    std::cout << has_typedef_X<A>::value << std::endl;
    std::cout << has_typedef_X<A_>::value << std::endl;
    std::cout << has_typedef_X<B>::value << std::endl;
    std::cout << has_typedef_X<B_>::value << std::endl;
    return 0;
}

输出为"true true true false".但是从我的观点来看,给出的' has_typedef_X< B> :: value '表示在结构B中,X是'typedef'的.

The output is 'true true true false'. But in my point of view, 'has_typedef_X<B>::value' giving 'true' implies that in struct B, X is 'typedef'ed.

那么,如果有人可以解释这个问题或纠正我?

So if anyone can please explain this problem or correct me?

可以在 http://melpon.org/wandbox/permlink/iwZ6eZ3PoBPgyFBj [已更正网址]

A online version is available at http://melpon.org/wandbox/permlink/iwZ6eZ3PoBPgyFBj [URL corrected]

推荐答案

父级的嵌套类型名称(即成员类型)在派生类的范围内可见并且可以访问,只要其访问说明符不是私有的即可.如果来自不同基类的多个具有相同名称的类型,则不合格名称是不明确的.

Nested type names (i.e. member types) of parents are visible in the scope of a derived class and accessible as long as the access specifier of is not private. If there are multiple types with the same name from different base classes, then the unqualified name is ambiguous.

与此相关的最相关的标准报价是:

The most relevant standard quotes that I found regarding this are:

[class.nested.type]§1

类型名称遵循与其他名称完全相同的范围规则.[...]

Type names obey exactly the same scope rules as other names. [...]

[class.member.lookup]§9

[注意:即使对象具有多个基类,也可以明确地找到基类T中定义的静态成员,嵌套类型或枚举器 .类型T的子对象.[...]

[ Note: A static member, a nested type or an enumerator defined in a base class T can unambiguously be found even if an object has more than one base class subobject of type T. [...]

实际上,使用此标准的一个示例是标准,它指定标准容器的迭代器继承 std :: iterator 模板,该模板只包含嵌套的类型名称.继承的重点是将这些嵌套的类型名称传递给迭代器.(此示例在下一个标准版本(c ++ 17)中将过时,在该版本中,建议不再使用 std :: iterator .)

In fact, an example of using this is the standard which specifies that the iterators of standard containers inherit std::iterator template, which contains nothing but nested type names. The whole point of the inheritance is to get these nested type names to the iterator. (This example will become outdated in the next standard version (c++17), where std::iterator is proposed not to be used anymore.)

这篇关于'typedef'是否自动在C ++类中继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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