Multi-argument template functions, overloading and ambiguity errors
Lets say I'm writing a some kind of conversion operator, and I want to use it like that:
SomeType a;
AnotherType b = conv<AnotherType>(a);
First, I write the base (default) function:
template <typename T, typename U>
inline T conv(const U& a)
{
return T(a);
}
Full special开发者_开发知识库ization (or a non-template overload) is not a problem, however, when I want to do something like that:
template <typename T>
inline Point<T> conv(const Ipoint& p)
{
return Point<T>(p.x, p.y);
}
I can't write any more conversion functions from the Ipoint (to the FunkyPoint< T > for example) due to ambiguity, and I end up with an awkward usage:
Ipoint a;
Point<double> b = conv<double>(a); //ugly!
//Point<double> b = conv<Point<double> >(a); //I want that, but it (obviously) does not compile.
Is there any way of doing it nicely?
Implement the body in a class template and then you can partially specialize:
template < typename T, typename U >
struct convert
{
static T apply(U const& u) { return T(u); }
};
template < typename T, typename U > T conv(U const& u) { return convert<T,U>::apply(u); }
template < typename T > struct convert<Point<T>, Ipoint> { static Point apply(Ipoint const& u) { return Point(u.x, u.y); } };
Should work but is untested.
精彩评论