class GAGenome {
virtual void method(){};
};
template <class T>
class GAArray {
};
template <class T>
class GA1DArrayGenome : public GAArray<T>, public GAGenome {
};
int main() {
GA1DArrayGenome<float> genome;
const GAGenome & reference = genome;
auto cast = dynamic_cast<const GA1DArrayGenome<int> &>(reference);
}
这个明显错误的程序(因为模板参数不同)崩溃了
terminate called after throwing an instance of 'std::bad_cast'
what(): std::bad_cast
Aborted (core dumped)
除了运行时错误消息之外,是否有一种方法可以准确诊断出哪里出了问题?可以向我指出 int/float 错误的东西吗?我正在寻找描述性错误消息,例如
const GA1DArrayGenome<float> &
cannot be cast toconst GA1DArrayGenome<int> &
更好的是,由于 C++ 类型有时会变得毛茸茸,该工具可以注意到模板参数中的精确差异。
最佳答案
您也可以放弃直接使用 dynamic_cast
并将其包装在您自己的模板机制中:
#include <sstream>
class my_bad_cast: public std::bad_cast {
public:
my_bad_cast(char const* s, char const* d): _source(s), _destination(d) {
#ifdef WITH_BETTER_WHAT
try {
std::ostringstream oss;
oss << "Could not cast '" << _source
<< "' into '" << _destination << "'";
_what = oss.str();
} catch (...) {
_what.clear();
}
#endif
}
char const* source() const { return _source; }
char const* destination() const { return _destination; }
#ifdef WITH_BETTER_WHAT
virtual char const* what() const noexcept {
return not _what.empty() ? _what.c_str() : std::bad_cast::what();
}
#endif
private:
char const* _source;
char const* _destination;
#ifdef WITH_BETTER_WHAT
std::string _what;
#endif
// you can even add a stack trace
};
template <typename D, typename S>
D my_dynamic_cast(S&& s) {
try {
return dynamic_cast<D>(std::forward<S>(s));
} catch(std::bad_cast const&) {
throw my_bad_cast(typeid(S).name(), typeid(D).name());
}
}
关于c++ - 如何调试 std::bad_cast 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23391649/