I am trying to write a template function similar to std::to_string
that works for basic types as well as iterators of STL containers. But I am not sure how to write the templates specific enough to identify just the iterators.
What I tried so far is to try to use the iterator
typedef in STL containers
template<typename... Args, template <typename...> class Container>
static string to_string(typename Container<Args...>::iterator s) { ...
A minimal example is attached below. The code compiles but the template function My::to_string
fails to match the above signature, and treated std::set<int>::iterator
as a default type.
My question is how to write this correctly in a generic manner, so that the template function My::to_string
can pickup iterators, but do not confuse iterators with other standard template types like std::string
.
Thanks in advance.
#include <set>
#include <iostream>
using namespace std;
class My{
//base case
template<typename T>
static string to_string(const T& t) {
return "basic ";
}
//specialization for string
template <typename Char, typename Traits, typename Alloc>
static string to_string(const std::basic_string<Char, Traits, Alloc>& s) {
return (string)s;
}
//Problem line: how to write specialization for iterators of standard containers?
template<typename... Args, template <typename...> class Container>
static string to_string(typename Container<Args...>::iterator s) {
return "itor ";
}
};
int main() {
int i = 2;
string str = "Hello";
set<int> s;
s.insert(i);
cout << to_string(i) << ", " << str << ", "
<< to_string(s.begin()) << endl; //didn't get captured by iterator spec.
}
Output:
basic, Hello, basic
Desired output:
basic, Hello, itor