Skip to content

Commit adf9179

Browse files
author
Aart Stuurman
committed
Add getSdfAttrSafe function util that performs checks before reading sdf parameters. Not yet fully tested but putting it out there so i can continue later
1 parent b1e9c00 commit adf9179

1 file changed

Lines changed: 42 additions & 0 deletions

File tree

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#include <sdf/Element.hh>
2+
3+
namespace revolve
4+
{
5+
namespace gazebo
6+
{
7+
8+
// Gets an attribute from an sdf element
9+
// Throws std::runtime_error when not present.
10+
// Can do types:
11+
// - 'std::string'
12+
// - 'bool'
13+
// - 'double'
14+
template <typename OfType>
15+
OfType getSdfAttrSafe(sdf::ElementPtr sdf, std::string const &attribute)
16+
{
17+
static_assert(
18+
std::is_same<OfType, std::string>::value ||
19+
std::is_same<OfType, double>::value ||
20+
std::is_same<OfType, bool>::value,
21+
"Type not supported");
22+
if (!sdf->HasAttribute(attribute) || !sdf->GetAttribute(attribute)->IsType<OfType>())
23+
{
24+
throw std::runtime_error(std::string("Could not get attribute: ") + attribute);
25+
}
26+
else
27+
{
28+
if constexpr (std::is_same<OfType, std::string>::value)
29+
{
30+
return sdf->GetAttribute(attribute)->GetAsString();
31+
}
32+
else
33+
{
34+
// Did not test this part yet
35+
OfType buffer;
36+
return sdf->GetAttribute(attribute)->Get<OfType>(buffer);
37+
}
38+
}
39+
}
40+
41+
}
42+
}

0 commit comments

Comments
 (0)