tags:

views:

69

answers:

1

I'm working with a large code base which uses const strings in structure initializers. I'm trying to translate these strings via GNU gettext with a minimal amount of time. Is there some sort of conversion operator I can add to default_value which will allow Case #1 to work?

#include <cstring>

template<int N> struct fixed_string
{
    char text[N];
};

// Case #1
struct data1
{
    char string[50];
};

// Case #2
struct data2
{
    const char* string;
};

// Case #3
struct data3
{
    fixed_string<50> string;
};

// A conversion helper
struct default_value
{
    const char* text;
    default_value(const char* t): text(t) {}

    operator const char*() const
    {
        return text;
    }

    template<int M> operator fixed_string<M>() const
    {
        fixed_string<M> ret;
        std::strncpy(ret.text, text, M);
        ret.text[M - 1] = 0;
        return ret;
    }
};

// The translation function
const char* translate(const char* text) {return "TheTranslation";}

int main()
{
    data1 d1 = {default_value(translate("Hello"))}; // Broken
    data2 d2 = {default_value(translate("Hello"))}; // Works
    data3 d3 = {default_value(translate("Hello"))}; // Works
}
+2  A: 

What about direct conversion to data1?

..
operator data1() const
{
    data1 ret;
    std::strncpy(ret.string, text, sizeof(ret.string));
    ret.string[sizeof(ret.string)] = 0;
    return ret;
}
..

and then:

..
    data1 d1 = default_value(translate("Hello")); // should work now...
..
Tomek
Good idea! Problem is that I have other members in the structure besides strings. The code above is just a test case. The actual structures often have over 100 members: strings, floats, doubles, enum values, etc. By using fixed_string, I am able to write a conversion, but then I also have to go update all the arrays to be fixed_string instead. I can do this, but I'm looking for a better option first.
Dark Falcon
I opted to go with case #3. There were fewer static-sized arrays than I anticipated, and few side effects from changing them to use the template class instead.
Dark Falcon