c++ - 继承类中的 g++ typedef 模板

标签 c++ templates inheritance typedef

简化我的问题我们可以考虑:

template <class T>
class Base{
    typedef typename std::pair<T, T> pair;
};

template <class T>
class Inheritor : public Base<T> {
    pair *p;                          
    // mean that we want to use constructor of std::pair.
    // say: std::pair withou argument list

    Inheritor<T>::pair *p;
    // dont see his typename
    // say: pair does not name a type

    typename pair *p;
    // I was sure that it works.
    // I dont know why it doesnt work.
    // say: expected nested-name-specifier before 'pair

    typename Inheritor<T>::pair *p;
    // ok!
};

为什么我们不能写类型名对 *p ?我不明白 Inheritor::的原因!它使代码更复杂,更难阅读!

附言 (当然是公开的。正如我所说的“简化我的问题......”)

typedef typename Base<T>::pair pair;

在我看来,这是一个...很难翻译的俄语单词("костыль")

它看起来像 Kludge 或管道胶带或 hack =)

据我了解:

typedefs 照常继承函数或变量。 但它不可访问(!!!)。 要访问它,我们应该写

typedef typename Base<T>::pair pair;

typedef typename Inheritor<T>::pair pair;

看起来很有趣Hindu code但我们需要它! (>_<)''''

公共(public)范围内的资源

最佳答案

当类型名称依赖于模板参数时,它是一个依赖名称You have to use typename to indicate you're naming a type.阅读那篇文章,您会发现您对 typename 的使用没有任何意义,除了最后一种情况。

您的代码可能如下所示:

template <class T>
class Base
{
public: // you probably don't want a private typedef
    typedef std::pair<T, T> pair; // typename isn't needed here, this isn't dependent
};

template <class T>
class Inheritor : public Base<T>
{
public: // public again
    typedef typename Base<T>::pair pair; // get the Base's pair type, typedef it

    pair *p; // ah, easy to use
};

关于c++ - 继承类中的 g++ typedef 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3927980/

相关文章:

c++ - 我是否误解了这个默认参数 shared_ptr 的范围?

c++ - 为什么 "virtuality"方法在 C++ 中隐式传播?

c# - 我可以创建一个继承自强类型 DataRow 的自定义类吗?

c++ - 在 Visual Studio 2017(VC++) 的链接阶段禁用库警告是否安全?

c++ - 摘要:UndefinedBehaviorSanitizer:未定义行为prog_joined.cpp:25:17

c++ - 使用 C++ 类处理常用参数

c++ - 将 std::partition 推广到 multi_partition

c++ - 标准库中的operator==如何将字符串隐式转换为string_view?

c++ - C++中如何获取子类成员

c++ - 错误 C2106 : '=' : left operand must be l-value c++