ARRAY_SIZE 
Author Message
 ARRAY_SIZE

Hi,
Is it safe to replace this macros
    #define ARRAY_SIZE(arr)    (sizeof(arr)/sizeof(arr[0]))

with this template
    template<class ARR> int ARRAY_SIZE(const ARR &arr)    {return
sizeof(arr)/sizeof(arr[0]);}
?

With VC 6.0 the answer is yes, what about other compilers and standard?



Mon, 17 May 2004 04:59:13 GMT  
 ARRAY_SIZE

Quote:
> Hi,
> Is it safe to replace this macros
>     #define ARRAY_SIZE(arr)    (sizeof(arr)/sizeof(arr[0]))

> with this template
>     template<class ARR> int ARRAY_SIZE(const ARR &arr)    {return
> sizeof(arr)/sizeof(arr[0]);}
> ?

> With VC 6.0 the answer is yes, what about other compilers and standard?

I think this is an excellent question, however, shouldn't you have posted it
to comp.lang.c++?


Mon, 17 May 2004 05:51:30 GMT  
 ARRAY_SIZE

Quote:

> > With VC 6.0 the answer is yes, what about other compilers and standard?

> I think this is an excellent question, however, shouldn't you have posted
it
> to comp.lang.c++?

The problem is that news.microsoft.com doesn't have this group :(,
I had to chouse from vc.atl, vc.mfc, vc.stl, vc.language, xbox.halo,...


Mon, 17 May 2004 06:14:49 GMT  
 ARRAY_SIZE

Quote:

> > > With VC 6.0 the answer is yes, what about other compilers and
standard?

> > I think this is an excellent question, however, shouldn't you have
posted
> it
> > to comp.lang.c++?
> The problem is that news.microsoft.com doesn't have this group :(,
> I had to chouse from vc.atl, vc.mfc, vc.stl, vc.language, xbox.halo,...

How about:

http://groups.google.com/groups?hl=en&group=comp.lang.c%2B%2B



Mon, 17 May 2004 07:07:14 GMT  
 ARRAY_SIZE

Quote:

> Hi,
> Is it safe to replace this macros
>     #define ARRAY_SIZE(arr)    (sizeof(arr)/sizeof(arr[0]))

> with this template
>     template<class ARR> int ARRAY_SIZE(const ARR &arr)    {return
> sizeof(arr)/sizeof(arr[0]);}
> ?

> With VC 6.0 the answer is yes, what about other compilers and standard?

www.comeaucomputing.com has an extremely standard online compiler for
checking the compliance of code (add the -tused switch),

Now ARRAY_SIZE might work, but it also compiles for pointers and
objects with operator[] defined, which is an undesirable source of
errors.

Anyway, ARRAY_SIZE has been done before in this version that only
compiles for arrays:

template<class T, std::size_t N>
inline std::size_t ARRAY_SIZE(T (&)[N])
{
   return N;

Quote:
}

template<class T, std::size_t N>
inline std::size_t ARRAY_SIZE(T const(&)[N])
{
   return N;

Quote:
}

I'm not sure whether MSVC6 compiles this though.

An even better solution is to use Boost's array_traits.hpp from
www.boost.org.

Tom



Tue, 18 May 2004 01:10:08 GMT  
 
 [ 5 post ] 

 Relevant Pages 

1. Safe ARRAY_SIZE macro

 

 
Powered by phpBB® Forum Software