[cfe-commits] [PATCH] [libcxx] avoid hardcoding buffer lengths
Marshall Clow
mclow.lists at gmail.com
Wed Dec 26 17:10:40 PST 2012
On Dec 26, 2012, at 4:11 PM, Saleem Abdulrasool <compnerd at compnerd.org> wrote:
> Hi Bigcheese, chandlerc,
>
> Introduce a new countof template "macro" to determine the count of elements in
> a statically allocated array. Use this to remove the various static hardcoded
> values for array element counts (strftime_l takes number of characters to write,
> not the size of the buffer, though they are equivalent with char).
>
> Provide an overload which takes two pointers (iterators) and returns the count
> of elements that would fit in the array bounded by the iterators. Do this to
> avoid having to add a pointless static assertion along the lines of:
>
> static_assert(is_same<decltype(__ib),
> typename remove_reference<decltype(__ie)>::type>::value,
> "iterator type mismatch");
>
> to ensure that the iterator types match when performing the calculation using
> sizeof on either of the iterators to determine the size of a single element:
>
> (__ie - __ib) / sizeof(*__ib)
You should definitely include Howard Hinnant on this - since he's the primary author of libc++.
Also, I think your second routine is incorrect:
> template <typename T>
> _LIBCPP_ALWAYS_INLINE size_t countof(const T * const begin, const T * const end)
> {
> return (end - begin) / sizeof(T);
> }
Consider calling it with ( ptr, prt + 1 )
It should return 1 in all cases - no matter what the type of "ptr" is.
But your code does not; it will return '0' for every type _except_ for ones where sizeof(T) == 1
char *cp;
int *ip;
std::cout << "Char " << countof ( cp, cp + 1 ) << std::endl;
std::cout << "Int " << countof ( ip, ip + 1 ) << std::endl;
prints:
Char 1
Int 0
-- Marshall
Marshall Clow Idio Software <mailto:mclow.lists at gmail.com>
A.D. 1517: Martin Luther nails his 95 Theses to the church door and is promptly moderated down to (-1, Flamebait).
-- Yu Suzuki
More information about the cfe-commits
mailing list