ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question
1

Initialize constant message

asked 2018-10-04 08:11:47 -0600

aPonza gravatar image

How do I initialize a constant message (with 2+ fields) in a class constructor? This is more of a raw C++ question but intertwined with some ROS complications. Some background:

  • for the class I'm writing it makes sense to have a member that is a message, as this will be used to command a grasp via an actionlib client so it's preemptable;
  • it would make sense for the message itself to be constant, since it's not going to change in this particular implementation (I only want to be able to grasp this kind of object with this width and this speed, etc), and possibly even static;
  • the message class doesn't have a constructor, as most (if not all) messages do, and I'd rather not write a constructor myself as it seems it's not a good way to deal with the problem because of how messages were designed;
  • the initializer list doesn't accept (or seem to accept) parameters;
  • I didn't manage to find non-ROS C++ examples that weren't using a constructor to solve the issue;
  • if I don't set it as constant I can initialize it in the body of the constructor, of course, but I think what I'm saying about the need for it to be constant makes sense.

    ROS kinetic, Ubuntu 16.04, kernel 4.8.15-rt10, libfranka 0.5.0, franka_ros 0.6.0

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted
3

answered 2018-10-05 00:37:32 -0600

kartikmohta gravatar image

Though it may not be the "cleanest" solution, you can initialize the const message in the initialization list of the class using the lambda initialization trick (See https://stackoverflow.com/q/11037650 and https://herbsutter.com/2013/04/05/com... ). This trick seems to be underutilized in the C++ community even though it's been available since C++11.

edit flag offensive delete link more
5

answered 2020-03-24 00:37:45 -0600

Rufus gravatar image

Based on @kartikmohta's answer, an example of initializing a constant std_msgs::String is as follows

const std_msgs::String MY_STRING = []{
    std_msgs::String ret;
    ret.data = "hello"; 
    return ret;}();
edit flag offensive delete link more

Question Tools

2 followers

Stats

Asked: 2018-10-04 08:11:47 -0600

Seen: 2,834 times

Last updated: Mar 24 '20