C++,泛型编程和虚函数。我怎样才能得到我想要的东西?
这就是我想要使用模板做的事情:
struct op1
{
virtual void Method1() = 0;
}
...
struct opN
{
virtual void MethodN() = 0;
}
struct test : op1, op2, op3, op4
{
virtual void Method1(){/*do work1*/};
virtual void Method2(){/*do work2*/};
virtual void Method3(){/*do work3*/};
virtual void Method4(){/*do work4*/};
}
我想要一个简单地从模板类派生的类,该类提供这些方法声明,同时使它们虚拟。这就是我设法想出的方法:
#include <iostream>
template< size_t N >
struct ops : ops< N - 1 >
{
protected:
virtual void DoStuff(){ std::cout<<N<<std::endl; };
public:
template< size_t i >
void Method()
{ if( i < N ) ops<i>::DoStuff(); }
//leaving out compile time asserts for brevity
};
template<>
struct ops<0>
{
};
struct test : ops<6>
{
};
int main( int argc, char ** argv )
{
test obj;
obj.Method<3>(); //prints 3
return 0;
}
但是,正如您可能已经猜到的那样,我无法重写我继承的 6 个方法中的任何一个。我显然在这里遗漏了一些东西。我的错误是什么?不,这不是家庭作业。这就是好奇心。
This is what I would like to do using templates:
struct op1
{
virtual void Method1() = 0;
}
...
struct opN
{
virtual void MethodN() = 0;
}
struct test : op1, op2, op3, op4
{
virtual void Method1(){/*do work1*/};
virtual void Method2(){/*do work2*/};
virtual void Method3(){/*do work3*/};
virtual void Method4(){/*do work4*/};
}
I would like to have a class that simply derives from a template class that provides these method declarations while at the same time making them virtual. This is what I've managed to come up with:
#include <iostream>
template< size_t N >
struct ops : ops< N - 1 >
{
protected:
virtual void DoStuff(){ std::cout<<N<<std::endl; };
public:
template< size_t i >
void Method()
{ if( i < N ) ops<i>::DoStuff(); }
//leaving out compile time asserts for brevity
};
template<>
struct ops<0>
{
};
struct test : ops<6>
{
};
int main( int argc, char ** argv )
{
test obj;
obj.Method<3>(); //prints 3
return 0;
}
However, as you've probably guessed, I am unable to override any of the 6 methods I have inherited. I'm obviously missing something here. What is my error? No, this isn't homework. This is curiosity.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 GCC 4.3 进行测试。甚至不知道为什么我要花时间在这个上:-/
我不知道如何将“prettifier”
method()
模板函数移出test
。Tested with GCC 4.3. Don't even know why I spent time on this :-/
I don't know how to move the "prettifier"
method()
template function out oftest
.这编码了一个无限循环。当 N 达到 0 时,递归不会停止。在主模板之后立即添加最终情况的专门化:
另外,这有什么作用?为什么不直接调用
ops::DoStuff()
呢?This codes an endless loop. The recursion doesn't stop when N reaches 0. Add a specialization for the end case, immediately after the primary template:
Also, what does this do? Why not just call
ops<i>::DoStuff()
directly?模仿你最初的愿望:
To mimic your original desire: