language: C++11 (gcc-4.7.2)
date: 202 days 18 hours ago
link:
visibility: public
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
#include <iostream>
 
 
template<typename T, typename LogFunc>
class Foo {
  public:
    Foo(const T& t, LogFunc fn) : t_(t), lfn_(fn) {}
 
    template<typename LFN>
    Foo& operator+=(const Foo<T, LFN>& other) {
      lfn_(t_, other());
      t_ += other();
      return *this;
    }
    T operator()() const { return t_; }
 
  private:
    T t_;
    LogFunc lfn_;
};
 
template<typename T, typename LogFunc>
std::ostream& operator<<(std::ostream& o, const Foo<T, LogFunc>& f) {
  return o << f();
}
 
// It's actually amazing that this works, and I presume that it works because it
// is only used in an inline function, from which it can be resolved at
// compile-time.
struct Noop {
  template<typename...A>
  void operator()(A...) { };
};
 
template<typename T, typename LogFunc=Noop>
Foo<T, LogFunc> make_foo(const T& t, LogFunc func=LogFunc()) {
  return Foo<T, LogFunc>(t, func);
}
 
template<typename T>
void log(std::ostream& o, const T& a, const T& b) {
  o << "a: " << a << " b: " << b << std::endl;
}
 
int main(int argc, char**argv) {
  auto f1 = make_foo(3.141592653);
  auto f2 = make_foo(2.5, [&](double a, double b) { log(std::cout, a, b); });
  f1 += f2;
  f2 += f1;
  std::cout << "f1: " << f1 << " f2: " << f2 << std::endl;
  return 0;
}