www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Cast to original type each argument in template pack

reply Andrey <saasecondbox yandex.ru> writes:
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?
Aug 21 2018
parent Alex <sascha.orlov gmail.com> writes:
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; } } ´´´
Aug 21 2018