我正在为非常小的常量 vector 和矩阵上的线性代数运算实现一些类。 目前,当我这样做时:
MyMathVector<int, 3> a ={1, 2, 3};
MyMathVector<double, 3> b ={1.3, 2.3, 3.3};
std::cout<<"First = "<<a+b<<std::endl;
std::cout<<"Second = "<<b+a<<std::endl;
然后First = {2, 4, 6}
和 Second = {2.3, 4.3, 6.3}
,因为第二个元素被编译器转换为第一个元素类型。是否有任何“简单”的方法来提供与 native C++ 中相同类型的自动转换:int+double=double, double+int=double?
非常感谢。
编辑:
使用答案给出的语法,我让 operator+ 工作了。但我尝试了以下语法,编译失败并出现错误:expected a type, got ‘std::common_type<T, TRHS>::type’
#include <iostream>
#include <type_traits>
template<class T> class MyClass
{
public:
MyClass(const T& n) : _n(n) {;}
template<class TRHS> MyClass<typename std::common_type<T, TRHS>::type> myFunction(const MyClass<TRHS>& rhs)
{
return MyClass<std::common_type<T, TRHS>::type>(_n*2+rhs._n);
}
T _n;
};
int main()
{
MyClass<double> a(3);
MyClass<int> b(5);
std::cout<<(a.myFunction(b))._n<<std::endl;
}
那个语法有什么问题?
最佳答案
使用std::common_type
:
template <std::size_t s, typename L, typename R>
MyMathVector<typename std::common_type<L, R>::type, s> operator+(MyMathVector<L, s> const& l, MyMathVector<R, s> const& r)
{
// do addition
}
如果是成员函数(在类主体中,T
和 s
可见):
template <typename TRHS>
MyMathVector<typename std::common_type<T, TRHS>::type, s> operator+(MyMathVector<TRHS, s> const& rhs) const
{
// do addition
}
关于C++ 自动类型转换 : wrong behaviour for a container class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11744028/