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

Dav*_*eer 3 c++ casting

为方便起见,我希望能够在其他库中定义的两种类型之间进行转换.(具体来说,QString来自Qt库和UnicodeStringICU库.)现在,我在项目命名空间中创建了实用程序函数:

namespace MyProject {
    const icu_44::UnicodeString ToUnicodeString(const QString& value);
    const QString ToQString(const icu_44::UnicodeString& value);
}
Run Code Online (Sandbox Code Playgroud)

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

有没有更优雅的方法来实现这一点而不修改库的源代码?也许某些运算符重载语法?

Edw*_*nge 7

你可以随时做你正在做的事,但让它看起来更像是铸造.这样做甚至可能有一些合理的论据,例如能够覆盖更多类型并保留相同的语法.

考虑:

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...
Run Code Online (Sandbox Code Playgroud)

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

编辑:来想一想,我正在做我正在做的一个项目,从std :: string转换为/从std :: wstring.我想我会用这个替代品替代它.