Skip to content

Instantly share code, notes, and snippets.

@kbenzie
Last active August 29, 2015 13:56
Show Gist options
  • Save kbenzie/8887260 to your computer and use it in GitHub Desktop.
Save kbenzie/8887260 to your computer and use it in GitHub Desktop.
Operator of the day!
#include <stdio.h>
void takes_int_reference(int &i) { i = 42; }
// Trivial wrapper example, a more appropriate use would be to wrap a resource
// which requires R.A.I.I. for safe usage.
class int_wrapper {
private:
int i;
public:
int_wrapper(int i) : i(i) {}
void print() { printf("%d\n", i); }
// Operator of the day! Allows passing the wrapper into functions as if it
// was the type it is wrapping.
operator int &() { return i; }
};
// This can also extend to generic wrappers
template<typename T>
class wrapper
{
T val;
public:
wrapper(T val) : val(val) {}
// Note: This is not a reference meaning val will be copied leaving it
// unchanged.
operator T() { return val; }
};
int main() {
int_wrapper i(0);
i.print();
// Here we can pass the wrapper to a function which only...
takes_int_reference(i);
i.print();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment