Skip to content

Instantly share code, notes, and snippets.

@tomwhoiscontrary
Created March 29, 2018 17:08
Show Gist options
  • Save tomwhoiscontrary/6d4771a587391b9701f58ade89fd511f to your computer and use it in GitHub Desktop.
Save tomwhoiscontrary/6d4771a587391b9701f58ade89fd511f to your computer and use it in GitHub Desktop.
Fresh as hell demonstration of perfect forwarding constructor with varargs in C++
#include <iostream>
#include <boost/make_shared.hpp>
class Widget {
public:
virtual int getMass() const = 0;
};
class SimpleWidget : Widget {
private:
int mass;
float price;
public:
SimpleWidget(int mass, float price) : mass(mass), price(price) {}
virtual int getMass() const {
std::cerr << "calculating mass ..." << '\n';
return mass;
}
};
template <typename UnderlyingWidget>
class CachingWidget : Widget {
private:
UnderlyingWidget underlying;
mutable int cachedMass;
public:
template <typename... Args>
CachingWidget(Args&&... args) : underlying(std::forward<Args>(args)...) {}
virtual int getMass() const {
if (cachedMass == 0) cachedMass = underlying.getMass();
return cachedMass;
}
};
int main(int argc, char** argv) {
boost::shared_ptr<CachingWidget<SimpleWidget>> cachedWidget =
boost::make_shared<CachingWidget<SimpleWidget>>(31337, 69.99);
int mass;
mass = cachedWidget->getMass();
std::cerr << "mass = " << mass << '\n';
mass = cachedWidget->getMass();
std::cerr << "mass = " << mass << '\n';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment