Skip to content

Instantly share code, notes, and snippets.

@wbic16
Last active November 4, 2016 04:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wbic16/d99c50f421e7f9a5f5650da887d0d158 to your computer and use it in GitHub Desktop.
Save wbic16/d99c50f421e7f9a5f5650da887d0d158 to your computer and use it in GitHub Desktop.
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