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

C++ automatic type casting : wrong behaviour for a container class

本文关键字:错误 容器类 类型转换 C++      更新时间:2023-10-16

我正在实现一些类,用于在非常小的常数大小向量和矩阵上进行线性代数运算。Currenty,当我这样做时:

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},因为编译器将第二个元素强制转换为第一个元素类型。有没有什么"简单"的方法可以提供与原生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;
}

这种语法有什么问题?

使用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
}

Ot在成员函数的情况下(在类主体中,其中Ts可见):

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

使用std::common_type特性来计算混合运算的正确结果类型。

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

绝对;使用decltype:

template<typename Other>
auto operator+(const MyMathVector<Other, size> &other)
    -> MyMathVector<decltype(std::declval<T>() + std::declval<Other>()), size>;

作为一个非成员运算符,最好说出实际引用向量成员的意思:

template<typename size, typename L, typename R>
auto operator+(const MyMathVector<L, size> &l, const MyMathVector<R, size> &r)
    -> MyMathVector<decltype(l[0] + r[0]), size>;