"Merge"PODs合二为一
"Merge" PODs into one
有没有办法在它们之间组合(或合并、聚合)PODs?一个直观的解决方案:
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
}
我知道合并后的基础 类 之间可能会出现一些歧义和冲突。但是将 PODs 合并为一个会非常好。我尝试达到的结果:
struct Expected { int i; char c; }; // I want Derived to behave exactly like this
我在反思的境界吗?我应该最终使用宏吗?
如果我们
don't care if the derived struct is a POD or not
,Boost.PFR
的任务非常简单 - 只需将您的 PODs 转换为元组并连接它们:
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;
}
有没有办法在它们之间组合(或合并、聚合)PODs?一个直观的解决方案:
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
}
我知道合并后的基础 类 之间可能会出现一些歧义和冲突。但是将 PODs 合并为一个会非常好。我尝试达到的结果:
struct Expected { int i; char c; }; // I want Derived to behave exactly like this
我在反思的境界吗?我应该最终使用宏吗?
如果我们
don't care if the derived struct is a POD or not
,Boost.PFR
的任务非常简单 - 只需将您的 PODs 转换为元组并连接它们:
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;
}