加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 06:01:54 所属栏目:百科 来源:网络整理
导读:我在非常小的恒定大小的向量和矩阵上实现一些线性代数运算的类. 当然,当我做: MyMathVectorint,3 a ={1,2,3};MyMathVectordouble,3 b ={1.3,2.3,3.3};std::cout"First = "a+bstd::endl;std::cout"Second = "b+astd::endl; 然后First = {2,4,6}和Second = {2
我在非常小的恒定大小的向量和矩阵上实现一些线性代数运算的类.
当然,当我做:
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
}

在成员函数的情况下(在类体中,T和s是可见的):

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读