这个'缺少模板参数'C++错误的含义是什么?

Rob*_*b N 7 c++ templates

啊,C++模板......

我看到的代码对我
来说很有意义,
但GCC ......
它不同意.

以下代码按预期编译和运行,但如果取消注释#define,则会出现错误,我不明白.符号iterator仍然只有一个可以引用的东西:超类中的typedef.所以我想我有两个问题:1.错误是什么意思?2.修复它们的最佳方法是什么.

#include <map>
#include <string>
#include <cstdio>

using namespace std;

// #define WITH_TEMPLATE 1

#ifdef WITH_TEMPLATE
template <class C>
struct MyClass : public map<string, C>
#else
struct MyClass : public map<string, int>
#endif
{
    bool haskey(const string &s)
    {
        iterator it = find(s);
        return (it != end());
    }
};

int main()
{
#ifdef WITH_TEMPLATE
    MyClass<int> m;
#else
    MyClass m;
#endif
    m["test"] = 10;    
    printf("%d %d\n", m.haskey("test"), m.haskey("no"));
}
Run Code Online (Sandbox Code Playgroud)

海湾合作委员会的错误:

temp.cc:在成员函数'bool MyClass :: haskey(const std :: string&)':
temp.cc:18:error:在'
it'temp.cc:18:error:expected`;' 之前缺少模板参数 在'
it'temp.cc:19 之前:错误:'它'未在此范围内声明
temp.cc:19:错误:'end'没有依赖于模板参数的参数,因此声明'end '必须可用
temp.cc:19:错误:(如果使用'-fpermissive',G ++将接受您的代码,但不允许使用未声明的名称)

asc*_*ciz 4

您还需要更改 MyClass::haskey 方法。

bool haskey(const string &s)
{
    typename MyClass<C>::iterator it = this->find(s);
    return (it != this->end());
}
Run Code Online (Sandbox Code Playgroud)

这种行为的解释位于http://physicals.ucsd.edu/students/courses/winter2008/physicals141/manuals/rhel-gcc-en-4/上的“名称查找、模板和访问基类成员”部分。 c---misunderstandings.html(来自另一个答案的评论的链接,以防万一)。

整个固定示例代码:http://ideone.com/G7Rty