C++ to D
John Colvin via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Apr 1 08:22:09 PDT 2015
On Wednesday, 1 April 2015 at 13:59:10 UTC, Dennis Ritchie wrote:
<snip>
You can do this:
import std.typetuple;
//helper for staticReduce
template Alias(alias a)
{
alias Alias = a;
}
// staticReduce should really be in std.typetuple, or
// the soon to arrive std.meta package.
template staticReduce(alias F, TL ...)
if (TL.length >= 2)
{
static if (TL.length == 2)
alias staticReduce = Alias!(F!(TL));
else
alias staticReduce
= staticReduce!(F, F!(TL[0..2]), TL[2..$]);
}
enum Add(Args...) = Args[0] + Args[1];
enum Inc(Args...) = Args[0] + 1;
alias staticSum(TL ...) = staticReduce!(Add, TL);
void main()
{
//using two_plus_one = add<two, one>;
enum two_plus_one = 2 + 1;
//std::cout << to_int<two_plus_one>::result << std::endl;
static assert(two_plus_one == 3);
//using l = list<one, list<two, list<four, nil>>>;
alias l = TypeTuple!(1, 2, 4);
//std::cout << length<l>::result << std::endl; // prints 3
static assert(l.length == 3);
//using res = sum<map<inc, l>::result>::result;
enum res = staticSum!(staticMap!(Inc, l));
//std::cout << to_int<res>::result << std::endl; // prints 10
static assert(res == 10);
}
but really, there's no point:
import std.algorithm;
//All at compile-time:
static assert(1+2 == 3);
static assert([1,2,4].length == 3);
static assert([1,2,4].map!"a+1".sum == 10);
Compile Time Function Evaluation (CTFE) is a very powerful tool
to avoid having to enter in to all that C++ style mess.
More information about the Digitalmars-d-learn
mailing list