Boost logo

Boost :

Subject: [boost] Compile Time String in C++14
From: TONGARI J (tongari95_at_[hidden])
Date: 2014-08-21 23:52:30


Hi all,

I found a way to make CT strings in C++14, with the help of generic lambda.

FYI, Ábel Sinkovics has presented a c++11 CT string in his
mpllibs::metaparse[1] lib before, but it requires some PP trick which has a
predefined limit MPLLIBS_LIMIT_STRING_SIZE.

The new trick doesn't suffer from the limitation, but it assumes a
null-terminated string.
It's fairly simple, see below:

```c++
    template<char...>
    struct str {};

    template<char c>
    struct ch {};

    template<int n>
    using idx = std::integral_constant<int, n>;

    template<class S, char c, char... cs>
    auto accum(S s, ch<c>, str<cs...>)
    {
        return accum(s, s(idx<sizeof...(cs) + 1>()), str<cs..., c>());
    }

    template<class S, char... cs>
    auto accum(S, ch<0>, str<cs...> ret)
    {
        return ret;
    }

    template<class S>
    auto make_str(S s)
    {
        return accum(s, s(idx<0>()), str<>());
    }

    #define LIT(s) make_str([](auto idx) { return ch<s[idx.value]>(); })
```

Then you can use `doSomething(LIT("abc"))` in your code.
What do you think?

[1] http://abel.web.elte.hu/mpllibs/metaparse/


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk