Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Template-fu: https://github.com/SuperV1234/vittorioromeo.info/blob/master/extra/in_place_expr_validity/0_cpp11.cpp
Object-fu:
#include <iostream>
#include <vector>
using namespace std;
struct Cat
{
void meow() const { cout << "meow\n"; }
};
struct Dog
{
void bark() const { cout << "bark\n"; }
};
struct Calico
{
void meow() const { cout << "MROW!\n"; }
};
struct Hound
{
void bark() const { cout << "WOOF!\n"; }
};
struct MakeNoise
{
virtual void noise() = 0;
};
template <typename Catish>
struct SimpleCat : public MakeNoise
{
SimpleCat(const Catish& other)
: m_cat(other)
{
}
void noise() override final { m_cat.meow(); }
private:
const Catish& m_cat;
};
template <typename Dogish>
struct SimpleDog : public MakeNoise
{
SimpleDog(const Dogish& other)
: m_dog(other)
{
}
void noise() override final { m_dog.bark(); }
private:
const Dogish& m_dog;
};
int main()
{
Cat morgan;
Dog abby;
Calico miley;
Hound hailey;
vector<MakeNoise*> stuff;
SimpleCat<Cat> icat(morgan);
SimpleDog<Dog> idog(abby);
SimpleCat<Calico> ical(miley);
SimpleDog<Hound> ihound(hailey);
stuff.push_back(&idog);
stuff.push_back(&icat);
stuff.push_back(&ical);
stuff.push_back(&ihound);
for (MakeNoise* noiseMaker : stuff)
{
noiseMaker->noise();
}
return 0;
}
// Output:
bark
meow
MROW!
WOOF!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment