gpt4 book ai didi

templates - C++11 中迭代器的类型别名/using 声明

转载 作者:行者123 更新时间:2023-12-02 14:40:13 25 4
gpt4 key购买 nike

我在使用我认为应该有效的 using 声明时遇到问题:

#include <iostream>
#include <vector>
using namespace std;

template<typename C, typename V>
vector<typename C::iterator> find_all1(C& c, V v)
{
vector<typename C::iterator> res;
for (auto p = c.begin(); p!=c.end(); ++p) {
if (*p == v)
res.push_back(p);
}
return res;
}

template<typename T>
using Iterator<T> = typename T::iterator;

template <typename C, typename V>
vector<Iterator<C>> find_all2(C& c, V v)
{
vector<Iterator<C>> res;
for (auto p = c.begin(); p != c.end(); ++p) {
if (*p == v)
res.push_back(p);
}
return res;
}

int main(int argc, const char *argv[])
{
return 0;
}

这基本上是 Stroustrup 书中的一个示例,它无法编译。第一部分 (find_all1) 可以,但尝试使用 using 声明的模板版本不会。

错误喷涌的主要部分如下所示:

$ make
c++ -g -fPIC -std=c++0x -stdlib=libc++ -c -o iter_tests2.o iter_tests2.cpp
iter_tests2.cpp:18:7: error: no template named 'Iterator'; did you mean 'iterator'?
using Iterator<T> = typename T::iterator;
^~~~~~~~
iterator
/usr/bin/../lib/c++/v1/iterator:415:25: note: 'iterator' declared here
struct _LIBCPP_TYPE_VIS iterator
^
iter_tests2.cpp:18:15: error: partial specialization of alias templates is not permitted
using Iterator<T> = typename T::iterator;
^~~

还有更多,但我认为重要的部分是关于 using 声明。

最佳答案

您的语法不正确,请删除 <T> :

template<typename T>
using Iterator = typename T::iterator;

关于templates - C++11 中迭代器的类型别名/using 声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21241933/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com