有沒有辦法在它們之間組合(或合并、聚合)POD?一種直觀的解決方案:
struct Base1 { int i; };
struct Base2 { char c; };
struct Derived : Base1, Base2 {};
// in a more generalized way
// template <class... Ts> struct Aggregate : Ts... {};
除了,我們失去了一些東西:
int main()
{
Derived d {42, 'c'}; // OK
auto [i, c] = d; // Error
static_assert(std::is_standard_layout_v<Derived>); // Error
}
我看到我們最終可能會在合并的基類之間出現一些歧義和沖突。但是將 POD 合并為一個會非常好。我試圖達到的結果:
struct Expected { int i; char c; }; // I want Derived to behave exactly like this
我是在反思的領域嗎?我應該最終使用宏嗎?
uj5u.com熱心網友回復:
要是我們
不關心派生結構是否為 POD
,任務非常簡單Boost.PFR- 只需將您的 POD 轉換為元組并將它們連接起來:
template<typename... Ts> using Merge = decltype(std::tuple_cat(
boost::pfr::structure_to_tuple(std::declval<Ts>())...
));
一個簡單的測驗:
int main() {
struct Base1 { int i, j; };
struct Base2 { char c; };
using Expected = Merge<Base1, Base2>;
static_assert(std::is_same_v<Expected, std::tuple<int, int, char>>);
Expected expected{42, 1337, 'c'};
auto&& [i, j, c] = expected;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/325650.html
