是否可以在 std::local
上覆盖多个方面?
例如,举一个相当做作的例子:
#include <locale>
class NumberFacet : public std::numpunct<char>
{
protected:
char do_decimal_point() const override
{
return '.';
}
char do_thousands_sep() const override
{
return ',';
}
};
class MoneyFacet : public std::moneypunct<char>
{
protected:
char do_decimal_point() const override
{
return '.';
}
char do_thousands_sep() const override
{
return ',';
}
};
我知道我可以像这样覆盖 std::locale
的一个方面来创建一个新的 locale
变量。
std::locale locale(std::locale(), new NumberFacet());
我该如何传递MoneyFacet
?
我必须这样做似乎不太令人满意:
std::locale locale(std::locale(std::locale(), new NumberFacet()), new MoneyFacet());
还有更好的方法吗?
最佳答案
operator<<()
适合这种情况:
#include <locale>
template <typename T,
typename = std::enable_if_t<
std::is_constructible<std::locale, std::locale, T*>::value
>
>
std::locale operator<<(const std::locale& locale, T* facet)
{
return {locale, facet};
}
int main()
{
auto locale = std::locale{} << new MoneyFacet{} << new NumberFacet{};
std::cout.imbue(locale);
std::cout << 12345.67f << '\n';
std::cout << 123456789u << '\n';
}
Demo。
关于c++ - 覆盖 std::locale 上的多个方面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34855812/