2014-09-06 108 views
1

我想获得一个迭代器到我的向量shared_ptr。它给我2编译错误:共享指针的向量迭代器

syntax error : missing ';' before identifier 'begin' 
missing type specifier - int assumed. Note: C++ does not support default-int 

在代码中,如果我用字符串或基本的东西替换矢量的条目类型,它编译。 [当然那不是我想要的]。这是怎么回事?

#include <vector> 
#include <unordered_map> 
#include <memory> 

template<class _Kty, class _Ty> class MyClass { 
public: 
    typedef std::shared_ptr<std::pair<_Kty, _Ty>> Entry; 

    // Vector containing pairs of the key & value 
    std::vector<Entry> container; 

    // Beginning iterator to the vector part 
    std::vector<Entry>::iterator begin() noexcept { 
     return containervector.begin(); 
    } 
}; 

回答

2

std::vector<Entry>::iterator依赖名。

使用typename为关于编译器一个暗示,嵌套::iterator东西

typename std::vector<Entry>::iterator begin() noexcept { 
// ^^^^^^^^ 

Q & A节:

为什么typedef std::string Entry;作品没有typename

std::string是一个模板std::basic_string<char>的显式实例,因此,编译器知道这个类型及其嵌套成员类的一切。

为什么我需要typenameshared_ptr版本的代码?

这是因为std::vector<Entry>后面隐藏的内容取决于提供给模板的参数。也就是说,std::vector<Entry>::iterator将根据什么Entry是变化,并且Entry本身利用模板参数(因为它具有std::pair<_Kty, _Ty>),并且iterator构件可以不存在可言,或者它可以是例如一个静态对象,而不是一个类型。 typename是编译器的提示。

+0

工作!但我有另一个问题。我将typedef行改为:typedef std :: string Entry;它编译。为什么我需要shared_ptr版本的代码的类型名称? [&不是字符串版本] – RandomClown 2014-09-06 21:08:34

+1

@RandomClown:已更新 – 2014-09-06 21:18:00