提问者:小点点

如何利用迭代器和用户类正确地实现模板功能


我正在学习C++,并决定使用模板和迭代器。
但是当我开始尝试将我的代码用于类时,它停止工作了,因为我不能将我在模板函数中使用的::迭代器用于类。

#include <vector>

template <class Iterator>
struct Page {
    std::vector<Iterator> data;

    auto begin() const { return *data.begin(); }
    auto end() const { return *data.end(); }
};

template <typename Iterator>
struct My_struct {
    My_struct(Iterator begin, Iterator end) { /*...*/ }
    /*...*/
};

template <typename C>
My_struct<typename C::iterator> fun(C& c) {
    return { c.begin(), c.end() };
}

int main()
{
    Page<std::vector<int>::iterator> pag;   
    auto b = fun(pag);                      // 

    std::vector<std::vector<int>::iterator> vec;
    auto a = fun(vec);
}

错误E0304函数模板“fun”没有与参数列表25匹配的实例


共1个答案

匿名用户

my_struct是错误源,因为page没有iterator成员(page::iterator不存在)。

还有,这个

auto begin() const { return *data.begin(); }
auto end() const { return *data.end(); }

将导致分段错误,因为向量中没有元素,因此您不应该取消引用迭代器:

auto begin() const { return data.begin(); }
auto end() const { return data.end(); }

并且为了使有趣工作,您可以使用auto作为返回类型,以及模板参数推导:

template <typename C>
auto fun(C& c) {
//^^-- auto as return type
    return My_struct{ c.begin(), c.end() };
//         ^^^^^^^^^^---- template argument deduction
}

最后你会得到:

#include <vector>

template <class Iterator>
struct Page {
    std::vector<Iterator> data;

    auto begin() const { return data.begin(); }
    auto end() const { return data.end(); }
};

template <typename Iterator>
struct My_struct {
    My_struct(Iterator begin, Iterator end) { /*...*/ }
    /*...*/
};

template <typename C>
auto fun(C& c) {
    return My_struct{ c.begin(), c.end() };
}

int main()
{
    Page<std::vector<int>::iterator> pag;
    auto b = fun(pag);                      //

    std::vector<std::vector<int>::iterator> vec;
    auto a = fun(vec);
}

这应该能正常工作