我的软件是通过gettext翻译的。在主函数的一开始就调用了locales。不幸的是,我的单态 "Messages "中包含所有消息字符串的静态成员变量没有被翻译,因为静态成员变量是在主函数之前处理的。软件的其他部分("Messages "类的静态函数)被翻译成了预期的样子。
我的意思是,我可以使用函数来代替,但我更希望有一个解决方案,让变量仍然是变量。
如何让静态成员变量不被翻译成函数?
消息.h
#include <boost/format.hpp>
#include <boost/locale.hpp>
#define _(STRING) boost::locale::translate(STRING)
class Messages
{
const std::string example_var = _("This message is not translated.");
void example_func(int i) noexcept
{
return boost::str(boost::format(_("Just use %1% somehow.")) % i);
}
}
主文件.cpp
#include <iostream>
#include <boost/locale.hpp>
#include "Messages.h"
int main()
{
boost::locale::generator gen;
//Specify the location of dictionaries.
gen.add_messages_path("./translations/");
gen.add_messages_domain("de_DE");
//Generate the locales and imbue them to the iostream.
std::locale::global(gen(""));
std::cout.imbue(std::locale());
std::cerr.imbue(std::locale());
//Not translated
std::cout << Messages::example_var << std::endl;
//Translated
std::cout << Messages::example_func() << std::endl;
}
我用Reinstate Monica.Just把一个未使用的变量放在所有静态成员变量之前,并在lambda函数中计算其值。值本身根本不重要。唯一重要的是lambda函数进行了正确的locale函数调用.参见下面我的解决方案。
#include <boost/format.hpp>
#include <boost/locale.hpp>
#define _(STRING) boost::locale::translate(STRING)
class Messages
{
//Member variables
private:
int init_locales = []() -> int
{
//Localization
if(!Settings::get_lang().empty())
{
boost::locale::generator gen;
//Specify the location of dictionaries.
gen.add_messages_path("./translations/");
gen.add_messages_domain(Settings::get_lang());
//Generate the locales and imbue them to the iostream.
std::locale::global(gen(""));
std::cout.imbue(std::locale());
std::cerr.imbue(std::locale());
}
return 0;
}();
public:
const std::string example_var = _("This message is translated now!");
//Member functions
void example_func(int i) noexcept
{
return boost::str(boost::format(_("Just use %1% somehow.")) % i);
}
}