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

c – 为模板专业化添加方法

发布时间:2020-12-16 03:25:26 所属栏目:百科 来源:网络整理
导读:我有一个模板化的C类,它暴露了许多方法,例如 templateint X,int Yclass MyBuffer {public: MyBufferX,Y method1();}; 现在,如果X == Y,我想向这个类公开其他方法.我通过继承MyBuffer来完成这个, templateint Xclass MyRegularBuffer : public MyBufferX,X {p
我有一个模板化的C类,它暴露了许多方法,例如
template<int X,int Y>
class MyBuffer {
public:
    MyBuffer<X,Y> method1();
};

现在,如果X == Y,我想向这个类公开其他方法.我通过继承MyBuffer来完成这个,

template<int X>
class MyRegularBuffer : public MyBuffer<X,X> {
public:
    MyRegularBuffer method2();
};

现在,问题是我希望能够做到,例如

MyRegularBuffer<2> buf = ...
MyRegularBuffer<2> otherBuf = buf.method1().method2();

但我不知道如何做到这一点.我试着想到复制构造函数,转换运算符等,但不幸的是我的C技能有点生疏.

编辑:我应该补充说,这些对象的创建相对便宜(而且,它不会发生很多),这意味着可以做这样的事情:

MyRegularBuffer<2> buf = ...
MyRegularBuffer<2> temp = buf.method1(); // Implicit conversion
MyRegularBuffer<2> otherBuf = temp.method2();

那么问题是,如何定义这样的转换.我认为转换运算符需要在MyBuffer中,但我希望它只有在X == Y时才可用.

解决方法

您不需要单独的类来表示特殊行为.部分专业化允许您处理一些MyBuffer< X,Y>案件特别给他们额外的方法.

保留MyBuffer的原始声明< X,Y>并添加这个:

template<int Y>
class MyBuffer<Y,Y> {
public:
    MyBuffer<Y,Y> method1();
    MyBuffer<Y,Y> method2();
};

MyBuffer<1,2> m12; m12.method2(); // compile fail,as desired,as it doesn't have such a method because 1 != 2
MyBuffer<2,2> m22; m22.method2(); // compile success

编辑:我的最后几行毕竟不是很有用,正如Georg在评论中指出的那样,所以我删除了它们.

(编辑:李大同)

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

    推荐文章
      热点阅读