Comparing class templates with function templates

Grammatically speaking, C++ supports class templates and function templates, but the corresponding semantics of the two overlap. Some functions can be completed through class templates or function templates. The following is a comparison of the implementation of Publisher in Ros1 and Ros2. one time:

In Ros1, Publisher is implemented as follows:

//define
class ROSCPP_DECL Publisher {
    template <typename M>
    void publish(const boost::shared_ptr<M>& message) const {
         //...
     }
}
//use
ros::NodeHandle n;
ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 1000);
std_msgs::String msg;
std::stringstream ss;
ss << "hello world "
msg.data = ss.str();
chatter_pub.publish(msg);

In Ros2, Publisher is implemented as follows:

//define
template<typename MessageT, typename Alloc = std::allocator<void>>
 class Publisher : public PublisherBase
 {
   virtual void
   publish(std::unique_ptr<MessageT, MessageDeleter> & msg)
   {
        //...
   }
}
//use
auto pNode = std::make_shared<rclcpp::Node>("node");
auto marker_pub_ = pNode->create_publisher<visualization_msgs::msg::Marker>("slots_points", 10);
marker_pub_->publish(*marker_msg);

In Ros1, Publisher is an ordinary class. Users need to ensure that the type of publish is consistent with the type of the parameter template behind the previous advertisement, otherwise an error will occur.

In Ros2, Publisher is a template class, so the type feature is bound to the class. The compiler can help programmers to detect that the type release of publish is the same as the template type. If it is not the same, a compilation error will be prompted.

From this point of view, template classes have advantages over ordinary classes + template functions, but not necessarily, because in template classes, parameters are part of the type, so they cannot be added dynamically, and must be specified when writing code Good types, furthermore, they cannot be managed by containers in STL (STL containers can only hold objects of the same type, and Publishers corresponding to different types belong to different types).

So template classes can provide more static safety guarantees, but there are some sacrifices in code flexibility.

Guess you like

Origin blog.csdn.net/cyfcsd/article/details/129928724