hel*_*922 6 c++ templates iterator stl
我正在尝试实现一个允许用户输入某种类型的开始和结束迭代器的函数,然后所有函数都对数据执行一些操作.然而,该功能必须足够通用的,应该对很多类型的迭代工作(例如std::vector::iterator,std::string::iterator,std::iterator等).唯一的限制是迭代器必须至少是forward_iterator_tag功能.
我的函数原型看起来像这样:
template <class key_type, class data_type> std::shared_ptr<data_type>
remove(std::iterator<std::forward_iterator_tag, key_type> key_start,
std::iterator<std::forward_iterator_tag, key_type> key_end);
Run Code Online (Sandbox Code Playgroud)
但是,这限制了我特别使用forward_iterator_tag迭代器,因此尝试调用这样的函数:
remove<char, char>(std::iterator<std::random_access_iterator_tag, char>(), std::iterator<std::random_access_iterator_tag, char());
Run Code Online (Sandbox Code Playgroud)
将失败,因为编译器无法将a转换std::iterator<std::random_access_iterator_tag,...>为a std::iterator<std::forward_access_iterator_tag,...>.此外,此方法不适用于字符串迭代器,矢量迭代器或其他stl迭代器.
有人知道stl如何实现容器/字符串以接受彼此的迭代器吗?例如,这正确编译:
std::string a = "hello";
std::vector<char> v(a.begin(), a.end());
Run Code Online (Sandbox Code Playgroud)
Edw*_*nge 13
template < typename Iter >
void fun_impl(Iter begin, Iter end, std::forward_iterator_tag)
{
// do your stuff here...
}
template < typename Iter >
void fun(Iter begin, Iter end)
{
fun_impl(begin,end, std::iterator_traits<Iter>::iterator_category());
}
Run Code Online (Sandbox Code Playgroud)
返回的类型begin()和end()关于各种容器不是类型的iterator<category...>但亚类(有时).在编写通用代码时,您永远不会以特定的迭代器类型为目标.相反,您使用"标记调度"来对迭代器进行分类并调用正确的实现.由于random_iterator_tag是一个forward_iterator_tag,它将自动转换为这样,以便上述fun_impl任何forward_iterator或扩展名都能正确解析.
| 归档时间: |
|
| 查看次数: |
830 次 |
| 最近记录: |