Going from CTFE-land to Template-land
Bill Baxter
wbaxter at gmail.com
Tue Nov 17 05:56:06 PST 2009
On Tue, Nov 17, 2009 at 5:28 AM, Steven Schveighoffer
<schveiguy at yahoo.com> wrote:
> On Tue, 17 Nov 2009 08:14:55 -0500, Bill Baxter <wbaxter at gmail.com> wrote:
>
>> Currently this doesn't work, because the CTFE function doesn't "know"
>> that it's running compile-time:
>>
>> int templ_incr(int x)() {
>> return x+1;
>> }
>>
>> int ctfe_incr(int x) {
>> return templ_incr!(x);
>> }
>>
>> Seems common to write a function that you know is only intended to be
>> used compile-time.
>> But it can't compile because the compiler doesn't know you only plan
>> to call it at compile-time.
>>
>> Is something version(__ctfe) might help with? E.g.
>> version(__ctfe) {
>> // only allow cfte_incr to be called at compile-time so it can use
>> templates
>> int ctfe_incr(int x) {
>> return templ_incr!(x);
>> }
>> }
>>
>> Or is there something more fundamental preventing CTFE funcs from
>> instantiating templates?
>
> I think it may be a valid point, but it also may be a case of factoring. Do
> you have a real example? In the one you posted, you can trivially rewrite
>
> ctfe_incr(x);
>
> as
>
> templ_incr!(x)(); // not sure if parens are optional there...
>
> or trivially rewrite ctfe_incr as:
>
> int ctfe_incr(int x) {
> return x + 1;
> }
>
> A real example would go a long way in furthering the cause...
For instance there's a handy "Format!(A...)" template in std.metastrings.
But it works on template arguments. So you can't call it from a CTFE function.
Though, there the correct solution is probably "rewrite Format!() as a
CTFE function".
I don't really know if this is a fundamentally a limitation or not.
But I would like to why not if it is not a problem.
It just seems like an artificial barrier. If I prefer to write
something as a template seems like I should be able to. Perhaps this
is just something that should become an Effective D tip: always prefer
CTFE over templates where possible. Templates also have the
disadvantage of bloating up your binaries.
A related thing is the inability to effectively use "pragma(msg, ...)"
inside a ctfe function. (It's related in the sense that if you
*could* instantiate a template from CTFE then you could make a
template that calls pragma(msg,...) to print something useful).
--bb
More information about the Digitalmars-d
mailing list