I have a function where I need a data type using an iterator as the return type, for example:
#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; }
In main (), I have to explicitly specify the data type 'int' or 'char' of the get_odd function, is there a way to find out the data type underlying the iterator and let the template automatically subtract the correct data type?
dguan source share