jeudi 4 janvier 2018

Implicit cast to char* when calling printf

I'm using Unicode strings as icons in my C++ GUI application and wanted to get rid of all the u8"\uf118" magic strings I had splattered around, and on the way, make these strings a type of their own.

So I created a class like this:

struct icon
{
    explicit constexpr icon(const char (&unicode_icon)[4]) :
        _icon{ unicode_icon[0], unicode_icon[1], unicode_icon[2], unicode_icon[3] }
    {
    }
    operator const char*() const
    {
        return _icon.data();
    }
private:
    std::array<char, 5> _icon;
};

And the GUI library uses some form of printf (I think vfprintf) So the code calls:

icon smiley { u8"\uf118" };
printf("%s", smiley);

I was testing this on windows so far and it worked great, but when I compile it on Linux with gcc (5.1) I get the following warning:

main.cpp:22:24: warning: format '%s' expects argument of type 'char*', but argument 2 has type 'icon' [-Wformat=]
     printf("%s", smiley);

Live example here

And when I run it, I get a seg fault inside vfprintf since it is not using the cast operator I provided.

I know I can explicitly cast the icon when I pass it to the GUI library (which has the following prototype (const char* fmt, ...) but this will make me write even more code and, well, it will look worse.

Is there a way to make the compiler do the magic and allow me to call the function like this: printf("%s", smiley); (or some other simple way)?

Aucun commentaire:

Enregistrer un commentaire