Cast to original type each argument in template pack

Alex sascha.orlov at gmail.com
Tue Aug 21 14:15:24 UTC 2018


On Tuesday, 21 August 2018 at 08:08:58 UTC, Andrey wrote:
> Hello,
> I have a function:
>> string format(string pattern, T...)(T value)
>>{
>>    auto writer = appender!string();
>>    
>> writer.formattedWrite!pattern(convertToUnderlyingType(value)); 
>> //Tuple!T(value).expand.to!(OriginalType!T)
>> 
>>    return writer.data;
>>}
>
> The "value" in this function can be any type including "enum". 
> And if it is a "enum" I want to print it's contents not name.
> So what I need - check if current argument in template pack is 
> enum then convert it in original type. If current argument 
> isn't enum - leave it as is. In my example I showed it with 
> imaginary function "convertToUnderlyingType".
> How to implement it in D?

Do you mean something like this:

´´´
import std.stdio;
import std.traits;
import std.range;
import std.format;
import std.meta;

enum E
{
	A = "a",
	B = "b"
}
void main()
{
	format!"%s"("kuku").writeln;
	format!"%s"(E.A).writeln;
	format!"%s %s"("kuku", E.A).writeln;
}

string format(string pattern, T...)(T vals)
{
     auto writer = appender!string();
     
writer.formattedWrite!pattern(convertToUnderlyingType!(vals)); 
//Tuple!T(value).expand.to!(OriginalType!T)

     return writer.data;
}

template convertToUnderlyingType(T...)
{
	alias convertToUnderlyingType = 
staticMap!(convertToUnderlyingTypeSingle, T);
}

auto convertToUnderlyingTypeSingle(alias value)()
{
	static if(is(typeof(value) == enum))
	{
		return cast(OriginalType!(typeof(value)))value;
	}
	else
	{
		return value;
	}
}
´´´


More information about the Digitalmars-d-learn mailing list