Poly. Solving the Expression Problem in C++11
github.com1 pointsby pyrtsa0 comments
if (x < 100) throw new Exception("Weird!); // LEAK!
You shouldn't use `new` either when throwing exceptions. Just: if (x < 100) throw Exception("Weird!); // no leak. template <size_t N>
typename enable_if<(1 < N && N < 10), void>::type
foo(int (&bar)[N])
{
// called when 1 < N && N < 10
}
template <size_t N>
typename enable_if<(N >= 10), void>::type
foo(int (&bar)[N])
{
// called when N >= 10
}
OTOH, the key advantage in static_assert is the meaningful error message. template <size_t N>
typename enable_if<(N >= 10), void>::type
foo(int (&bar)[N]) { ... }
EDIT: Changed condition from N >= 0 into a more meaningful one. X-) (-> (california) bay-in city-on) ; "The Californian bay's city"
vs. (city-on (bay-in (california))) ; "The city on the bay in California"
The former ("->") starts with what's fed into the pipeline, the latter starts with what you get out of it. In addition, "->" avoids the nesting of expressions regardless of the number of steps, which might be useful in some cases. But both styles have their place. template <typename A, typename B>
struct between_ {
A a; B b;
between_(A const & a, B const & b) : a(a), b(b) {}
template <typename T>
bool operator()(T const & t) const { return a < t && t < b; }
};
template <typename A, typename B>
between_<A, B> between(A const & a, B const & b) {
return between_<A, B>(a, b);
}
// ...
auto i = find_if(begin(v), end(v), between(x, y));
Verbose? Admittedly. Except maybe for the point of use, i.e. the last line. Which, I think, helps a lot anyway. template <typename T> using up = std::unique_ptr<T>;
template <typename T> using sp = std::shared_ptr<T>;
// ...
up<int> foo(sp<int> bar) {
return bar ? up<int>(new int(*bar)) : nullptr;
} 19+18+18+18+19 (iPhone 3GS)
38+36+36+36+38 (iPhone 4) float temp = min(x, y);
x = max(x, y);
y = temp;
instead of the conditional swapping operations, to make the whole network sorting algorithm deterministic. (Edit: notice that min() and max() here are hardware operations.)
Both test functions in transduce-bench return 250000500000.