How to concatenate a tuple of strings at compile time?

user1205 user1205 at 1205.nc
Sat Jan 6 21:38:41 UTC 2018


On Saturday, 6 January 2018 at 21:35:19 UTC, user1205 wrote:
> On Saturday, 6 January 2018 at 19:35:33 UTC, paul wrote:
>> Hi!
>>
>> How to concatenate  a tuple of strings at compile time?
>> [...]
>
> Hello, this simple template does the job:
>
> ```
> template staticCat(T...)
> if (T.length)
> {
>     static if (T.length == 1)
>         enum staticCat = T[0];
>     else static if (T.length == 2)
>         alias staticCat = staticCat!(T[0] ~ T[1]);
>     else static if (T.length > 2)
>         alias staticCat = staticCat!(T[0] ~ T[1], T[2..$]);
> }
>
> enum elems1 = tuple("foo", "bar");
> enum elems2 = tuple("0", "1", "2");
> enum elems3 = tuple("a");
> ```
>
> pragma(msg, staticCat!(elems1.expand));
> pragma(msg, staticCat!(elems2.expand));
> pragma(msg, staticCat!(elems3.expand));
>
> There might be other solutions, maybe even in std.meta.

There is also this one, less verbose, more efficient (not 
recursive template instances):

```
template staticCat(T...)
if (T.length)
{
     import std.array;
     enum staticCat = [T].join();
}

enum elems1 = tuple("foo", "bar");
enum elems2 = tuple("0", "1", "2");
enum elems3 = tuple("a");

pragma(msg, staticCat!(elems1.expand));
pragma(msg, staticCat!(elems2.expand));
pragma(msg, staticCat!(elems3.expand));
```


More information about the Digitalmars-d-learn mailing list