Elegant Implicit Type Conversion with Template Friend Functions
When dealing with template classes, enabling implicit type conversion can be challenging. Consider the class template A with a constructor that takes an int and an operator overload for addition:
template <unsigned int m> class A { public: A(int) {} }; template<unsigned int m> A<m> operator+(const A<m>&, const A<m>&) { return A<m>(0); }
Normally, calling the constructor with an int requires explicit casting. However, the following example raises compilation errors:
A<3> a(4); A<3> b = a + 5; A<3> c = 5 + a;
The Problem of Exact Type Matching
The issue lies in how overload resolution works for template functions. During type deduction, the compiler seeks exact matches for template parameters. In our case, it fails to match the int argument to the constructor because the types do not align exactly.
The Solution: Non-Member Friend Functions
One elegant solution is to define a non-member friend function inside the class definition:
template <typename T> class test { friend test operator+(test const &, test const &) { return test(); } };
For each template instantiation, the compiler generates a separate non-template function at namespace level with the appropriate signature:
test<int> operator+(test<int> const &, test<int> const &) { return test<int>(); }
Advantages of Non-Member Friend Functions
The above is the detailed content of How to Achieve Elegant Implicit Type Conversion with Template Friend Functions?. For more information, please follow other related articles on the PHP Chinese website!