How to get a function name (string) @ compile time
Denis Koroskin
2korden at gmail.com
Sun Nov 2 15:11:27 PST 2008
On Mon, 03 Nov 2008 01:59:56 +0300, Daniel Ribeiro Maciel
<daniel.maciel at gmail.com> wrote:
> How do we get a function name (string) @ compile time?
>
> I need to do stuff like (in C)
>
> #include <stdio.h>
>
> #define HELLO( func ) \
> printf( "calling " #func "\n" ); \
> func();
>
> void foo()
> {
> printf( "@foo" );
> }
>
> int main()
> {
> HELLO( foo );
> printf( "\n" );
> }
>
> The output is:
> calling foo
> @foo
>
> Thanks in advance,
> Daniel
>
Just in case you know little D here is the source code, explanation and
comparison to C++:
import std.stdio; // this is used to import writefln() - a function
similar to printf (but typesafe)
// this is a template function that takes almost anything (close to C++
templates and C macros)
void print(alias functionName)()
{
// stringof is used to take a string representation of the identifier
writefln("Calling ", functionName.stringof);
// let's invoke it! This will succeed if functionName is a function,
pointer to function,
// delegate or an object that have overloaded opCall() (similar to C++
operator())
functionName();
}
void foo()
{
writefln("@foo"); // same as printf("@foo);
}
void main()
{
// foo is a global (free) function. it is passed to the template
function.
// In C++ you would do print<foo>(); (but C++ doesn't support
specializing
// templates with functions nor does it have .stringof)
print!(foo);
}
More information about the Digitalmars-d-learn
mailing list