Walter Bright said:
I don't understand why, for instance:
int foo(int x)
{
x = 3 + x;
for (int i = 0; i < 10; i++)
x += 7;
return x;
}
is inappropriate for compile time execution. Of course, it could be
rewritten in FP style, but since I'm programming in C++, why shouldn't
straightforward C++ work?
First, notice that nothing prevents a C or C++ compiler to notice that
foo is a pure function, and therefore that any call such as:
int y=foo(42);
can be executed at compilation time.
The real reason why you would want to have some code executed at
compilation time is really to do metaprogramming.
Why code such as the above is inappropriate for compile time, in blub
languages, is because the types and data structures available in those
languages ARE NOT the types and data structure used by the compiler.
Well, you could 'try' to use string^W oops, there's no string data
type in C. Ok, let's try to use std::string in C++:
std::string genFun(std::string name,std::string body){
std:
stringstream s;
s<<"void "<<name<<"(){"<<endl;
s<<"cout<<\"Entering "<<name<<"\"<<endl;"<<endl;
s<<body<<endl;
s<<"cout<<\"Exiting "<<name<<"\"<<endl;"<<endl;
s<<"}"<<endl;
return(s.str());
}
and now we'd need some way to hook this function into the compiler,
let's assume a keyword 'macro' do do that:
macro genFun("example","cout<<\"In example function.\"<<endl;")
this would make the compiler run the expression following the keyword,
and replace the macro and expression with the resulting string, and
interpreting it in place.
Not very nice, is it.
What you are really longing for is Lisp with its s-expressions...
Regardless of the merits of FP programming, regular C++ programming is
not FP and it is not necessary for compile time evaluation to be FP.
Indeed, compiler hooks (macros) and programming style are totally orthogonal.
C++ has opened the door on that, I agree. Where I don't agree is that
C++ has stumbled on the ideal way of doing compile time programming,
That's the less that can be said about it...
or that FP is ideal for it, or that compile time programming should be
in a different language than runtime programming.
I am not an expert in C++ TMP. But when I do examine examples of it,
it always seems like a lot of effort is expended doing rather simple
things.
Indeed.
Furthermore, because every step in evaluating TMP requires the
construction of a unique template instantiation, this puts some rather
onerous memory and time constraints on doing more complicated things
with TMP. Perhaps these are merely technical limitations that will be
surmounted by advancing compiler technology, but I just don't see how
the result could be better than thousands of times slower than
executing the equivalent at run time.
Well, technically, since the solution has been know for about 50
years, it's not technical limitations, but psychological ones.