C++自动类型转换:容器类的错误行为

Vin*_*ent 9 c++ templates types casting

我正在非常小的常量矢量和矩阵上实现一些线性代数运算的类.当我这样做的时候:

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;
Run Code Online (Sandbox Code Playgroud)

然后First = {2, 4, 6}Second = {2.3, 4.3, 6.3},因为所述第二元件被浇铸到由编译器的第一个元素的类型.是否有任何"简单"的方法来提供与本机C++相同类型的自动转换:int + double = double,double + int = double?

非常感谢你.

编辑:使用答案给出的语法,我得到了运算符+工作.但我尝试了以下语法,编译失败并出现错误: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;
}
Run Code Online (Sandbox Code Playgroud)

这种语法有什么问题?

yur*_*hek 9

用途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
}
Run Code Online (Sandbox Code Playgroud)

在成员函数的情况下(在类体中,在哪里Ts可见):

template <typename TRHS>
MyMathVector<typename std::common_type<T, TRHS>::type, s> operator+(MyMathVector<TRHS, s> const& rhs) const
{
    // do addition
}
Run Code Online (Sandbox Code Playgroud)


Ker*_* SB 5

使用std::common_type特征为混合操作确定正确的结果类型.

链接页面甚至有一个与您的案例非常相似的示例.