Andrei Alexandrescu は、前回のC++ and Beyond で体系的なエラー処理に関する講演を行いました。私は Expected テンプレート パターンが好きで、これを Visual Studio 2010 に適合させました。これは、コンパイラがこれまでのところ拡張ユニオンをサポートしていないためです。そこで、すべてが機能することを確認する UnitTest を作成しました。そこで、スライスされた例外の検出が機能することを確認したいということになりました。しかし、そうではありませんでした。
ここに完全なコードを貼り付けたくなかったので、要点を減らしてみました。
#include <iostream>
#include <string>
#include <exception>
#include <typeinfo>
class MyException : public std::exception
{
public:
MyException()
: std::exception()
{}
virtual const char* what() const { return "I come from MyException"; }
};
void hereHappensTheFailure()
{
throw MyException();
}
template <class E>
void detector(const E& exception)
{
if (typeid(exception) != typeid(E))
{
std::cout << "Exception was sliced" << std::endl;
}
else
{
std::cout << "Exception was not sliced" << std::endl;
}
}
int main()
{
try
{
hereHappensTheFailure();
}
catch (std::exception ex) // intentionally catch by value to provoke the problem
{
detector(ex);
}
return 0;
}
しかし、スライスは検出されませんでした。テストにエラーがありますか、これは VS2010 では機能しませんか、それとも最後にパターンが機能しませんか? ( ideoneの gcc 4.7.2 が気に入らなかったため、編集しました) よろしくお願いします!