I have a function where I have a container which holds strings (eg vector<string>, set<string>, list<string>) and, given a start iterator and an end iterator, go through the iterator range processing the strings.
Currently the function is declared like this:
template< typename ContainerIter>
void ProcessStrings(ContainerIter begin, ContainerIter end);
Now this will accept any type which conforms to the implicit interface of implementing operator*, prefix operator++ and whatever other calls are in the function body.
What I really want to do is have a definition like the one below which explicitly restricts the amount of input (pseudocode warning):
template< typename Container<string>::iterator>
void ProcessStrings(Container<string>::iterator begin, Container<string>::iterator end);
so that I can use it as such:
vector<string> str_vec;
list<string> str_list;
set<SomeOtherClass> so_set;
ProcessStrings(str_vec.begin(), str_vec.end()); // OK
ProcessStrings(str_list.begin(), str_list.end()); //OK
ProcessStrings(so_set.begin(), so_set.end()); // Error
Essentially, what I am trying to do is restrict the function specification to make it obvious to a user of the function what it accepts and if the code fails to compile they get a message that they are using the wrong parameter types rather than something in the function body that XXX function could not be found for XXX class.
You can get close to this with a template template parameter:
This will process a whole container, and give a compile error if it doesn’t contain strings.
If you want to work with iterator ranges, then the best I could manager is
Unfortunately, type inference won’t work on the function arguments, so you’ll have to explicitly give the template parameter:
Can anyone improve on this?