C++ 自动类型转换 : wrong behaviour for a container class

标签 c++ templates types casting

我正在为非常小的常量 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
}

如果是成员函数(在类主体中,Ts 可见):

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/

相关文章:

javascript - 从 JSON 自动生成 HTML

javascript - 什么是胖箭头函数/回调类型?

c++ - 替换字符串中的字符需要成本吗?

c++ - 如何将一个巨大的二维数组初始化为类中的空间?

c++ - 文件本地定义

haskell - 数据声明的类型类约束

c# - C# 中的 `x is int?` 和 `x is int` 有区别吗?

c++ - 如何实现自动插入隐含占位符的 easy_bind() ? *带有成员指针*

c++ - gcc上静态成员变量编译错误的概念检查

c++ - 为什么必须在哪里放置 “template”和 “typename”关键字?