public
Last active

C++ out/inout parameters

  • Download Gist
inout.cpp
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
#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);
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.