Skip to content

Instantly share code, notes, and snippets.

@cbsmith
Last active December 23, 2015 21:19
Show Gist options
  • Select an option

  • Save cbsmith/6695445 to your computer and use it in GitHub Desktop.

Select an option

Save cbsmith/6695445 to your computer and use it in GitHub Desktop.
Attempt to create an operator||=
// -*- compile-command: "clang++ -Weverything -Wno-c++98-compat -ggdb -o test -std=c++11 -stdlib=libc++ test.cpp" -*-
#include <iostream>
#include <type_traits>
template <typename T, typename U, bool boolable = std::is_convertible<T,bool>::value, bool assignable = std::is_assignable<T, U>::value >
struct or_assign_helper;
template <typename T, typename U>
struct or_assign_helper<T, U, true, true> {
static T&& compute(T&& t, const U&& u) {
if (!t) {
t = u;
}
return std::forward<T>(t);
}
};
//replace or_assign with operator of your choice
template <typename T, typename U>
T&& or_assign(T&& t, const U&& u) {
return or_assign_helper<T, U>::compute(std::forward<T>(t), std::forward<const U>(u));
}
struct Foo {
operator int() const { return 42; }
operator const char*() const { return "this shouldn't get used"; }
};
int main(const int argc, const char* argv[]) {
int foo = argc - 1;
or_assign(foo, Foo());
std::cout << "Test: " << foo << std::endl;
or_assign(argv[argc-1], Foo());
std::cout << "String test: " << argv[argc-1] << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment