【发布时间】:2014-10-15 07:08:28
【问题描述】:
我有一个函数,我需要一个迭代器的底层数据类型作为返回类型,如下所示:
#include <iostream>
#include <vector>
#include <iterator>
template<class T, class ForwardIterator>
std::vector<T> get_odd(ForwardIterator data_begin, ForwardIterator data_end)
{
std::vector<T> ret;
std::copy_if(data_begin, data_end, std::back_inserter(ret), [](int x) { return x % 2; });
return ret;
}
int main()
{
std::vector<int> vi { 1, 2, 3, 4, 5 };
for (auto i : get_odd<int>(vi.begin(), vi.end()))
std::cout << i << ", ";
std::cout << std::endl;
std::vector<unsigned int> vui{ 9UL, 8UL, 7UL, 6UL, 5UL };
// Note the 'char' I provided to the function, this will print weird chars
for (auto i : get_odd<char>(vui.begin(), vui.end()))
std::cout << i << ", ";
std::cout << std::endl;
return 0;
}
在main()中,我要显式提供数据类型'int'或'char'给get_odd函数,有没有办法找出迭代器的底层数据类型,让模板自动扣除正确的数据类型?
【问题讨论】:
-
仅供参考,
get_odd不需要前向迭代器,输入迭代器就可以了。
标签: c++ templates c++11 iterator