C++ tricks For Reference

std::bind

#include 
#include 
#include 
void func(int i, char c, int j, std::string s, int k) {
  std::cout << i << " " << c << " " << j << " " << s << " " << k << std::endl;
}
int main() {
  auto f = std::bind(func, 1, 'c', std::placeholders::_1, std::string("hello"),
                     std::placeholders::_2);
  f(10, 20);
  f(101, 50);
  return 0;
}
/* 输出:
1 c 10 hello 20
1 c 101 hello 50

abi::__cxa_demangle 返回类的名字字符串

下面这个Point一个默认构造的实现参考了下 protobuf 的 pb.cc

#include 
#include 
#include 
class Point {
 public:
  Point() {
    std::cout << "Point()" << std::endl;
    memset(&x, 0, static_cast(reinterpret_cast(&y) -
                                      reinterpret_cast(&x) + sizeof(y)));
  }
  Point(int _x = 0, int _y = 0) : x(_x), y(_y) {
    std::cout << "Point(int _x = 0, int _y = 0)" << std::endl;
  }
  ~Point() { std::cout << "~Point()" << std::endl; }

  void print() { std::cout << " (" << x << " , " << y << ") " << std::endl; }
  int x;
  int y;

  std::string GetTypeName() {
    return abi::__cxa_demangle(typeid(*this).name(), 0, 0, 0);
  }
};

你可能感兴趣的:(c++,开发语言)