很抱歉,这听起来像是一个常见问题,据我所知,我找不到问题的答案。最近的帖子是这个:Template Specialization for basic POD only
假设我有一个类 template <class T> class A {...};
,并且我想将 operator+ 重载为内部二元运算符(两个 A 类型的对象),以及作为混合二元运算符(A 类型的对象和数字 POD 类型的对象)。
理想情况下,我想写的是:
#include <type_traits>
using namespace std;
// Declare/fine template
template <class T> class A {...};
// Internal binary operator
template < class T, class U >
A< typename common_type<T,U>::type >
operator+ ( const A<T> &a, const A<U> &a ) { ... }
// Mixed binary operator
template < class T, class U >
A< typename common_type<T,U>::type >
operator+ ( const A<T> &a, const U &b ) { ... }
但是第二个定义似乎与第一个定义冲突。使用第二个定义,我知道如何确保 U 是数字 POD 类型,这不是重点。如果我这样做,问题是如果它是某个 A,我无法知道 U 中包含什么底层模板类型。
如果我的问题不够清楚,请告诉我,在此先感谢! :)
编辑:在我的最后一句话“U if it is some A<T>
”中,HTML 过滤器删除了模板规范。简而言之,我是说 T 是隐藏的。
最佳答案
你可以让它与一些辅助特性一起工作,以区分 A
的特殊化和更一般的类型:
#include <type_traits>
// "A" template
template <typename> class A {};
// Traits for "A-ness":
template <typename> struct is_a : std::false_type { };
template <typename T> struct is_a<A<T>> : std::true_type { };
// Operators:
template <class T, class U>
A<typename std::common_type<T, U>::type>
operator+(const A<T> & a, const A<U> & b);
template <class T, class U,
typename = typename std::enable_if<!is_a<U>::value>::type>
A<typename std::common_type<T, U>::type>
operator+(const A<T> & a, const U & b);
这会立即从可行集中排除第二个重载,因此当只需要第一个重载时,确定第二个重载的返回类型的问题永远不会出现。
(这是在默认模板参数中使用 enable_if
来控制重载集的示例。)
关于c++ - 模板运算符重载中的类型冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13542966/