异常多重继承 [英] Exception multiple inheritance
问题描述
我在混合异常和多重继承时遇到问题.基本上我有以下代码:
I have the problem with mixing exceptions and multiple inheritance. Basically I have this code:
#include <exception>
#include <stdexcept>
#include <iostream>
class A : public std::exception
{
public:
virtual ~A() noexcept {};
};
class B : public A, public std::runtime_error
{
public:
B() : A{}, std::runtime_error{""}
{
}
};
int main()
{
try {
throw B{};
} catch (const std::exception& error) {
// this catch doesn't work
std::clog << "Caught!" << std::endl;
}
}
我需要修改它,以便可以将类B的异常捕获为std :: exception(现在调用了终止处理程序).我如何实现这种行为?我想需要虚拟继承,但是在这种情况下我看不到任何使用它的方法.
What I need is to modify it so that exception of class B can be caught as std::exception (for now the terminate handler is called). How can I achieve such behavior? I guess virtual inheritance is needed but I don't see any way to use it in this case.
更新:我需要能够:
-将A视为A(琐碎),
-将A捕获为std :: exception,
-将B捕获为B(再次,琐碎),
-将B捕获为std :: exception,
-将B捕获为std :: runtime_error
UPDATE: I need to be able to:
- catch A as A (trivial),
- catch A as std::exception,
- catch B as B (again, trivial),
- catch B as std::exception,
- catch B as std::runtime_error
我知道这是很多要求,也许没有多大意义,但是我需要它,我很好奇:)
I know this is a lot of requirements, and maybe it doesn't make much sense, but I need it and I'm just curious:)
UPDATE2:我认为问题是std :: runtime_error实际上不是从std :: exception派生的(这将允许我通过A中的虚拟继承来解决问题).我对吗?仍然可以解决吗?
UPDATE2: I think the problem is std::runtime_error not derving virtually from std::exception (which would allow me to solve problem by by virtual inheritance in A). Am I right? Still, can it be solved?
UPDATE3:艾伦·斯托克斯(Alan Stokes)在下面的评论中建议了解决方案,这似乎对我有用:
UPDATE3: Alan Stokes suggested solution in comments below, which seems to work for me:
是否可以将A分为两类-一类实现B所需的功能,另一类增加对std :: exception的继承?这样,A和B都可以从(例如)A_base继承.
Can you split A into two classes - one that implements the functionality B needs, and one that adds in the inheritance from std::exception? Then both A and B could inherit from (say) A_base.
感谢您,但是如果有人还有其他好的解决方案,请告诉我.
Thanks for that, still if anyone has other good solutions please let me know.
推荐答案
Stroustrup建议以虚拟方式从std::exception
继承,以便只有一条转换路径.
Stroustrup recommends to inherit from std::exception
virtually, so that there is only one conversion path.
我个人认为,制定多重继承方案可能是过度工程,并且更喜欢线性继承链...或者根本没有.
Personally, I find that working out a multiple inheritance scheme is probably over-engineering and prefer a linear inheritance chain... or just none at all.
这篇关于异常多重继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!