The code I see,
makes sense to me,
but GCC…
it disagrees.
以下代码按预期编译和运行,但如果取消注释#define,则会出现错误,我不明白.符号迭代器仍然只有一个可以引用的东西:超类中的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")); }
海湾合作委员会的错误:
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)
解决方法
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