在模板类中创建使朋友运算符重载的模板 [英] Create templates overloading friend operators in template class

查看:64
本文介绍了在模板类中创建使朋友运算符重载的模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的不知道如何正确地创建它.我有带操作员重载的模板类.据我所知,我需要创建模板来重载此运算符,以获得更通用的形式.我的问题是代码无法编译,我不知道如何解决

示例:

I really don't know how to create this properly. I have templates class with overloads for operators. And as i know i need to create templates to overload this operators for more universal form. My problem is that code not compile and i don't know how to fix it

Example:

    NSize<30> a(101);
    NSize<25> b(120);
    NSize<30> c(115);
    NSize<30> res = (a*b)*(a*c)*(c*b)*(b*a)*(a*c);

最后,我应该能够做到.现在我将其定义为:

In the end, I should be able to do it. For now i defined it as :

template <int length>
friend NSize  operator * (const NSize &a, const NSize &b){
   //sth
}

我的班级的定义看起来像这样:

And definition of my class looks like this:

template<int size,typename basic_type=unsigned int,typename long_type=unsigned long long,long_type base=256>
class NSize
{
   public:
   //sth
}

推荐答案

您可以通过以下方式实现operator*:

You can implement your operator* the following way:

template<int size,typename basic_type=unsigned int,typename long_type=unsigned long long,long_type base=256>
class NSize
{
    // Note: that is not member but just friend
    template <int lengthA, int lengthB>
    friend NSize<lengthA + lengthB>  operator * (const NSize<lengthA> &a, const NSize<lengthB> &b);
};

// Actual definition that will work for every pair of Nsize of arbitrary size
template <int lengthA, int lengthB>
NSize<lengthA + lengthB>  operator * (const NSize<lengthA> &a, const NSize<lengthB> &b)
{
    return NSize<lengthA + lengthB>(...);
}

这个想法是我们应该定义opeator *的方式,使其可以使用2个任意大小的Nsize.然后生成大小为参数大小总和的结果(以确保结果始终合适)

The idea is that we should define opeator * the way it could take 2 Nsize of arbitrary size. Then it generates the result with the size being the sum of argument sizes (to be sure result always fits)

但是使用这种方法这段代码

However using this approach this code

int main() {
    NSize<30> a(101);
    NSize<25> b(120);
    NSize<30> c(115);
    auto res = (a*b)*(a*c)*(c*b)*(b*a)*(a*c);
}

最终将以res大小为285

will end up with res size being 285

在线示例

如果要保留较大的参数大小,可以将sum替换为maximum:

If you want to stick to the bigger argument size you can replace sum with maximum:

constexpr int constmax(int a, int b) {
    return a>b?a:b;
}

//.....

friend NSize<constmax(lengthA,lengthB)>  operator * (const NSize<lengthA> &a, const NSize<lengthB> &b);

在线示例

这篇关于在模板类中创建使朋友运算符重载的模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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