例外の階層を作成したいと思います。私はC++イディオム「PolymorphicException」を使用しました。
難しいのは、これらのクラスをstd :: exceptionから派生させて、コードの任意の時点でtry ... catch(exception&e)を使用して例外をキャッチできるようにすることです。
ただし、例外がstd :: exceptionから発生した場合でも、ユーザー定義の例外から発生した場合でも、例外の処理方法を変えたいと思います。
これはポリモーフィズムを使用することを示唆しますが、std::exceptionで仮想関数を定義することはできません。
関数テンプレート(以下のコードを参照)も試しましたが、呼び出されるテンプレート関数はコンパイル時に決定されるため、機能しません。
#include <iostream>
#include <string>
using namespace std;
#include <boost\type_traits\is_base_of.hpp>
#include <boost\utility\enable_if.hpp>
class BaseError :public exception {
public:
virtual void raise(){throw *this;}
virtual string msg (){ return "This is the base class"; }
};
class DerivedError: public BaseError {
public:
void raise(){throw *this;}
string msg (){ return "This is the derived class"; }
};
template <typename T>
typename boost::disable_if<boost::is_base_of<BaseError, T>>::type
handleException(T &e)
{
cout << "Handling generic exception" << endl;
cout << e.what() << endl;
}
template <typename T>
typename boost::enable_if<boost::is_base_of<BaseError, T>>::type
handleException(T &e)
{
cout << "Handling specific exception" << endl;
cout << e.msg() << endl;
}
int main () {
BaseError b;
handleException(b);
// prints "Handling specific exception"
// prints "This is the base class"
try{
throw exception("Exception !!!");
}
catch (exception &e){
handleException(e);
// prints "Handling generic exception"
// prints "Exception !!!"
}
try{
BaseError b;
b.raise();
}
catch (exception &e){
handleException(e);
// prints "Handling generic exception" - I would like the specific behaviour
// prints "Unknown exception"
}
try{
DerivedError d;
d.raise();
}
catch (exception &e)
{
handleException(e);
// prints "Handling generic exception" - I would like the specific behaviour
// prints "Unknown exception"
}
return 0;
}
これを達成する方法について何か考えはありますか?
前もって感謝します!