Can someone explain the code below? I get confused when I try to understand how isNumeric!T works in this case.
auto foo(T)(T n) if (isNumeric!T) {
return (T m) {return m > n;};
}
void main() {
auto hoo5 = foo!int(1000);
writeln(hoo5(93));
writeln(hoo5(23));
}
Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one.
A template is a C++ programming feature that permits function and class operations with generic types, which allows functionality with different data types without rewriting entire code blocks for each type.
A template is a piece of code that can be copied and modified to fit a specific situation. Some templates show how, why, and when to use some feature of the language. Some templates show how to implement design patterns.
The main type of templates that can be implemented in C are static templates. Static templates are created at compile time and do not perform runtime checks on sizes, because they shift that responsibility to the compiler.
Start with:
auto foo(T)(T n) if (isNumeric!T) {
// ignore this for now
}
foo is a generic function that takes one argument of its generic type. if (isNumeric!T)
is a compile-time check from std.traits that guarantees foo's type is numeric. Non-numeric types won't work. Its return type is inferred and in this case is a delegate.
This:
(T m) {return m > n;}; //returned from foo
is a delegate literal (or closure). It's basically a function pointer with state. In this case, it closes over the parameter n
passed to foo. In your example:
auto hoo5 = foo!int(1000);
is effectively translated to the function:
bool hoo5 (int x) { return x > 1000; }
So when you call hoo5
, it returns a boolean indicating if its argument is greater than 1000 - but only in your specific case.
If you call foo like this:
auto hoo5 = foo!double(1.2345);
You get a reference to a function that returns a boolean indicating if its argument (a double) is greater than 1.2345.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With