c++ - 无法将迭代器传递给 C++ 中的类方法

标签 c++ c++11

我有以下简单的类:

template <class T> class ListWrap
{
    std::list<T> m_List;
    explicit ListWrap(std::initializer_list<T> data)
    {
        Set(data);
    }
    void Set(std::initializer_list<T> data)
    {
        m_List.clear();
        m_List.insert(m_List.end(), data);
    }
};

这很好用,我可以使用初始化列表实例化一个新对象 ListWrap。现在我还想允许从另一个列表或迭代器设置 m_List,并从复制构造函数中使用它。

所以我尝试添加以下内容:

// copy constructor
explicit ListWrap(const ListWrap& Other)
{
    Set(Other.m_List.begin());
}
void Set(std::iterator<std::list<T>, T> Iterator)
{
    m_List.clear();
    m_List.insert(m_List.end(), Iterator);
}

但是,现在当我尝试编译时出现以下错误:

error C2664: cannot convert argument 1 from
   'std::_List_const_iterator<std::_List_val<std::_List_simple_types<int>>>'
to 'std::initializer_list<_Ty>'*

此错误消息是指在新的复制构造函数中调用 Set()。所以它似乎尝试将“旧”Set() 方法与初始化列表一起使用,而不是第二个"new"版本的 Set() 接收迭代器.

知道我在这里遗漏了什么吗?

最佳答案

// copy constructor
explicit ListWrap(const ListWrap& Other)
{
    Set(Other.m_List.begin());
}

Other是 const 引用,所以 Other.m_List.begin()是一个const 迭代器。

尝试 std::iterator<const std::list<T>&, T> , 或 std::list<T>::const_iterator , 对于 Set 的参数类型功能。

编辑:

这是一个 working code .

#include <iostream>
#include <list>

using namespace std;

template <class T> class ListWrap
{
public:
    std::list<T> m_List;
    explicit ListWrap(std::initializer_list<T> data)
    {
        Set(data);
    }
    // copy constructor
    explicit ListWrap(const ListWrap& Other)
    {
        Set(Other.m_List.begin(), Other.m_List.end());
    }

    void Set(std::initializer_list<T> data)
    {
        m_List.clear();
        m_List.insert(m_List.end(), data);
    }

    //typename std::list<T>::const_iterator also works as argument type
    void Set(decltype(m_List.cbegin()) beg, decltype(m_List.cbegin()) end)
    {
        m_List.clear();
        m_List.insert(m_List.end(), beg, end);
    }
};

int main() {
    ListWrap<int> l({1,2,3});
    ListWrap<int> l2(l);

    cout << l2.m_List.size() << endl;

    return 0;
}

显然 std::list::insert使用来自另一个列表但不是来自初始化列表的迭代器时需要有三个参数。不妨把const std::list<T>&作为 Set 的参数,然后做 m_List = arg如评论中所示。

关于c++ - 无法将迭代器传递给 C++ 中的类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40952668/

相关文章:

c++ - 嵌套异常和原始类型

c++ - 将 std::move 与 std::shared_ptr 一起使用

c++ - 如何递归使用typedef?

c++ - "MyClass a(anotherInstance);"比 "MyClass a = anotherInstance;"快吗?

c++ - 在 main.cpp 以外的文件中定义的结构的奇怪之处

c++ - 非类型模板参数可以在 STL 容器上完成吗?

c++ - "True Polymorphism"的例子? (最好使用 Haskell)

c++ - 在 union 中构建结构

c++ - 为什么不允许在 const 非 volatile 成员函数上消除公共(public)子表达式?

c++ - 使用enable_if在按值传递与按引用传递之间更改函数声明