Boost logo

Boost :

From: Giovanni Piero Deretta (gpderetta_at_[hidden])
Date: 2008-04-12 07:45:18


On Sat, Apr 12, 2008 at 9:28 AM, Eric Niebler <eric_at_[hidden]> wrote:
> I recently had a C++ problem and found an answer that tickled my brain.
> In the spirit of Car Talk on NPR, I thought I'd share it in the form of
> a puzzler.
>
> Say that you are given a set of types, and you must find the "common"
> type, where common is defined as follows:
>
> - If all the types are the same, say X, then the common type is X
> - If some types are X and some are Default (where Default is a known
> special type), the common type is X
> - If some types are X and some are Y (and neither X nor Y is Default),
> then there is no common type. It's an error and you should issue a
> diagnostic.
>
> So for example:
>
> [Default, Default, Default] --> Default
> [Default, A, Default] --> A
> [B, B, B] --> B
> [Default, C, D] --> Error, issue diagnostic.
>
> And here's the kicker ... do it in O(1). No O(N) recursive template
> instantiations allowed. Assume that the maximum size of the set is known
> ahead of time.

In your honor, the master of conditional operator tricks, here is my solution.
The easy part only allows one to retrieve the common type inside a
template function.
With some sizeof trickery you can of course retrieve it anywhere.
It is not generalized (it needs some per-type boilerplate, which
should be easily wrappable in a macro).

-- 
gpd



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