Beginning generically, plus decltype considering local using-declaration

后端 未结 2 1512
猫巷女王i
猫巷女王i 2021-02-08 08:23

C++0x\'s ranged-for loop has a special exception to handle arrays (FDIS §6.5.4), and there are two functions, std::begin and end, which are overloaded to handle arrays or to sel

2条回答
  •  死守一世寂寞
    2021-02-08 09:04

    You can special-case the arrays yourself. The type of an array is (and has to be for begin/end to work) ElementType (&)[Size], so if you overload the function like:

    template
    void f(C (&c)[S]) {
      do_something_with(std::begin(c), std::end(c));
    }
    

    it should behave specially like the for-loop.

    On a side-note, you don't need std::begin and std::end then, they are trivial:

    template
    void f(C (&c)[S]) {
      do_something_with(c, c + S);
    }
    

    (may need a cast; I actually only used it with things that demanded pointers, not any iterators).

    On another side-note, begin and end functions taking pointers are rather silly thing to do. If the pointed object is a collection, they should probably be taking reference instead.

提交回复
热议问题