Boost的反射庫PFR

目錄

簡介

Boost.PFR是一個Boost 1.75版本出的C++14的基礎反射庫,其使用非常簡單,非常便捷,但是適用性也比較差,有很多的地方無法使用,適合比較簡單的結構體。

使用方法

  1. 獲取欄位
struct simple {
  char a;
  float f;
};

sample var{};
boost::pfr::get<1>(var) = 1.2;

std::cout << var.f << std::endl; // 1.2
  1. 比較
assert(
  boost::pfr::eq(simple{'1', 2}, simple{'1', 2});
)
  1. 遍歷
struct test {
  int f1;
  long f2;
};

test var{100, 200};

boost::pfr::for_each_field(var, [](auto& field) {
  field += 1;
})

  1. 輸出
struct test {
  int f1;
  long f2;
};

test var{100, 200};
std::cout << boost::pfr::io(var) << std::endl;
  1. 為結構體添加簡單的操作符
struct test {
  int f1;
  long f2;
}

BOOST_PFR_FUNCTIONS_FOR(test)

這個宏會為test結構體自動添加比較運算符和輸入輸出運輸符。

  1. 獲取結構體屬性的數量
struct test {
  int a, b, c, d, e;
};

std::cout << boost::pfr::tuple_size<test>::value << std::endl; //  輸出5
  1. 將結構體解包

class MyData {
public:
  int a = 1;
  int b = 2;
};

int sa, sb;
MyData da;
std::tie(sa, sb) = boost::pfr::structure_to_tuple(MyData());
std::tie(sa, sb) = boost::pfr::structure_tie(da);

兩個類似,但是也有一些不同。structure_to_tuple是複製,structure_tie是引用。

限制

需要滿足SimpleAggregate要求。

  1. Aggregate Type: 沒有用戶定義的構造函數、沒有private或者protecetd的非靜態成員變數,沒有基礎類,沒有虛擬函數;
  2. 沒有const欄位,沒有引用或者C語言的數組。

總結

這個庫的作用感覺非常的弱,只能用於比較特定的結構體。依據提供的方法,最好的運用途徑就是替代tuple了。

Tags: