不知道标准委员会那帮家伙们干嘛把C++语法搞那么复杂,你倒是多增加一些库不行吗?语法整这么复杂除了增加编译器和Code Review的成本还有个P用?
就拿调用说事吧,下面仅列出很少一部分写法。int foo(int n)
{
int s = 1;
for(; 0 < n; --n)
s *= n;
return s;
}
class C
{
public:
C() = default;
explicit C(int a) : y(a) {}
~C() = default;
int foo(int x) const { return x + y; }
private:
int y;
};
#include <functional>
#include <string>
#include <iostream>
int main()
{
typedef int (*f_int_t1) (int); // the old style
f_int_t1 foo_p1 = &foo; // & is redundant and optional
using f_int_t2 = int (*)(int); // easy to understand
f_int_t2 foo_p2 = foo;
std::function<int(int)> stdf_foo = &foo; // modern
const std::string Sep(" ");
constexpr int N = 5;
std::cout << "global function:" << foo(N) << Sep << foo_p1(N) << Sep
<< foo_p2(N) << Sep << stdf_foo(N) << "\n";
typedef int (C::* f_C_int_t1) (int) const;
f_C_int_t1 C_foo_p1 = &C::foo; // the old style
using f_C_int_t2 = int (C::*) (int) const;
f_C_int_t2 C_foo_p2 = &C::foo;
const C c(10);
constexpr int X = 20;
std::cout << "old member call: " << (c.*C_foo_p1)(X) << Sep << (c.*C_foo_p2)(X) << "\n";
std::function<int(const C&, int)> stdf_C_foo = &C::foo;
auto greet = std::mem_fn(&C::foo);
auto callback = std::bind(&C::foo, &c, std::placeholders::_1);
std::cout << "new member call: " << stdf_C_foo(c, X) << Sep << greet(c, X) << Sep
<< callback(X) << "\n";
return 0;
}