混合模板化参数类型
Mixing Templated Argument Types
如何在
C++模板/泛型编程和重载运算符中处理混合数据类型?
例如,假设我们正在创建一个带有 x 和 y 参数的二维坐标类,并且我们想要添加它们:
template <class T>
class Cartesian {
public:
Cartesian();
Cartesian(T _x, T _y);
Cartesian<T> operator + (const Cartesian<T> & rhs);
// setters, getters
private:
T x, y;
};
+
运算符重载以添加两个坐标:
template <class T>
Cartesian<T> Cartesian<T>::operator + (const Cartesian<T> & rhs) {return Cartesian(x+rhs.x,y+rhs.y);}
现在,我们实例化四个点:两个具有int
系数;另外两个具有float
:
int main() {
Cartesian<int> i1(1,2), i2(3,4);
Cartesian<float> f1(5.7, 2.3), f2(9.8, 7.43);
添加两个整数没有问题,添加两个浮点数也没有问题。但是,如果我们想在浮点数中添加一个 int 怎么办?即使在四年级的教室里,这也不会带来问题,但在这里......
(i1 + i2); // ok
(f1 + f2); // ok
(i1 + f2); // uh oh!!!
有没有简单的方法来处理这种情况?谢谢!:)
您可以使用
免费的operator+
重载。
template <class T, class U>
typename std::enable_if<std::is_arithmetic<T>::value &&
std::is_arithmetic<U>::value, Cartesian<std::common_type_t<T, U>>>::type
operator + (Cartesian<T> const & lhs, Cartesian<U> const & rhs)
{
return Cartesian<std::common_type_t<T, U>>(lhs.x+rhs.x,lhs.y+rhs.y);
}
如果早于 C++14,请将std::common_type_t<T, U>
替换为 typename std::common_type<T,U>::type
。
现在您可以执行上述操作:
Cartesian<int> i1(1, 2), i2(3, 4);
Cartesian<float> f1(5.7, 2.3), f2(9.8, 7.43);
auto a = i1 + i2; // a === Cartesian<int>
auto b = f1 + f2; // b === Cartesian<float>
auto c = i1 + f2; // c === Cartesian<float>
我只想定义一个提供参数类型推导的工厂函数,
template< class T >
auto cartesian( T const x, T const y )
-> Cartesian<T>
{ return {x, y}; }
然后是一个独立的operator+
,比如
template< class U, class V >
auto operator+( Cartesian<U> const& a, Cartesian<V> const& b )
{ return cartesian( a.x + b.x, a.y + b.y ); }
呵呵,这很容易。
相关文章:
- 扩展C++生成的代码的模板参数类型名称
- 如何在 c++ 中定义接受不同参数类型的函数向量?
- 在 C++ 中运行时调用模板时,是否可以切换模板的参数类型?
- 将函数参数类型声明为 auto
- 将函数的参数 - 签名从使用 'std::function<T>' 转换为模板参数类型
- 在 C++17 中调用具有不同参数类型的构造函数
- 具有先前参数类型匹配的参数包
- 我想知道为什么"std::unique_ptr<int> foo(新 int)"是合法的,因为"std::<int>unique_ptr"要求输入参数类型应该是"int"?
- 将可变参数类型列表的扩展打包为复杂类型的初始值设定项列表 - 合法吗?
- MSVC 错误:4 个重载中的任何一个都无法转换所有参数类型
- 使用constexpr + auto作为返回和参数类型的奇怪类型推导
- 如何从第一个参数推断第二个参数类型?
- C++模板函数中,指定回调函子/lambda 的参数类型,同时仍允许内联?
- 如何用不同的参数类型和数字回调函数
- C++stoi:这两个重载都无法转换所有参数类型
- 为什么std::{container}::template不能推导其参数类型
- 为模板参数类型中的新对象分配内存
- 为指向成员模板参数的指针推导额外模板参数类型的紧凑方式
- 使用std::conditional中的模板来确定函数参数类型
- C++中的短参数类型