i wanna know what's wrong with following code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
namespace my{
    template <typename Itr>
    void sort(Itr,Itr);
    template <typename Ran>
    void sort_helper(Ran beg, Ran end, std::random_access_iterator_tag) {
        std::sort(beg, end, std::less<decltype(*beg)>());
    }
    template <typename For>
    void sort_helper(For beg, For end, std::forward_iterator_tag) {
        std::vector<decltype(*beg)> v{beg, end};
        sort(v.begin(), v.end());
        std::copy(v.begin(), v.end(), beg);
    }
    template <typename Itr>
    void sort(Itr beg, Itr end) {
        sort_helper(beg, end, std::iterator_traits<Itr>
                    ::iterator_category());
    }
}
int main(){
    std::forward_list<int> fl;
    std::default_random_engine e;
    std::uniform_int_distribution<> d(0, 100);
    for(int i = 0; i < 10; ++i){
        fl.push_front(d(e));
    }
    my::sort(fl.begin(), fl.end());
    for (auto item: fl) {
        std::cout << item << " ";
    }
    std::cout << std::endl;
}

the compiler reports an error at line 17:unexpected type name "iterator_category": expected expression.
I omits all header for simplicity
who can help me? please!thanks.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
namespace my{
    template <typename Itr>
    void sort(Itr,Itr);
    template <typename Ran>
    void sort_helper(Ran beg, Ran end, std::random_access_iterator_tag) {
        std::sort(beg, end, std::less<decltype(*beg)>());
    }
    template <typename For>
    void sort_helper(For beg, For end, std::forward_iterator_tag) {

        // **** can't have vector of references
        std::vector< typename std::iterator_traits<For>::value_type > v{beg, end};
        // or: std::vector< typename std::remove_reference< decltype(*beg) >::type > v{beg, end};

        std::sort(v.begin(), v.end());  // **** qualify with std:: (unqualified name won't do here)
        std::copy(v.begin(), v.end(), beg);
    }
    
    template <typename Itr>
    void sort(Itr beg, Itr end) {
        // **** typename: dependant names must be disambiguated
        sort_helper(beg, end, typename std::iterator_traits<Itr> 
                    ::iterator_category());
    }
}
Last edited on
Topic archived. No new replies allowed.