【问题标题】:Why can't I call a template base class constructor with a const_iterator? [duplicate]为什么我不能用 const_iterator 调用模板基类构造函数? [复制]
【发布时间】:2014-07-20 17:55:41
【问题描述】:

由于某种原因,以下代码给出了错误Symbol 'TemplateBase' could not be resolved.

template <typename T>
class TemplateBase
{
    TemplateBase(std::map<std::string, T>::const_iterator anIterator)
    { }
};

class SubClass : public TemplateBase<int>
{
    SubClass(std::map<std::string, int>::const_iterator anIterator) :
        TemplateBase<int>(anIterator) //Error: Symbol 'TemplateBase' could not be resolved.
    { }
};

奇怪的是,当我删除 ::const_iterator 并且只剩下 std::map&lt;std::string, int&gt; 时没有出现错误:

template <typename T>
class TemplateBase
{
    TemplateBase(std::map<std::string, T> aMap)
    { }
};

class SubClass : public TemplateBase<int>
{
    SubClass(std::map<std::string, int> aMap) :
        TemplateBase<int>(aMap) //No error.
    { }
};

另外,下面的函数也没有报错,所以它看起来确实与模板基类调用与 const_iterator 的组合有关:

void function()
{
    std::map<std::string, int>::const_iterator anIterator;
    TemplateBase<int> aTemplateBase(anIterator); //No error
}

是否有一些规则反对使用 const_iterator 作为我不知道的基类模板构造函数的参数?或者这是一个编译器错误?

我正在使用 C++11 在 Windows 7 上使用 MinGW 64bit 4.9.0 进行编译。

【问题讨论】:

  • 你错过了typename
  • “一个错误”?哪一个?
  • @Igvidal:“错误:无法解析符号'TemplateBase'。”,它在代码片段的注释中。我现在也将它添加到正文中。
  • @ildjarn:将 替换为 时问题仍然存在。此外,在我的实际代码中,我使用了一个类。我已经编辑了问题的代码。
  • @Aberrant :不仅可能,而且是必需的! ;-D

标签: c++ templates inheritance c++11 const-iterator


【解决方案1】:

当您使用依赖于模板类型的嵌套类型时,您需要使用typename 关键字:

TemplateBase(typename std::map<std::string, T>::const_iterator anIterator)
{ }

【讨论】:

  • 呵呵,没想到把typename这个词放在那里也是合法的。这为我修好了,谢谢。但是为什么std::map&lt;std::string, T&gt;::const_iterator 需要这个而不是std::map&lt;std::string, T&gt;
  • @Aberrant 因为在第二种情况下您不是指嵌套类型。另外,您是否觉得this 与您的问题重复?我的近距离投票具有约束力,因此我想在此之前与您确认。
  • @Praetorian 我想可能是这样。我在那里找不到这个特定的语法(ClassName(typename someComplexlyDerivedNestedIdontevenType)),但从关键字的解释范围来看,它可能在某种程度上就在那里。我会确保通读全文。所以,是的,我想结束这个问题很好。
  • 解释一下,没有typename 关键字,编译器无法判断const_iterator 是类型名还是变量名。在此之后,您可以编写 std::map 的模板特化来更改该细节。
  • @Aberrant :有关typename的更多信息,请参阅此常见问题解答:What is the template typename keyword used for?
猜你喜欢
  • 1970-01-01
  • 2012-02-28
  • 2013-12-04
  • 2017-12-21
  • 2021-04-20
  • 1970-01-01
  • 1970-01-01
  • 2022-01-27
  • 2021-02-18
相关资源
最近更新 更多