← Back to 24T3

Tutorial 9: Generic Programming, Webots III

MTRN2500 24T3



Generic Programming

  1. What is generic programming?
  1. Refactor this program so that it uses template functions.
#include <iostream> #include <vector> void print(int val) { std::cout << val << std::endl; } void print(double val) { std::cout << val << std::endl; } void print(std::string val) { std::cout << val << std::endl; } void print(std::vector<int> val) { for (auto const& e : val) std::cout << e << ", "; std::cout << std::endl; } int main() { print(2); print(4.2); print("hello"); print(std::vector<int>{1, 2, 3}); }
  1. Why can’t this code compile?
// print.hpp #pragma once template <typename T> void print(T val); // print.cpp #include <iostream> #include "print.hpp" template <typename T> void print(T val) { std::cout << val; } // main.cpp #include "print.hpp" int main() { print("Hello World!"); }
  1. Write a class called Union which accepts two datatype parameters <U, V> and switches types based on the currently set type. It should have the following methods:

The following program shows how the union should be used and its expected values.

int main() { std::cout << std::boolalpha; // Print true/false instead of 1/0. Union<double, std::string> obj(3.3); std::cout << obj << "\n"; // 3.3 std::cout << obj.isType<double>() << "\n"; // true std::cout << obj.isType<std::string>() << "\n"; // false obj.set("Now a string"); std::cout << obj << "\n"; // "Now a string" std::cout << obj.isType<double>() << "\n"; // false std::cout << obj.isType<std::string>() << "\n"; // true }

Webots III

The starter code for this tutorial can be found here.

  1. Open the Webots controller “Pose”. This controller should constantly output its pose which is a tuple with 4 elements (X, Y, Z, R) where:

A sample output of a pose is as follows:

X: -14.75 Y: 10.11 Z: 0.00 R: 3.14

Verify the output is correct by dragging the robot around with the mouse.

a. Use the GPS device to read in the robot’s pose.

b. Use the compass device to read in the robot’s absolute heading with the positive y-axis as global north. It is important to consider that the compass device returns a 3D-vector of “northness” along their respective XYZ axes. Therefore the angle between two values is needed.

  1. Open the Webots controller “ClosestObject”. Use the lidar device so that this controller gets the distance and (x, y) position of the closest object to the robot.