www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Template. C++ to D

reply "Dennis Ritchie" <dennis.ritchie mail.ru> writes:
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
}
Mar 11 2015
next sibling parent reply "Namespace" <rswhite4 gmail.com> writes:
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
}
Mar 11 2015
parent "Namespace" <rswhite4 gmail.com> writes:
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
}
Mar 11 2015
prev sibling parent reply Rikki Cattermole <alphaglosined gmail.com> writes:
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)); }
Mar 11 2015
parent "Dennis Ritchie" <dennis.ritchie mail.ru> writes:
Thank you all.
Mar 11 2015