Metaprogramming
-
Upload
dmitri-nesteruk -
Category
Technology
-
view
1.295 -
download
1
description
Transcript of Metaprogramming
•
•
•
•
•
•
template<int n> struct Factorial
{
enum {
RET = n *
Factorial<n-1>::RET
}
};
template<> struct Factorial<0>
{
enum {
RET = 1
}
};
⋮
int n = Factorial<5>::RET; // 120
•
•
–
–
–
•
–
•
–
•
•
–
•
–
–
–
–
•
–
–
•
–
•
•
–
•
•
•
– #define sqr(x) ((x)*(x))int n = sqr(2);// emits int n = ((2)*(2));
•
–pow(x,n)
•
•
–#define
•
•
•
•
class MyMacro(AbstractAstMacro)
{
override def Expand(macro as MacroStatement)
{
// macro.Argument[n]
// macro.Body
yield/return
}
}
• MyMacro
• MyMacro 1 2
• MyMacro:print “test”
class MyMacro(AbstractAstMacro)
{
override def Expand(macro as MacroStatement)
{
// macro.Argument[0]
// macro.Body
yield/return
}
}
macro MyMacro (n as int):
// MyMacro.Argument[n]
// MyMacro.Body
yield/return
k
•
•
•
•
–
•
– →
– →
•
–
–
–
•
macro dateNow:
now = DateTime.Now
return [|
print $(now.ToLocalTime().ToString())
|]
macro RepeatCStyle(c as int):
return [|
for i in range($c):
$(RepeatCStyle.Body)
|]
macro RepeatInline(c as int):
body = RepeatInline.Body
yieldAll body for i in range(c)
RepeatXxx 3:print “Go”
Console.WriteLine("Go");Console.WriteLine("Go");Console.WriteLine("Go");
int ___temp14 = 0;while (___temp14 < 3){int i = ___temp14;___temp14++;Console.WriteLine("Go");
}
•
•
•
•
–
[meta] def assert(condition as Expression):
return [|
if not $condition:
raise AssertionFailedException( $(condition.ToCodeString()))
|]
•
•
–
•
•
–
•
public class TimestampAttribute(AbstractAstAttribute):
public override def Apply(node as Node):
c = node as ClassDefinition
now = DateTime.Now
m = [|
public def GetTimestamp():
return $(now.ToLocalTime().ToString())
|]
c.Members.Add(m) // a new member added to
// an existing class
•
•
– [Timestamp]public class C:public def constructor():pass
•
– c = C()print c.GetTimestamp()
j
•
–
–
•
•
•–
•
–
–
•
–
–
•
•
–
–
•
–
–
–
•
–