Return data from different types of conditional operation

rumbu via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Apr 23 03:26:08 PDT 2015


On Thursday, 23 April 2015 at 10:06:45 UTC, John Colvin wrote:
> On Thursday, 23 April 2015 at 09:48:21 UTC, Dennis Ritchie 
> wrote:
>> Hi,
>> Why the program can not return different types of data from 
>> the conditional operator?
>>
>> -----
>> import std.stdio;
>>
>> auto foo() {
>>
>> 	if (true) {
>> 		return 0;
>> 	} else
>> 		return "true";
>> }
>>
>> void main() {
>>
>> 	writeln(foo);
>> }
>
> import std.variant, std.stdio;
>
> auto foo()
> {
> 	if (true)
> 		return Variant(0);
> 	else
> 		return Variant("Hello");
> }
>
> void main()
> {
> 	foo.writeln;
> }

If 'true' is known at compile time, it works:

auto foo() {

	static if (true) {
		return 0;
	} else
		return "true";
}


More information about the Digitalmars-d-learn mailing list