C++0x 添加了显式转换运算符,但它们必须始终定义为 Source 类的成员。这同样适用于赋值运算符,它必须在 Target 类上定义。
当所需转换的 Source 和 Target 类彼此独立时,Source 都不能定义转换运算符,Target 也不能从 Source 定义构造函数。
通常我们通过定义一个特定的函数来获得它,例如
Target ConvertToTarget(Source& v);
如果 C++0x 允许通过非成员函数重载转换运算符,我们可以在不相关类型之间隐式或显式定义转换。
template < typename To, typename From >
operator To(const From& val);
例如,我们可以专门从 chrono::time_point 到 posix_time::ptime 的转换,如下所示
template < class Clock, class Duration>
operator boost::posix_time::ptime(
const boost::chrono::time_point<Clock, Duration>& from)
{
using namespace boost;
typedef chrono::time_point<Clock, Duration> time_point_t;
typedef chrono::nanoseconds duration_t;
typedef duration_t::rep rep_t;
rep_t d = chrono::duration_cast<duration_t>(
from.time_since_epoch()).count();
rep_t sec = d/1000000000;
rep_t nsec = d%1000000000;
return posix_time::from_time_t(0)+
posix_time::seconds(static_cast<long>(sec))+
posix_time::nanoseconds(nsec);
}
并将该转换用作任何其他转换。
有关问题的更完整描述,请参阅here http://viboes.blogspot.com/2010/04/extrinsic-conversions.html或者在我的升压转换 https://svn.boost.org/trac/boost/wiki/LibrariesUnderConstruction#Boost.Conversion图书馆..
所以问题是:不允许使用非成员函数重载 C++ 转换运算符的理由是什么?