gpt4 book ai didi

c++ - 这个 'missing template arguments' C++ 错误是什么意思

转载 作者:可可西里 更新时间:2023-11-01 18:34:56 28 4
gpt4 key购买 nike

啊,C++ 模板...

The code I see,
makes sense to me,
but GCC...
it disagrees.

以下代码按预期编译和运行,但如果您取消注释 #define,则会出现我不理解的错误。符号 iterator 仍然只有一件事可以引用:父类(super class)中的 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"));
}

来自 GCC 的错误:

temp.cc: In member function ‘bool MyClass::haskey(const std::string&)’:
temp.cc:18: error: missing template arguments before ‘it’
temp.cc:18: error: expected `;' before ‘it’
temp.cc:19: error: ‘it’ was not declared in this scope
temp.cc:19: error: there are no arguments to ‘end’ that depend on a template parameter, so a declaration of ‘end’ must be available
temp.cc:19: error: (if you use ‘-fpermissive’, G++ will accept your code, but allowing the use of an undeclared name is deprecated)

最佳答案

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

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

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

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

关于c++ - 这个 'missing template arguments' C++ 错误是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4890487/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com