Variadic template arguments unpacking

Ali Çehreli acehreli at yahoo.com
Fri Jul 5 18:35:28 PDT 2013


On 07/05/2013 05:41 PM, Max Strakhov wrote:
> Suppose, in c++ i've got a variadic template function F, and i want to
> convert all the arguments in some individual manner by function conv and
> pass all the converted arguments as a variadic list to another variadic
> template function G.
> Then i just do the following:
>
> template<typename T>
> struct R;
>
> template<typename T>
> R<T>::Type conv(T&& val);
>
> template<typename ... Args>
> void F(Args&& ... args) {
>      G(conv(std::forward<Args>(args))...);
> }
>
> Is there any way to do the same kind of thing in D? I couldn't find any
> unpacking operator or a library function to do so...
> The problem is that i have to pass converted lits to a C-like variadic
> function, for example printf, so it would be like:
>
> template<typename T>
> struct R;
>
> template<typename T>
> R<T>::Type conv(T&& val);
>
> template<typename ... Args>
> void MyPrintf(const char * format, Args&& ... args) {
>      printf(convFormat(format), conv(std::forward<Args>(args))...);
> }
>
> I hope, my point is clear enough.

Here is one that works:

import core.stdc.stdio;
import std.string;

string convFormat(string s)
{
     return s ~ '\n';
}

void myPrintf(T...)(string s, T args)
{
     printf(convFormat(s).toStringz, args);
}

void main()
{
     myPrintf("format %d %f %c %s", 42, 1.5, 'a', "hello".toStringz);
}

Ideally, the caller of MyPrintf should not have to call toStringz on 
"hello", because myPrintf is a proper D function. However, I don't know 
how to manipulate args to call toStringz on string arguments.

More information is at

   http://dlang.org/template.html#TemplateTupleParameter

Ali



More information about the Digitalmars-d-learn mailing list