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

时间:2012-07-31 15:47:33

标签: 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;

然后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;
}

该语法有什么问题?

3 个答案:

答案 0 :(得分: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
}

在成员函数的情况下(在类正文中,Ts可见):

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

答案 1 :(得分:5)

使用std::common_type特征为混合操作找出正确的结果类型。

链接页面甚至有一个与你的情况非常相似的例子。

答案 2 :(得分:4)

绝对;使用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>;