【问题标题】:c++ compilation errorc++编译错误
【发布时间】:2009-06-26 05:32:27
【问题描述】:

以下代码在 Visual Studio 2009 中出现编译错误。

#include <iterator>
#include <vector>

template <class T1, class T2 >
class A
{
public:

    typename std::vector<std::pair<T1,T2> >::iterator iterator;
    std::pair<iterator, bool > foo(const std::pair<T1 ,T2> &value_in);
};

任何人都可以解释一下吗?这是错误。

error C2327: 'A<T1,T2>::iterator' : is not a type name, static, or enumerator

【问题讨论】:

    标签: c++ visual-studio templates


    【解决方案1】:

    这将iterator 声明为变量(不是类型):

    typename std::vector<std::pair<T1,T2> >::iterator iterator;
    

    你是这个意思吗?

    typedef typename std::vector<std::pair<T1,T2> >::iterator iterator;
    

    更多信息:如果您对typename 的作用感到好奇,请阅读dependent 和非依赖名称之间的区别。如果您的类型与特定容器密切相关,则该容器的 typedef 可能很有用,因为 STL 模式使用许多嵌套的 typedef,您可以轻松访问(下面的V::value_type)。这具有额外的优势,即随着代码的发展需要更少的更改,例如使用不同的分配器(向量的第二个模板参数),只需要一次编辑。

    template<class T1, class T2>
    struct A {
    private:
      // you may or may not want to expose these convenience types
      typedef std::pair<T1, T2> P;
      typedef std::vector<P> V;
    
    public:
      typedef typename V::value_type value_type;
      typedef typename V::iterator iterator;
      std::pair<iterator, bool> foo(value_type const& value_in);
    };
    

    【讨论】:

      【解决方案2】:

      你需要 typedef,而不是 typename

      【讨论】:

        猜你喜欢
        • 2015-12-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-01
        • 2011-05-16
        相关资源
        最近更新 更多