Monday, May 26, 2008

Template Type Arguments

To gain code locality I often use local types. I really like this feature as it allows me to define a type a the location where it is needed.

A frequent use for this would be compare or ordering functors for standard algorithms like sort or standard containers like hash_maps. This look's like this:
void foo(const std::vector<Bar> bars)
    struct Sort {
        bool operator()(const Bar& lhs, const Bar& rhs) const 
        { /* ... */ }
    std::sort(bars.begin(), bars.end(), Sort());
Other languages have code blocks or other features which allow you to write the sort criteria straight away. Local types are an tolerable alternative to this in my eyes. Ähm, I mean, they could have been. But the standard prevents this. Section says:
A local type, a type with no linkage, an unnamed type or a type compounded from any of these types shall not be used as a template-argument for a template type-parameter.
Oh my noodles. Why? Does anybody know a good reason for this? I can't imagine any. Furthermore I wonder how the syntax would look like when using an unamed type as a template parameter.

To make the confusion complete the GNU C++ compiler (version 4.2.3) dumps the following error when compiling the above example.
error: no matching function for call to 'sort(__gnu_cxx::__normal_iterator<Bar*, std::vector<Bar, std::allocator<Bar> > >, __gnu_cxx::__normal_iterator<Bar*, std::vector<Bar, std::allocator<Bar> > >, foo(std::vector<Bar, std::allocator<Bar> >&)::Sort&)'
Yeah, right.

No comments:

Post a Comment