Generic Programming
- What is generic programming?
No answers here :)
- 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});
}
No answers here :)
- 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!");
}
No answers here :)
-
Write a class called
Unionwhich accepts two datatype parameters<U, V>and switches types based on the currently set type. It should have the following methods:
- Constructor for value of type
U - Constructor for value of type
V - Setters which will set the new value of type either
UorV. isType<T>which checks if currently set type is of typeToperator<<overload to print the union value
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
}
No answers here :)
Webots III
The starter code for this tutorial can be found here.
- Open the Webots controller “Pose”. This controller should constantly output its pose which is a tuple with 4 elements (X, Y, Z, R) where:
XYZare the 3D position of the robot in metres.Ris the global heading of the robot about theZaxis in radians.
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.
No answers here :)
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.
No answers here :)
- 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.
No answers here :)