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

时间:2021-12-07 21:00:55

I get the following compilation error:

我收到以下编译错误:

error: expected `;' before 'it'"

Here's my code:

这是我的代码:

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

template< class T >
void example() {
    std::list< boost::function<T ()> >::iterator it;
}

Why does this happen? How can I fix it?

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

1 个解决方案

#1


18  

You need to put typename in front of that line, since the type you do ::iterator upon is dependant on the template-parameter T. Like this:

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

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

Consider the line

考虑一下这条线

std::list< boost::function<T ()> >::iterator * it; 

which could mean a multiplication, or a pointer. That's why you need typename to make your intention clear. Without it, the compiler assumes not a type, and thus it requires an operator there or a semicolon syntactically.

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


Also consult the new C++ FAQ entry Where to put template and typename on dependent names.

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

#1


18  

You need to put typename in front of that line, since the type you do ::iterator upon is dependant on the template-parameter T. Like this:

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

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

Consider the line

考虑一下这条线

std::list< boost::function<T ()> >::iterator * it; 

which could mean a multiplication, or a pointer. That's why you need typename to make your intention clear. Without it, the compiler assumes not a type, and thus it requires an operator there or a semicolon syntactically.

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


Also consult the new C++ FAQ entry Where to put template and typename on dependent names.

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