c++ - 模板运算符重载中的类型冲突

标签 c++ c++11

很抱歉,这听起来像是一个常见问题,据我所知,我找不到问题的答案。最近的帖子是这个: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/

相关文章:

c++ - 什么算法会混合具有相同场景的多张图像,除了每张图像中不同位置的一个对象?

C++:根据 struct 的整数之一对 vector <struct>(其中 struct 有 2 个整数)进行排序

c++ - 并发中的右值引用

c++ -/用户/rstu/workspace/.../main.cpp :38:13: No matching conversion for C-style cast from 'void' to 'std::__1::basic_string<char>'

c++ - 无法在 C++ 中将一些 utf-8 字符正确打印到 txt 文件

C++ 极小极大函数

c++ - VSPerf VS2010 和其他分析工具没有获取 pdb

c++ - 为什么 C 和 C++ 中有二合字母?

c++ - 从可变参数函数将函数应用于参数包的所有元素

c++ - 为什么在使用 .replace 运算符时字符串的长度不超过 16 个字符?