C++部分模板特化
这个答案被认为是“好的”代码还是只是一个丑陋的代码黑客?
我想知道这是如何向前声明的(两个类)。
当我用 2 个模板参数前向声明该类时,无论 flag
的值是什么,它总是采用这个参数。
我想这样做,因为我有 2 个特殊的成员函数,它们在 flag
为 true 时应该表现不同,而且我不想重新实现整个类。此外,它应该具有相同的名称。根据这个例子,这似乎是可能的。
我必须前向声明它,因为我正在创建一个库,我们在其中前向声明所有内容。
有什么想法吗?
Is this answer considered "good" code or is it just an ugly hack?
And I would like to know how this is forward-declared (both classes).
When I just forward-declare the class with 2 template-parameters, it just always takes this one, no matter what value flag
has.
I would like to do this because I have 2 special member functions which should behave differently on flag
being true and I don't feel like reimplementing the whole class. Also, it should have the same name. According to this example, this seems to be possible.
And I have to forward-declare it because I'm creating a library in which we forward-declare everything.
Any idea?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它的缺点是它实际上不起作用。基成员函数不会被重写,但当您尝试从外部调用它时,它只是被派生类的函数隐藏。这意味着如果您从基类(可能是所有其他函数都存在的位置)调用
doSomething
,它将调用基类doSomething
这不是我们想要的。该问题的公认答案显示了解决问题的多种方法。
It has the drawback that it doesn't really work. The base member function is not overridden, but it is just hidden by the derived class' function when you try to call it from outside. Which means if you call
doSomething
out of the base class (where presumably all your other functions live) it will call the base classdoSomething
which is not what is wanted.The accepted answer on that question shows multiple ways for how you can solve your problem.
为了使用专门化,其定义必须始终对调用者可见。例如,如果您有 template在一个标头和 ,要使用后者,您必须包含第二个标头。如果没有它,您将始终获得第一个更通用的类型。
template中定义的结构内容
struct some<类型,true> :在第二个标头中定义的 public Something编辑:关于前瞻性声明的部分让我思考。如果您只想使用类型声明(如指针变量),请执行以下操作:
Header
Source
In order to use specialisation its definition always has to be visible to the caller. If, for example, you have
template <class Type, bool flag> struct something
defined in one header andtemplate <class Type> struct something<Type, true> : public something<Type, false>
defined in the second one, to use the latter you have to include the second header. Without that you will always get the first, more generic type.EDIT: the bit about forward-declaring got me thinking. If you want to use only type declaration, as in pointer variable, do the following:
Header
Source