/*
* CS 70 Petting Zoo, version 1 (Template version)
*
* For simplicity, this file contains all the classes and functions
*/
#include <iostream>
#include <string>
#include <type_traits>
#include <cstddef>
class Cow {
public:
explicit Cow(std::string name);
void speak() const;
void feed();
void party() const;
private:
std::string name_;
double happiness_;
size_t hunger_;
};
Cow::Cow(std::string name) : name_{name}, happiness_{7.5}, hunger_{3} {
// Nothing (else) to do
}
void Cow::speak() const {
std::cout << name_ << " says: Mooooo" << std::endl;
}
void Cow::feed() {
std::cout << name_ << " eats" << std::endl;
if (hunger_ > 0) {
--hunger_;
}
}
void Cow::party() const {
std::cout << name_ << " parties!!" << std::endl;
}
class Raptor {
public:
explicit Raptor(std::string name);
void speak() const;
void feed();
private:
std::string name_;
double anger_;
size_t hunger_;
};
Raptor::Raptor(std::string name) : name_{name}, anger_{11}, hunger_{42} {
// Nothing (else) to do
}
void Raptor::speak() const {
std::cout << name_ << " says: Rawrrr" << std::endl;
}
void Raptor::feed() {
std::cout << name_ << " eats" << std::endl;
if (hunger_ > 0) {
--hunger_;
}
}
template <typename T>
void engageWith(T creature) {
creature.feed();
creature.speak();
if constexpr (std::is_same_v<T, Cow>) {
// ^-- This is a C++ 17 feature that's outside the scope of CS 70.
// It's a compile-time check to see if T is the same type as Cow,
// if it is, then the code inside the if block is compiled.
// This block *isn't even compiled* when T is not a Cow.
//
// Why did I write this when you don't need to know it for this
// class? Because it's a cool feature of C++ templates, and
// because it seemed sad for our cows to never party!
creature.party();
}
}
int main() {
Cow bessie("Bessie");
Raptor peri("Peri");
std::cout << "# Petting the Cow:" << std::endl;
engageWith(bessie);
std::cout << "\n# Petting the Raptor:" << std::endl;
engageWith(peri);
return 0;
}