开发者

Iterating over a type's members at compile time

开发者 https://www.devze.com 2023-03-15 15:34 出处:网络
Is there any statically-typed, strongly-type compiled language that provides a functionality to iterate over a type\'s members at compile time and generate templated code for each one? For example, it

Is there any statically-typed, strongly-type compiled language that provides a functionality to iterate over a type's members at compile time and generate templated code for each one? For example, it could be something like:

// in pseudo-C#

public static void AddParameter(string parameterName, object value) { /* ... */ }

public static void AddParameters<T>(T parameters) {
    // Of course, the memberof(T), membersof(T), membername(<member>)
    // and membervalue(<member>, object) operators would be valid
    // inside a "compile for" block only
    compile for (memberof(T) member in membersof(T))
        AddParameter(membername(member), membervalue(member, parameters));

    /* If this were actual C#, the "compile for" block could even have a where clause */
}

So, if the following call was made:

StaticClass.AddParameters(new { UserID = "eleon", Passwor开发者_StackOverflow社区d = "Gu3$$17" });

Then that particular instantiation of AddParameters would be unrolled to

public static void AddParameters(InternalNameOfTheAnonymousType parameters) {
    AddParameters("UserID",   parameters.UserID);
    AddParameters("Password", parameters.Password);
}

At compile-time (if it were actual C# at IL-to-native compile time)


You can do it with Nemerle.


The syntactic briars are thick here, so it's hard for me to see what you're getting at, but I think Haskell's Scrap Your Boilerplate might be powerful enough to do the trick. It certainly is capable of some amazing compile-time generic metaprogramming.

0

精彩评论

暂无评论...
验证码 换一张
取 消