Home > Enterprise >  Disable "always failing dynamic_cast" warning
Disable "always failing dynamic_cast" warning

Time:12-27

My situation is similar to dynamic_cast<B *> (&a) gives a warning.

I have one base and one derived class:

struct Base {
  virtual ~Base() = default;

  int foo() { return 5; }
};

struct Derived : public Base {
  int bar() { return 10; }
};

I have typed unit test which checks that foo() returns 5 for both Base and Derived classes and bar() returns 10 for Derived class.

...
using Types = ::testing::Types(Base, Derived);

TYPED_TEST(Foo, Bar){
  auto obj = std::make_unique<ParamType>();
  auto *derived = dynamic_cast<Derived*>(obj.get());

  // check logic for Base
  // check logic for Derived if derived != nullptr
}

After test instantiation with ParamType equals Base, the line with dynamic_cast produces warning about dynamic_cast is never succeeds, as it is supposed to be.

How can I disable this warning on gcc compiler?

CodePudding user response:

You might use if constexpr, something along:

TYPED_TEST(Foo, Bar){
  auto obj = std::make_unique<ParamType>();

  // TestBase(*obj);
  if constexpr(std::is_same_v<ParamType, Derived>) {
      // auto *derived = dynamic_cast<Derived*>(obj.get()); // No longer needed
      // TestDerived(*obj);
  }
}
  • Related