Skip to content

Instantly share code, notes, and snippets.

@krosaen
Created January 11, 2019 15:01
Show Gist options
  • Save krosaen/8f1feba0df993d435e499ee633ed2bde to your computer and use it in GitHub Desktop.
Save krosaen/8f1feba0df993d435e499ee633ed2bde to your computer and use it in GitHub Desktop.
#include <math.h>
#include <iostream>
#include <vector>
template <class Part>
struct PartScorer {
struct PartAdapter {
double PartArea(const Part& part) = delete;
};
double ScoreParts(std::vector<Part> parts) {
PartAdapter part_adapter;
double total = 0.0;
for (const Part& part : parts) {
total += part_adapter.PartArea(part);
}
return total;
}
};
// pretend these are defined elswhere and I don't want to modify them
struct SteeringWheel {
int radius;
};
struct Seat {
int height;
int width;
};
// I just need to define adpaters for any types I want to score
template <>
struct PartScorer<SteeringWheel>::PartAdapter {
double PartArea(const SteeringWheel& steering_wheel) { return M_PI * steering_wheel.radius * steering_wheel.radius; }
};
template <>
struct PartScorer<Seat>::PartAdapter {
double PartArea(const Seat& seat) { return seat.height * seat.width; }
};
// And now I can instantiate a PartScorer for these types
int main() {
std::vector<SteeringWheel> sws = {{22}, {33}, {44}};
std::vector<Seat> seats = {{10, 20}, {22, 33}, {1, 33}};
std::cout << "score steering wheels " << PartScorer<SteeringWheel>().ScoreParts(sws) << std::endl;
std::cout << "score seats " << PartScorer<Seat>().ScoreParts(seats) << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment