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
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<class C, size_t S>
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<class C, size_t S>
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.
I've encountered the same situation while using tuples:
template<typename Tuple>
auto f(Tuple&& tuple)
-> /* ??? */
{
using std::get;
return get<Idx>(tuple);
}
which accepts both std::tuple
and boost::tuple
, and accepts both lvalues and rvalues as opposed to template<typename... Types> auto f(std::tuple<Types...>& tuple) -> /* ??? */
.
This particular case was solved with a traits class, which is in fact provided by the Standard: std::tuple_element
. As usual with traits classes, the idea is that tuple
is a protocol and anything that want to conform to it will provide a specialization for e.g. tuple_element
. So in my case the solution already existed.
In your case, if you were writing a library, I'd recommend writing (and documenting) such a traits class. In application code or other situations, I'm not so sure.