jeudi 3 mars 2016

GCC produce "could not convert" error when using aggregate initialization

I'm trying to make C-string size calculation at compile time, using code like this:

#include <stdio.h>
#include <stdint.h>

class StringRef
{
public:
    template<int N>
    constexpr StringRef(const char (&str)[N])
        : m_ptr(str), m_size(uint32_t(N-1)) {}

    constexpr const char *constData() const
    { return m_ptr; }

private:
    const char *m_ptr;
    uint32_t m_size;
};

struct S
{
    StringRef str;
};

constexpr static const struct S list[] =
{
    "str",
};

int main()
{
    printf("%s\n", list[0].str.constData());

    return 0;
}

In clang-3.7 everything is fine, but in GCC 4.9.3-5.3 I get:

error: could not convert '(const char*)"str"' from 'const char*' to 'StringRef'

It can be fixed by adding explicit braces:

constexpr static const struct S list[] =
{{
    { "str" },
}};

But code became ugly and, still, clang somehow understand it correctly.

How can I make gcc understand array initialization without explicit braces?

Aucun commentaire:

Enregistrer un commentaire