Variadic templates

Bill Baxter wbaxter at gmail.com
Fri Nov 3 00:16:49 PST 2006


Reiner Pope wrote:
> Craig Black wrote:
> 
>> This feature seems to supercede older versions of variadic functions.  
>> Are there still reasons to use the older approach to variadics?  If 
>> not, should any of the older approaches ever be deprecated in order to 
>> simplify the D language?
>>
>> -Craig
>>
> I think that we can get rid of old varargs, and here's why:
> 
> The only feature-wise differences I can see between old varargs and new 
> variadic templates is that old varargs can be done without the 
> source-code present, and old varargs can be a virtual function of a class.
> 
> We can address both of these concerns with wrapper functions and an 
> additional Phobos library:
> 
> // This would be part of Phobos
> struct varargData
> {
>   TypeInfo[] ti;
>   void* argptr;
> }
> 
> varargData getVarargData(T...) (T t)
> {
>   varargData info;
>   with (info)
>     foreach (t; a)
>     {
>       ti ~= typeid(t);
>       argptr ~= cast(void*)t[0..t.sizeof]; // I'm not sure if this is 
> right, but you get the idea
>     }
>   return info;
> }
> 
> // This would be the wrapper function of the closed-source library.
> // The wrapper is open source, but doesn't expose any algorithmic details.
> // This is analogous to C++ header files.
> void opensourceWrapper(T...) (T t)
> {
>   auto data = getVarargData(t);
>   closedFoo(data);
> }
> 
> // We could create a 'final' wrapper function within a class:
> class Foo
> {
>   final void foo(T...) (T t)
>   {
>      auto data = getVarargData(t);
>      virtualFoo(data);
>   }
> 
>   // Subclasses override this
>   void virtualFoo(varargData data) {...}
> }
> 
> So, the same functionality as old varargs can be achieved with new 
> varargs, with a small pattern on the declaration site. I assert that the 
> need for this pattern will be sufficiently small (since vararg functions 
> are quite rare, and they are generally better to implement with 
> templates anyway) that this syntactic sugar (old varargs) can be removed 
> from the language.
> 
> Furthermore, this pattern is simple enough that it should be possible to 
> express with a sufficiently powerful macro system. Unfortunately, the 
> lack of string pasting in macros means that making differently-named 
> wrappers is not possible at the moment.
> 
> Cheers,
> 
> Reiner


Does that handle a variadic function in an interface, too?

interface ILogger
{
   void log_msg(char[] fmt, ...);
}

--bb



More information about the Digitalmars-d mailing list