On 01/21/12 01:22 AM, Ben Bacarisse wrote:
> Ian Collins<ian-> writes:
>>> On 01/19/12 10:09 AM, Kaz Kylheku wrote:
>>>>
>>>> Here is a requirement:
>>>>
>>>> or(x, y)
>>>>
>>>> This must evaluate X. If X is nonzero, then the value X is the
>>>> result, and Y is not evaluated. Otherwise the result is the value of
>>>> Y. X is evaluated exactly once, and Y at most once.
> <snip>
>> I couldn't resist following this up, so here's a rather OT C++0x solution:
>>
>> template<typename X, typename Y, typename... Args>
>> auto do_or( X x, Y y, Args... args ) -> decltype(x+y( args...))
>> {
>> if( x ) return x;
>>
>> return y( args...);
>> }
>
> This may be a close as one can get (I can't get any closer!) but it
> doesn't strike me as being "a solution" because of the need to wrap the
> original expression, y, in a function to delay its execution. C++11's
> lambdas make this simple enough, but it still won't look as readable as
> the original:
>
> do_or(a++, [&b]{return b++;})
> vs
> or(a++, b++)
>
> That may, however, be an advantage, since having odd evaluation semantics
> for the arguments of something that looks like a function is asking for
> trouble. (Yes, I know it was posed as an academic exercise so this is
> an incidental point).
>
> BTW, what's the purpose of the extra args? I'd have though that the
> availability of lambdas renders these unnecessary. If it's to allow a
> non-lambda function as a wrapper for the expression, then would you not
> need to write Args&... args to allow for modification?
I overlooked the lambdas.
--
Ian Collins
|