Thread overview | |||||||
---|---|---|---|---|---|---|---|
|
March 11, 2015 Template. C++ to D | ||||
---|---|---|---|---|
| ||||
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 Re: Template. C++ to D | ||||
---|---|---|---|---|
| ||||
Posted in reply to Dennis Ritchie | 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 Re: Template. C++ to D | ||||
---|---|---|---|---|
| ||||
Posted in reply to Namespace | 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 Re: Template. C++ to D | ||||
---|---|---|---|---|
| ||||
Posted in reply to Dennis Ritchie | 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 Re: Template. C++ to D | ||||
---|---|---|---|---|
| ||||
Posted in reply to Rikki Cattermole | Thank you all. |
Copyright © 1999-2021 by the D Language Foundation