有标量可浇铸类型的特征吗? [英] Is there a trait for scalar-castable types?

查看:81
本文介绍了有标量可浇铸类型的特征吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 使用std :: OPS ::加入; 

struct Test< T:Add> {
m:T
}

impl< T:Add> Add for Test< T> {
type Output = Test< T>;
fn add(self,rhs:Test< T>) - >试验< T> {
Test {m:(self.m + rhs.m)as T}
}
}

我无法将(self.m + rhs.m)转换为 T 因为它是一个非标量转换



是否存在标量类型的特征 - 可转换为 T

解决方案

不,不存在覆盖此功能的特质。只有一些演员是可能的,他们的完整列表可以在 The Book



至于你的 Add 实现,你应该按照下面的方式修改它工作:

 使用std :: ops :: Add; 

struct Test< T:Add> {
m:T
}

impl< T> Add for Test< T>其中T:添加<输出= T> {
type Output = Self;

fn add(self,rhs:Self) - > Self {
Test {m:self.m + rhs.m}
}
}

你可以找到一个很好的解释,为什么在 T:Add< Output = T> stackoverflow.com/a/29184450/1870153\">这个SO回答这一个可能更接近您的具体情况。


I'm stuck with this code for operator overloading.

use std::ops::Add;

struct Test<T: Add>{
    m:T
}

impl<T:Add> Add for Test<T>{
    type Output = Test<T>;
    fn add(self, rhs: Test<T>) -> Test<T> {
        Test { m: (self.m + rhs.m) as T }
    }
}

I cannot cast (self.m + rhs.m) to T because it is a non-scalar cast.

Is there a trait for types scalar-castable to T?

解决方案

No, there isn't a trait covering this functionality. Only some casts are possible and their full list can be found in The Book.

As for your Add implementation, you should modify it in the following manner in order for it to work:

use std::ops::Add;

struct Test<T: Add>{
    m: T
}

impl<T> Add for Test<T> where T: Add<Output = T> {
    type Output = Self;

    fn add(self, rhs: Self) -> Self {
        Test { m: self.m + rhs.m }
    }
}

You can find a good explanation why the additional T: Add<Output = T> bound is necessary in this SO answer. This one might be even closer to your exact case.

这篇关于有标量可浇铸类型的特征吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆