undefined

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//C++ WaitGroup like golang sync.WaitGroup
class WaitGroup {
public:
void Add(int incr = 1) { counter += incr; }
void Done() { if (--counter <= 0) cond.notify_all(); }
void Wait() {
std::unique_lock<std::mutex> lock(mutex);
cond.wait(lock, [&] { return counter <= 0; });
}

private:
std::mutex mutex;
std::atomic<int> counter;
std::condition_variable cond;
};

undefined

c++98 的函数对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct adder {
explicit adder(int n) : n_(n) {}
int operator() (int x) const {
return x + n_;
}
private:
int n_;
};

int main() {
auto add_2 = adder(2);
auto num = add_2(2);
std::cout << num << std::endl;
}

函数对象在c++98 开始被标准化了,函数对象是一个可以被当作函数来用的对象。

使用函数模板(函数的指针和引用)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int add_2(int x)
{
return x + 2;
};

template <typename T>
auto test1(T fn)
{
return fn(2);
}

template <typename T>
auto test2(T& fn)
{
return fn(2);
}

template <typename T>
auto test3(T* fn)
{
return (*fn)(2);
}

查看更多