Boost logo

Boost :

Subject: Re: [boost] compile time parser generator
From: Fernando Pelliccioni (fpelliccioni_at_[hidden])
Date: 2012-01-09 13:34:09


On Mon, Jan 9, 2012 at 3:09 PM, Simonson, Lucanus J <
lucanus.j.simonson_at_[hidden]> wrote:

> From: Dave Abrahams
> >> The code getting the characters one by one and building the MPL list
> >> (or string in the above example) can be generated by a macros - I know
> >> it is not that nice and the length of the string will be tricky, but
> >> we'll have something. The above code snippet compiles with gcc 4.6.
>
> >If you can demonstrate something that works, I'll be really excited.
>
> The return value of the constexr is a compile time constant. We ought to
> be able to use it as a template parameter.
>
> Doesn't Abel's example work?
>
> I tried this little test:
>
> #include <stdio.h>
>
> template <int N>
> constexpr char nth(const char s[N], int n) {
> return n >= N ? 0 : s[n];
> }
>
> #define S "cool"
>
> template <char T>
> void foo() { printf("not cool\n"); }
> template <>
> void foo<'c'>() { printf( "cool\n"); }
> template <>
> void foo<'o'>() { printf( "way cool\n"); }
> template <>
> void foo<'l'>() { printf( "way way cool\n"); }
>
> int main()
> {
> foo<nth<sizeof(S)>(S, 0)>();
> foo<nth<sizeof(S)>(S, 1)>();
> foo<nth<sizeof(S)>(S, 2)>();
> foo<nth<sizeof(S)>(S, 3)>();
> return 0;
> }
>
> With compile line:
> gcc/4.6.2/bin/g++ -std=c++0x
>
> And got the following output:
>
> cool
> way cool
> way cool
> way way cool
>
> It looks like you can specialize a template based on the individual
> characters within a string literal using constexpr quite simply. From here
> we ought to be able to perform arbitrary TMP on the contents of string
> literals. I would think that an ebnf as a string literal in a template
> parameter (with a macro call around it) ought to be able to generate a
> function that matches that grammar as an extreme example.
>
> Regards,
> Luke
>
>

A little code improvement

#include <stdio.h>

template <typename ArrayType, size_t N>
constexpr ArrayType nth( const ArrayType (&s)[N], int n )
{
    return n >= N ? 0 : s[n];
}

#define S "cool"

template <char T>
void foo() { printf("not cool\n"); }

template <>
void foo<'c'>() { printf( "cool\n"); }
template <>
void foo<'o'>() { printf( "way cool\n"); }
template <>
void foo<'l'>() { printf( "way way cool\n"); }

int main()
{
    foo<nth(S, 0)>();
    foo<nth(S, 1)>();
    foo<nth(S, 2)>();
    foo<nth(S, 3)>();

    return 0;
}

Regards,
Fernando.


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