Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.