Gazebo Msgs

API Reference

12.0.2
MessageCastUtils.hh
Go to the documentation of this file.
1/*
2 * Copyright (C) 2026 Open Source Robotics Foundation
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16 */
17
18#ifndef GZ_MSGS_MESSAGE_CAST_UTILS_HH_
19#define GZ_MSGS_MESSAGE_CAST_UTILS_HH_
20
21#include <memory>
22#include <utility>
23
24#include <google/protobuf/message.h>
25#include <google/protobuf/message_lite.h>
26
27namespace gz::msgs
28{
29
30// A helper to do a dynamic cast from a generic proto message to a concrete
31// type. In newer versions of protobuf, the helper `DynamicCastMessage` is
32// available and should be used.
33template <typename T>
34const T* DoDynamicCastMessage(const google::protobuf::MessageLite* message)
35{
36#if GOOGLE_PROTOBUF_VERSION >= 5028000
37 return google::protobuf::DynamicCastMessage<T>(message);
38#else
39 return dynamic_cast<const T*>(message);
40#endif
41}
42
43// A helper to do a dynamic cast from a generic proto message to a concrete
44// type. In newer versions of protobuf, the helper `DynamicCastMessage` is
45// available and should be used.
46template <typename T>
47T* DoDynamicCastMessage(google::protobuf::MessageLite* message)
48{
49#if GOOGLE_PROTOBUF_VERSION >= 5028000
50 return google::protobuf::DynamicCastMessage<T>(message);
51#else
52 return dynamic_cast<T*>(message);
53#endif
54}
55
56// A helper to do a dynamic pointer cast from a shared_ptr to a generic proto
57// message to a concrete type. In newer versions of protobuf, the helper
58// `DynamicCastMessage` is available and should be used.
59template <typename T>
62{
63#if GOOGLE_PROTOBUF_VERSION >= 6030000
64 return google::protobuf::DynamicCastMessage<T>(std::move(message));
65#else
67#endif
68}
69
70// A helper to do a dynamic cast from a unique_ptr to a generic proto message
71// to a concrete type. In newer versions of protobuf, the helper
72// `DynamicCastMessage` is available and should be used.
73template <typename MsgT>
76{
77 auto* ptr = DoDynamicCastMessage<MsgT>(_baseMsg.get());
78 if (ptr) {
79 // transfer ownership to a new unique_ptr object by releasing from old one
80 (void)_baseMsg.release();
81 return std::unique_ptr<MsgT>(ptr);
82 }
83 return nullptr;
84}
85
86} // namespace gz::msgs
87
88#endif // GZ_MSGS_MESSAGE_CAST_UTILS_HH_