gz-rendering icon indicating copy to clipboard operation
gz-rendering copied to clipboard

Throwless Variant?

Open darksylinc opened this issue 4 years ago • 3 comments

ignition::rendering::Variant throws whenever it is interpreted as the wrong type.

e.g.

Variant labelAny = ogreVisual->UserData("label");
int label;
try
{
  label = std::get<int>(labelAny);
}
catch(std::bad_variant_access &e)
{
  // items with no class are considered background
  label = this->segmentationCamera->BackgroundLabel();
}

This looks fine except it makes debugging hard because "break on thrown exceptions" hits dozen/hundreds of times per frame

Desired behavior

Code should work the same as now, but could avoid throwing exceptions.

Implementation suggestion

Something like the following could work:

const int *label = std::get_if<int>(&labelAny, );
if (!label)
{
  // items with no class are considered background
  label = this->segmentationCamera->BackgroundLabel();
}

Additional context

This is a quality of life improvement for developers trying to troubleshoot a problem. IMHO exceptions should be used as a rare error that warrants attention or special handling.

What are exceptions useful for are subject to lots of debate though (e.g. Python by default treats every tiny mistake via exceptions)

darksylinc avatar Dec 18 '21 22:12 darksylinc

If there are no objections, I can submit a PR using get_if

darksylinc avatar Dec 18 '21 22:12 darksylinc

yep, no objections, we can use get_if

iche033 avatar Dec 20 '21 21:12 iche033

The task here is to change existing code that uses std::get to std::get_if. Examples:

  • https://github.com/gazebosim/gz-rendering/blob/f3d30738726d11d240907e30699ce4c66e8a0f50/ogre2/src/Ogre2SegmentationMaterialSwitcher.cc#L91
  • https://github.com/gazebosim/gz-rendering/blob/f3d30738726d11d240907e30699ce4c66e8a0f50/ogre/src/OgreThermalCamera.cc#L224
  • https://github.com/gazebosim/gz-rendering/blob/f3d30738726d11d240907e30699ce4c66e8a0f50/ogre2/src/Ogre2BoundingBoxMaterialSwitcher.cc#L122

azeey avatar May 31 '24 23:05 azeey