C ++需要typename [duplicate]的函数指针向量

  可能重复:   正式,什么是typename?   我必须在哪里以及为什么要放“模板”?和“typename”在依赖名称? 编辑:对不起,我搜索但没有看到这个副本:官方,什么是typename? 大家好。我正在用C ++编写一个简单的事件处理程序类,过去一小时我一直在敲我的桌子试图弄清楚为什么下面的代码会给我以下错误:
typedef int (*fptr)(Data); // Data is a template class (this is from within a generic class)
// listeners is of type vector<fptr>, and this function is a member function of class Event
Event& add(fptr func) {
    for (std::vector<fptr>::iterator iter = listeners.begin(); iter != listeners.end(); ++iter) {
        if (*iter == func)
            return *this;
    }
    listeners.push_back(func);
    return *this;
}

g++ -Wall  -g     -c /root/learncpp/EventHandler/main.cpp -o obj/Debug/main.o
In file included from /root/learncpp/EventHandler/main.cpp:3:
/root/learncpp/EventHandler/event.h: In member function 'Event<Data>& Event<Data>::add(int (*)(Data))':
/root/learncpp/EventHandler/event.h:11: error: expected ';' before 'iter'
/root/learncpp/EventHandler/event.h:11: error: 'iter' was not declared in this scope
/root/learncpp/EventHandler/event.h: In member function 'Event<Data>& Event<Data>::add(int (*)(Data)) [with Data = std::basic_string<char, std::char_traits<char>, std::allocator<char> >]':
/root/learncpp/EventHandler/main.cpp:18:   instantiated from here
/root/learncpp/EventHandler/event.h:11: error: dependent-name 'std::vector::iterator' is parsed as a non-type, but instantiation yields a type
/root/learncpp/EventHandler/event.h:11: note: say 'typename std::vector::iterator' if a type is meant
Process terminated with status 1 (0 minutes, 2 seconds)
3 errors, 0 warnings
我已经弄明白了这个问题;我不得不改变(使用上面的代码)第3行
for (typename std::vector<fptr>::iterator iter = listeners.begin(); iter != listeners.end(); ++iter) {
它解决了这个问题,而且运作得很好。 我的问题是,为什么需要
typename
关键字?它做了什么,目的是什么?为什么我不能省略它? 我问所有这些问题,因为我正在编写的事件处理程序是一个非常简单的用于我正在编写的教程中,并且无法解释它会很奇怪。另外我想知道,只是要知道:p 附: - 我刚刚在我的C ++书中读到
typename
关键字告诉编译器确保它知道该类型被视为模板类型而不是对象类型。为什么需要这个,为什么编译器不能自己解决这个问题呢? (有点明显不是吗?) PPS - 我的书提供了关于typename关键字的非常少的信息,除了它告诉编译器使用的关键字是模板名称而不是对象名称,尽管它是一本参考书(Herbet Schildt的完整C ++参考:第四版) )     
已邀请:

要回复问题请先登录注册