What is the rationale to non allow overloading of C++ conversions operator with non-member functio
- by Vicente Botet Escriba
C++0x has added explicit conversion operators, but they must always be defined as members of the Source class. The same applies to the assignment operator, it must be defined on the Target class.
When the Source and Target classes of the needed conversion are independent of each other, neither the Source can define a conversion operator, neither the Target can define a constructor from a Source.
Usually we get it by defining a specific function such as
Target ConvertToTarget(Source& v);
If C++0x allowed to overload conversion operator by non member functions we could for example define the conversion implicitly or explicitly between unrelated types.
template < typename To, typename From
operator To(const From& val);
For example we could specialize the conversion from chrono::time_point to posix_time::ptime as follows
template < class Clock, class Duration
operator boost::posix_time::ptime(
const boost::chrono::time_point& from)
{
using namespace boost;
typedef chrono::time_point time_point_t;
typedef chrono::nanoseconds duration_t;
typedef duration_t::rep rep_t;
rep_t d = chrono::duration_cast(
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(sec))+
posix_time::nanoseconds(nsec);
}
And use the conversion as any other conversion.
So the question is: What is the rationale to non allow overloading of C++ conversions operator with non-member functions?