如何强制模板从 BaseClassA 派生?
是否有可能强制模板来自某个基类,以便我可以调用基类函数?
template <class T>
void SomeManager::Add(T)
{
T->CallTsBaseClassFunction();
//... do other stuff
}
Is there any possibility to force a template to be from a certain base class so that I can call the base class function?
template <class T>
void SomeManager::Add(T)
{
T->CallTsBaseClassFunction();
//... do other stuff
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当然,您可以将类型特征与 SFINAE 结合起来:
尽管我并没有真正看到这里的好处。
Sure, you can combine type traits with SFINAE:
Although I don't really see the benefit here.
值得一提的是,它可以使用 static_assert 在编译时以更具可读性的方式完成。大致如下:
即使 B 恰好是 Base,它也能工作。
如果 Base 本身就是一个模板类,它会变得更加复杂,但仍然可以完成,并且网上有大量资源。
Worth to mention that it can be done at compile time in a more readable fashion with static_assert. Something in the lines of:
It works even when B is exactly Base.
If Base is itself a templated class it becomes more complicated but it can still be done and there's plenty of resources online.
最简单的解决方案是添加一段代码,仅在您期望的情况下才进行编译:
The easiest solution is to add a snippet of code that compiles only if it's what you expected: