Skip to content

Instantly share code, notes, and snippets.

@LeszekSwirski
Last active March 25, 2020 06:48
Show Gist options
  • Save LeszekSwirski/3028820 to your computer and use it in GitHub Desktop.
Save LeszekSwirski/3028820 to your computer and use it in GitHub Desktop.
C++ out/inout parameters
#include <algorithm>
template <typename T>
class out_ {
public:
explicit out_(T& val) : pval(&val) {}
explicit out_() : pval(nullptr) {}
void operator=(const T& newval) {
if (pval) {
*pval = newval;
}
}
void operator=(T&& newval) {
if (pval) {
*pval = std::move(newval);
}
}
private:
T* pval;
};
template <typename T>
class inout_ {
public:
explicit inout_(T& val) : pval(&val) {}
void operator=(const T& newval) {
*pval = newval;
}
void operator=(T&& newval) {
*pval = std::move(newval);
}
operator const T& () const { return *pval; }
operator T& () { return *pval; }
private:
T* pval;
};
template <typename T>
out_<T> out(T& val) {
return out_<T>(val);
}
template <typename T>
inout_<T> inout(T& val) {
return inout_<T>(val);
}
struct {
template <typename T>
operator out_<T>() {
return out_<T>();
}
} out_ignore;
void f(out_<int> x) {
x = 2;
int z = 1;
x = z;
// This won't compile:
// int y = x;
}
void g(inout_<int> x) {
x = 2;
int y = x;
}
void h(const inout_<int> x) {
int y = x;
}
int main() {
int v;
f(out(v));
f(out_ignore); // Nothing will be set
g(inout(v));
h(inout(v));
// This won't compile:
// f(v);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment