[英]Adding methods to template specialization
我有一个模板化的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在评论中指出的那样,所以我删除了它们。
我在这里找CRTP :
template<int X, int Y, class Derived>
struct MyBufferBase {
// common interface:
Derived& method1() { return *static_cast<Derived*>(this); }
};
template<int X, int Y>
struct MyBuffer : MyBufferBase<X, Y, MyBuffer<X,Y> > {
// basic version
};
template<int X>
struct MyRegularBuffer : MyBufferBase<X, X, MyRegularBuffer<X> > {
// extended interface:
MyRegularBuffer& method2() { return *this; }
};
如果method1
和method2
返回对*this
的引用,则可以执行您想要的操作。 否则,您将需要进行转换,或将method1
设为虚拟。
诀窍是让MyRegularBuffer::method1
调用MyBuffer::method1
,然后将结果MyBuffer<X,X>
转换为MyRegularBuffer<X>
:
template<int X>
class MyRegularBuffer : public MyBuffer<X,X>
{
public:
MyRegularBuffer<X>()
{}
MyRegularBuffer<X>(MyBuffer<X,X>)
{
// copy fields, or whatever
}
MyRegularBuffer<X> method2();
MyRegularBuffer<X> method1()
{
MyRegularBuffer<X> ret(MyBuffer<X,X>::method1());
return(ret);
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.