C++ conditional include file runtime

后端 未结 4 2019
闹比i
闹比i 2020-12-10 08:15

I am working on a game that is coded in C++ and I would like to make it possible to change language at runtime. Currently, the language is chosen at compile time by includin

4条回答
  •  旧巷少年郎
    2020-12-10 08:31

    Perhaps the easiest way I've thought of is:

    struct language {
        virtual str::string greeting() =0;
        virtual str::string greeting(const std::string& name) =0;
        virtual str::string goodbye() =0;
        virtual ~language() {}
    };
    struct English_language {
        virtual str::string greeting() {return "Hello";}
        virtual str::string greeting(const std::string& name) {return "Hello "+name;}
        virtual str::string goodbye() {return "Goodbye";}
    } English;
    struct German_language {
        virtual str::string greeting() {return "Hallo";}
        virtual str::string greeting(const std::string& name) {return name+" Hallo";}
        virtual str::string goodbye() {return "Auf Wiedersehen";}
    } German;
    language* CurLanguage = &English;
    
    int main() {
       std::cout << CurLanguage->greeting("Steve") << '\n';
       CurLanguage = &German;
       std::cout << CurLanguage->goodbye() << '\n';
    }
    

    [EDIT] I rewrote it from scratch, since I realized pure virtual functions are a way to error at compile time if you miss a sentence, making maintenance much simpler. This version also has the ability to handle variables (dates, names, times, numbers, etc) neatly. This concept is based off what we use at my job, for over 2900 phrases/sentences in ~20 languages.

提交回复
热议问题