CTFE vs. traditional metaprogramming
Michel Fortin
michel.fortin at michelf.com
Fri Oct 9 17:20:02 PDT 2009
On 2009-10-09 15:49:42 -0400, Andrei Alexandrescu
<SeeWebsiteForEmail at erdani.org> said:
> Thanks!
>
>
> I plan to add more text at the end of the chapter that discusses the
> opportunities of CTFE. Walter revealed to me that CTFE, particularly
> now after it's been improved by leaps and bounds by Don and by Walter
> himself, could obviate a lot of the traditional metaprogramming
> techniques developed for C++.
>
> One question that bugs me is, where do you draw the line? Say there's a
> metaprogramming problem at hand. How to decide on solving it with CTFE
> vs. solving it with templates? It would be great to have a simple
> guideline that puts in contrast the pluses and minuses of the two
> approaches.
>
> It is quite possible that templates get relegated to parameterized
> functions and types, whereas all heavy lifting in metaprogramming
> should be carried with CTFE.
My idea on templates is that they're good when you have type
parameters, or to create types based on constant parameters.
- - -
But an interesting thing I realized in the last few months is this: all
you can do with a template you can also do at runtime provided
sufficient runtime reflection capabilities. Even creating types!
Details follow.
If you have runtime reflection, it ensues that you have a data
structure (most likely a class) capable of representing each type. From
that point on, you just have to build other instances of this
type-defining data structure at runtime, and all the code using the
reflection APIs will be able to use that type. Such code (relying on
runtime reflection) would also be slower, but as the D copiler proves
with CTFE, what you know at compile time can be used to optimize things.
And from that point of view, you can see templates as an compiled,
optimized version of runtime reflection and type creation capabilities.
Don't read this as a request to change D; it's just an observation I
wanted to share in your questioning about the purpose of templates.
--
Michel Fortin
michel.fortin at michelf.com
http://michelf.com/
More information about the Digitalmars-d
mailing list