检查可以是非多态类型的模板类的强制转换(如dynamic_cast)
我的类中有一个模板成员,我想知道该成员的类是否继承自特定类。
class BaseClass;
template <typename T>
class MyClass
{
T* my_member;
public:
void function()
{
BaseClass * base = dynamic_cast<BaseClass*>(my_member)
if(base != 0)
{
// DO SOMETHING
}
else
{
// DO SOMETHING ELSE
}
}
};
我知道如果 my_member
的类不是多态的,dynamic_cast 不会编译,但我无法控制模板类,它可以是多态类型,也可以不是(我正在编写一个库,我的用户可以使用他们想要的任何课程)。
难道没有人有想法以一种编译的方式来实现它,无论 T 是否是多态的? 感谢您的任何想法
I have a template member in my class and I'd like to know if the class of this member inherits from a specific class.
class BaseClass;
template <typename T>
class MyClass
{
T* my_member;
public:
void function()
{
BaseClass * base = dynamic_cast<BaseClass*>(my_member)
if(base != 0)
{
// DO SOMETHING
}
else
{
// DO SOMETHING ELSE
}
}
};
I know that dynamic_cast doesn't compile if the class of my_member
isn't polymorphic but I have no control on the Template Class it can be of polymorphic type or not (I am writing a library and my users can use any class they'd like).
Doesn't any one have an idea to implement this in a way that it compiles whether T is polymorphic or not?
Thanks for any ideas
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我相信 is_polymorphic Boost 类型特征 就是您要寻找的。您可能想看看另一种类型如果有更适合这项任务的话,也可以考虑特征。但请注意,其中很多都未实现,请务必检查文档。
I believe the is_polymorphic Boost type trait is the one you are looking for. You might want to take a look at the other type traits as well if there is one better suited for the task. Beware though, a lot of them are unimplemented, always check the documentation.
我知道这个问题很老了,但我遇到了同样的问题,我有一个泛型类,其类型 T 未知(库使用),因此 T 可能是多态的,也可能不是多态的,但我需要使用
dynamic_cast
来实现一些行为。我不确定这是最好的解决方案,但我能够编写一个“通用”动态转换,它使用 SFINAE 基于 T 进行不同的编译(https://en.cppreference.com/w/cpp/language/sfinae)
因此对于您的具体示例,它变成
I know this question is old, but I have been running into the same issue where I have a generic class whose type T is not known (library use) and as a result T may or may not be polymorphic yet I need to use
dynamic_cast
to implement some behavior.I am not sure this is the best solution, but I was able to write a "generic" dynamic cast which compiles differently based on T using SFINAE (https://en.cppreference.com/w/cpp/language/sfinae)
So for your specific example it becomes