I think D's static if
is an interesting language feature. That prompts my question: Are there are other examples of compiled languages in which the compiler has a strong notion of the code and there are languages facilities to access them?
For example, this code provides something similar to repr
from Python:
char[] repr(T)(T value) {
static if (is(typeof(value.__repr__))) { // class T provides a "repr()" method
return value.__repr__();
} else static if (is(T:string)) {
return `"` ~ value ~ `"`;
// ...other cases...
} else {
return toString(value);
}
}
I think this is cool is because it allows a different and more general approach to what overloading does, which is kind of an inside out way to make code more dynamic, compared to features like this. For example, the compiler knows how many fields my class has, but there's no way for my code to access that information at compile time in most languages.
CAVEAT: That last paragraph had opinions in it, but I just mean to provide some motivation and clarification for my question, not elicit controversy. I just want to find out if any other compiled languages have such features.
Any language with real macros has a form of static if. For instance Lisp and Nemerle let you construct the code that a macro expands to using programming constructs like 'if' and for-loops. Those are essentially compile-time decisions and let you do something similar to static if. In the case of Nemerle macros are basically plug-ins to the compiler that are executed at compile-time.
In C++ there's boost MPL library which has a kind of static if that can be used to choose between two types. You could put some code inside the two types in a run() member and get something kinda similar, but with very cumbersome syntax.
For example with Boost MPL you could do something like this:
struct float_impl {
static void run() { /* float case code */ }
}
struct int_impl {
static void run() { /* int case code */ }
}
typedef typename if_<
is_same<T, float>
, float_impl
, int_impl
>::type impl_t;
impl_t::run();
In D that'd be:
static if(is(T == float)) {
/* float code */
}
else {
/* int code */
}