Last active
March 25, 2020 06:48
-
-
Save LeszekSwirski/3028820 to your computer and use it in GitHub Desktop.
C++ out/inout parameters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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