how can I test the result of "dynamic_cast" without causing segment fault

Viewed 87

I'm writing a class using both polymorphism and template, it's like:


class base {
    virtual ~base() = default;
};

template <typename T>
class derived : public base {
T a;
    void save(T a_) { a = a_; }
};

so when I wanna use function derived::save(), basicly, I need dynamic_cast, but it cannot check if it's a good cast or a bad one:

void test() {
    base *p = new derived<float>();
    // good case
    dynamic_cast<derived<float>*>(p)->save(1);
    // bad case
    dynamic_cast<derived<int>*>(p)->save(1);
}

As you can see, the good case works fine, but the bad one would cause a segment fault which is kind of difficult to locate in a large project.

So, is there any way I check the cast, and warn the user like:

template <typename T>
class derived : public base {
T a;
using type = T;
/// of course this would not work, but you know want I mean
    void save(T a_) {
        if (std::is_same< std::decltype(a_), type >::value)
            a = a_;
        else
            throw std::runtime_error("invalid type");
    }
};
1 Answers

You can check result of the dynamic cast:

void test() {
    base* p = new derived<float>();
    // good case
    if (auto* d = dynamic_cast<derived<float>*>(p))
         d->save(1); // called
    if (auto* d = dynamic_cast<derived<int>*>(p))
         d->save(1); // not called
    delete p;
}

Making save virtual in the base class seems better BTW.

Related