简化我的问题我们可以考虑:
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/