gpt4 book ai didi

其他库中类型之间的 C++ 转换运算符

转载 作者:太空狗 更新时间:2023-10-29 20:01:09 26 4
gpt4 key购买 nike

为了方便起见,我希望能够在其他库中定义的两种类型之间进行转换。 (特别是来自 Qt 库的 QString 和来自 ICU 库的 UnicodeString。)现在,我已经在项目命名空间中创建了实用函数:

namespace MyProject {
const icu_44::UnicodeString ToUnicodeString(const QString& value);
const QString ToQString(const icu_44::UnicodeString& value);
}

一切都很好,但我想知道是否有更优雅的方法。理想情况下,我希望能够使用转换运算符在它们之间进行转换。但是,我确实想保留转换的明确性质。隐式转换应该是不可能的。

有没有更优雅的方法可以在不修改库源代码的情况下实现这一点?也许是一些运算符重载语法?

最佳答案

你总是可以做你正在做的事情,但让它看起来更像 Actor 。这样做甚至可能有一些合理的理由,例如能够覆盖更多类型并保留相同的语法。

考虑:

template < typename DestType, typename SourceType >
DestType string_cast(SourceType const& source)
{
return string_cast_impl<DestType,SourceType>::apply(source);
}

template < typename DestType, typename SourceType >
struct string_cast_impl;

template < >
struct string_cast_impl<QString,icu_44::UnicodeString>
{
QString apply(icu_44::UnicodeString const& val) { return MyProject::ToQString(value); }
};

// etc...

您可能会考虑不使用 impl 结构(因为您不需要部分特化......永远),或者您可能会考虑增强它以便您可以使用 enable_if。无论如何,您将拥有一个用于字符串类型转换的通用接口(interface),这样您就无需记住要调用的函数...只需调用 string_cast (source)。

编辑:想一想,我正在做您在我的一个项目中正在做的事情,将 std::string 转换为 std::wstring 或从 std::wstring 转换。我想我会用这个替代品来代替它。

关于其他库中类型之间的 C++ 转换运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2907094/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com