为什么我不能在std :: list中存储boost :: function?

Nay*_*den 5 c++ boost list

我收到以下编译错误:

error: expected `;' before 'it'"
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

#include <boost/function.hpp>
#include <list>

template< class T >
void example() {
    std::list< boost::function<T ()> >::iterator it;
}
Run Code Online (Sandbox Code Playgroud)

为什么会这样?我该如何解决?

Joh*_*itb 18

您需要放在typename该行的前面,因为您执行:: iterator的类型取决于模板参数T.像这样:

template< class T >
void example() {
    typename std::list< boost::function<T ()> >::iterator it;
}
Run Code Online (Sandbox Code Playgroud)

考虑一下这条线

std::list< boost::function<T ()> >::iterator * it; 
Run Code Online (Sandbox Code Playgroud)

这可能意味着乘法或指针.这就是为什么你需要typename明确你的意图.没有它,编译器假定不是一个类型,因此它需要一个运算符或语法分号.


另请参阅新的C++ FAQ条目将依赖名称上的模板和typename放在何处.