如何调试std :: bad_cast异常

use*_*610 6 c++ debugging

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);
}
Run Code Online (Sandbox Code Playgroud)

这个明显错误的程序(因为模板参数不同)崩溃了

terminate called after throwing an instance of 'std::bad_cast'
  what():  std::bad_cast
Aborted (core dumped)
Run Code Online (Sandbox Code Playgroud)

除了运行时错误消息之外,有没有办法如何精确诊断出错的地方?有什么东西,可以指出int/float错误给我?我正在寻找一个描述性的错误消息,如

const GA1DArrayGenome<float> & 无法施展 const GA1DArrayGenome<int> &

更好的是,由于C++类型有时会变得毛茸茸,因此该工具可以注意到模板参数中的精确差异.

Mat*_* M. 8

您也可以放弃直接使用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());
    }
}
Run Code Online (Sandbox Code Playgroud)