Thread overview
Template. C++ to D
Mar 11, 2015
Dennis Ritchie
Mar 11, 2015
Namespace
Mar 11, 2015
Namespace
Mar 11, 2015
Rikki Cattermole
Mar 11, 2015
Dennis Ritchie
March 11, 2015
Hi.
How to rewrite this code on D?

#include <string>
#include <iostream>

template <typename T>
T foo(const T &val)
{
    return val;
}

template <typename T, typename ...U>
T foo(const T &val, const U &...u)
{
    return val + foo(u...);
}

int main()
{
    std::cout << foo(std::string("some "), std::string("test")) << std::endl;	// prints some test
    std::cout << foo(2, 2, 1) << std::endl;		// prints 5
}
March 11, 2015
import std.stdio;

T foo(T)(auto ref const T val)
{
    return val;
}

T foo(T, Args...)(auto ref const T val, auto ref const Args u)
{
	static if (is(T == string))
    	return val ~ foo(u);
    else
    	return val + foo(u);
}

void main()
{
    writeln(foo("some ", "test")); // prints some test
    writeln(foo(2, 2, 1));		// prints 5
}
March 11, 2015
Or even shorter:

import std.stdio;

T foo(T, Args...)(auto ref const T val, auto ref const Args u)
{
    static if (Args.length > 0) {
        static if (is(T == string))
            return val ~ foo(u);
        else
            return val + foo(u);
    } else {
        return val;
    }
}

void main()
{
    writeln(foo("some ", "test")); // prints some test
    writeln(foo(2, 2, 1));      // prints 5
}
March 11, 2015
On 12/03/2015 1:02 a.m., Dennis Ritchie wrote:
> Hi.
> How to rewrite this code on D?
>
> #include <string>
> #include <iostream>
>
> template <typename T>
> T foo(const T &val)
> {
>      return val;
> }
>
> template <typename T, typename ...U>
> T foo(const T &val, const U &...u)
> {
>      return val + foo(u...);
> }
>
> int main()
> {
>      std::cout << foo(std::string("some "), std::string("test")) <<
> std::endl;    // prints some test
>      std::cout << foo(2, 2, 1) << std::endl;        // prints 5
> }

Just to declare I don't know c++. So this is just guessing.

T foo(T)(ref const(T) val) { // val does not need to be ref here!
	return cast()val; // remove const
}

T foo(T, U)(ref const(T) val, ref const(U)[] u...) { // again don't need ref/const
	import std.algorithm : map;
	return cast()val + map!((v) => cast()foo(v))(u); // ugg so basically a sum of all elements of u? ok std.algorithm has sum function for this. Also removes const

	// import std.algorithm : sum;
	// return val + u.sum;
}

void main() {
	import std.stdio : writeln;
	writeln("some ", "test"); // definitely shouldn't be separated out into two different strings
	writeln(foo(2, 2, 1));
}
March 11, 2015
Thank you all.