Skip to content

Instantly share code, notes, and snippets.

@amidvidy
Last active August 29, 2015 14:17
Show Gist options
  • Save amidvidy/ba5647f087863f2d5497 to your computer and use it in GitHub Desktop.
Save amidvidy/ba5647f087863f2d5497 to your computer and use it in GitHub Desktop.
std::mutate example
#include <type_traits>
#include <iostream>
namespace std {
template <typename T>
using mut = typename std::remove_reference<T>::type&;
template <typename T>
constexpr mut<T> mutate(T& t) {
return static_cast<mut<T>>(t);
}
}
void foo(std::mut<int> bar) {
bar +=2;
}
int main() {
int f = 2;
const int g = 3;
// Yes, this is just a trivial wrapper around a mutable reference.
// Many orgs, such as Google, disallow non-const ref parameters, in favor of pointers because
// when calling func(&param) vs func(param) it is clear that param is being mutated.
// However, that results in potential null pointer derefs....
// std::mutate gives a clear way to show that the parameter is mutated at the call site without
// sacrificing non-nullability.
foo(std::mutate(f));
// foo(std::mutate(g)); // compiler error
std::cout << f << std::endl; // 4
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment