MCPcopy Create free account
hub / github.com/BehaviorTree/BehaviorTree.CPP / tryCast

Method tryCast

include/behaviortree_cpp/utils/safe_any.hpp:513–569  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

511
512template <typename T>
513inline nonstd::expected<T, std::string> Any::tryCast() const
514{
515 static_assert(!std::is_reference<T>::value, "Any::cast uses value semantic, "
516 "can not cast to reference");
517
518 if(_any.empty())
519 {
520 throw std::runtime_error("Any::cast failed because it is empty");
521 }
522
523 if(castedType() == typeid(T))
524 {
525 return linb::any_cast<T>(_any);
526 }
527
528 // special case when the output is an enum.
529 // We will try first a int conversion
530 if constexpr(std::is_enum_v<T>)
531 {
532 if(isNumber())
533 {
534 return static_cast<T>(convert<int>().value());
535 }
536 if(isString())
537 {
538 if(auto out = stringToNumber<int64_t>())
539 {
540 return static_cast<T>(out.value());
541 }
542 }
543 return nonstd::make_unexpected("Any::cast failed to cast to enum type");
544 }
545
546 if(isString())
547 {
548 if constexpr(std::is_arithmetic_v<T> && !std::is_same_v<T, bool>)
549 {
550 if(auto out = stringToNumber<T>())
551 {
552 return out.value();
553 }
554 else
555 {
556 return out;
557 }
558 }
559 }
560
561 if(auto res = convert<T>())
562 {
563 return std::move(res.value());
564 }
565 else
566 {
567 return res;
568 }
569}
570

Callers 1

tryCastWithRegistryMethod · 0.45

Calls 4

make_unexpectedFunction · 0.85
moveFunction · 0.85
emptyMethod · 0.45
valueMethod · 0.45

Tested by

no test coverage detected