在模板运算符重载中键入冲突

She*_*ohn 5 c++ c++11

对不起,这听起来像是一个常见问题,就我看来,我无法找到问题的答案.最接近的帖子是这个:仅用于基本POD的模板专业化

假设我有一个类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 ) { ... }
Run Code Online (Sandbox Code Playgroud)

但是,似乎第二个定义与第一个定义相冲突.使用第二个定义,我知道如何确保U是一个数字POD类型,这不是重点.如果我这样做,问题是我无法知道U中包含什么底层模板类型,如果它是A.

如果我的问题不够明确,请告诉我,并提前致谢!:)

编辑:模板规范被HTML过滤器消灭,在我的最后一句"U如果它是一些A<T>".简而言之,我说T是隐藏的.

Ker*_* SB 2

您可以使其与一些辅助特征一起使用,以区分专业化和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);
Run Code Online (Sandbox Code Playgroud)

这会立即从可行集中排除第二个重载,因此当只需要第一个重载时,永远不会出现确定第二个重载的返回类型的问题。

enable_if(这是使用默认模板参数来控制重载集的示例。)