Template. C++ to D
Rikki Cattermole via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Mar 11 05:13:33 PDT 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));
}
More information about the Digitalmars-d-learn
mailing list