catching template errors

Now I have made a template to slurp a file into an STL list container
perl style


1
2
3
4
5
6
7
8
9
template <typename T>
void slurp(T & v, std::istream & in)
{
    std::string s;
    while (in >> s) {

        v.push_back(s);
    }
}

which works beautifully for deque and vector and list:

1
2
3
4

    vector<string> v;
    slurp(v, cin);


Now obviously this won't work for, say, a map, which makes sense.
but when you erroneously pass a map you get a long compiler error trace.

NOW is there a way to catch this?
i.e. if there isn't a push_back member I can give a nice error message rather
than a scary long list of compiler errors?

(I am bound to forget what this template does in the future of course)
You can specialize the template to work only with vector, list and deque or you can change it to something like this:
1
2
3
4
5
6
7
8
template <typename T>
void slurp( deque<T> &v, std::istream & in)
{
    T s;
    while (in >> s) {
        v.push_back(s);
    }
}
And overload it also for vector and list
yes, that would work but it's not generic enough.
if there was a later container that had a correct interface (i.e. a push_back())
I would have to add it manually.
1
2
3
4
5
6
7
8
template <typename T>
void slurp(T & v, std::istream & in)
{
    T::value_type s;
    while (in >> s) {
        v.insert(v.back(), s);
    }
}


This will work on any STL containers. Note: std::map and std::multimap needs completely different care, as it is has key-value pairs, not just values. You can make the exact same code to work with std::map<K, V> and std::multimap<K, V> by overloading std::istream& operator>>(std::istream&, std::pair<K,V>&);

Hope this helps.

EDIT : see corrected code in my next post
Last edited on
no that doesn't even compile for me.

T is-a vector<string>
sry, my bad

Correct code

1
2
3
4
5
6
7
8
template <typename T>
void slurp(T & v, std::istream & in)
{
    typename T::value_type s;
    while (in >> s) {
        v.insert(v.end(), s);
    }
}
much better, but still doesn't solve the problem.
catch wrong containers neatly with a nice error message like:
"oops cannot use a map here" rather than the usual compiler errors.

I tried to use template meta programming and iterator traits but my head exploded!

maybe it cannee be done

Last edited on
I don't think you can do it automatically. But there are softwares for this purpose :
For example http://www.bdsoft.com/tools/stlfilt.html
Last edited on
This may interest you: http://www.generic-programming.org/languages/conceptcpp/
Unluckily looks as concepts will not be included in C++0x
Topic archived. No new replies allowed.