Boost logo

Boost :

From: David Abrahams (abrahams_at_[hidden])
Date: 2000-09-30 07:49:06


----- Original Message -----
From: "John Maddock" <John_Maddock_at_[hidden]>

> Unfortunately, is_pointer is the only type-traits template I've been able
> to get working more or less correctly with this technique. Attempting to
> use the same technique with is_array, is_member_pointer, is_same, and
> is_reference all fail: either because the language doesn't allow it, or
> more often, internal compiler errors, or downright incorrect function
> overload resolution.
>
> If there are any cunning artificers out there that can extend this to any
> of the templates mentioned (especially is_reference), I would be very
happy
> to hear about it!

If you have some way of determining whether an expression is a compile-time
constant, I can help. Of course, it treads into "undefined behavior"
territory, but:

template <class T>
struct Holder {
   T x;
   Holder();
};

is_reference<T> :=
is_compile_time_constant<(std::size_t)&((Holder<T>*)0)->x>

Probably not much help, though :(

The following sequence of posts should get you is_array, though:

>
> On 24 Aug 2000 10:08:33 -0400, john_torjo_at_[hidden] wrote:
>
> >In article <=gmkOTzE9Q4=0uOJAM=1SoYQiIAV_at_[hidden]>,
> > Jonathan Lundquist <jhl_at_[hidden]> wrote:
> >>
> >> // Determine the number of elements in an array.
> >> #define countof(a) \
> >> (sizeof(countof_validate(a, &(a))) ? sizeof(a) / sizeof((a)[0]) : 0)
> >>
> >> template<typename T>
> >> void countof_validate(T* const, T* const*)
> >> {
> >> }
> >>
> >> template<typename T>
> >> int countof_validate(const void*, T)
> >> {
> >> }
> >>
> >
> >Thanks. It works.
> >But I don't understand how.
> >Why do you need two templated functions?
> >When can you return 0?
>
> int main()
> {
> char a[10];
> char* b = a;
> int i = countof(a);
> int j = countof(b); // compile time error, illegal sizeof operand
> return 0;
> }
>
> When invoked with a pointer instead of a true array, the template
> returning void will be resolved, which will fail the compile.
>
> When invoked with an array, the template returning int will be
> resolved, so sizeof(a) / sizeof((a)[0]) will be evaluated.
>
> The '0' term of the expression will never be returned, but is there to
> complete the syntax of the ?: expression.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk