跨继承树初始化元组
Initialize tuple across inheritance tree
让类 B 是 A 的基:
class B
{
public:
std::tuple<int, bool, float> properties.
}
class A : public B
{
public:
std::tuple<float, std::string, std::string> derivedProperties.
}
有没有办法将派生属性元组添加到基本元组?例如通过某种形式的 CRTP?我知道基类和派生类型的属性在编译时是已知的,但我似乎无法弄清楚如何组合不同继承级别的属性。
可以使用可变参数模板向基类的properties
成员添加更多类型(B
(。如果你也希望在派生类中拥有基类的构造函数,你可以使用 using-声明:
#include <string>
#include <tuple>
template<typename... Ts>
class B {
public:
B(int i, bool b, float f, const Ts&... rest) :
properties(std::make_tuple(i, b, f, rest...)) {
}
std::tuple<int, bool, float, Ts...> properties;
};
class A : public B<float, std::string, std::string> {
using B::B;
};
int main() {
A foo(12, true, 3.14, 6.28, "foo", "bar");
}
class B
的派生类传递给同一函数可以通过函数模板实现:
template<typename... Ts>
void test(const B<Ts...>& base);
现场演示
如果相关,您可以使用以下内容:
template <typename ... Ts>
class C
{
public:
std::tuple<int, bool, float, Ts...> properties.
};
using B = C<>;
using A = C<float, std::string, std::string>;
当你想到CRTP时,你几乎拥有它。
您可以执行以下操作:
// We need this boilerplate to overcome
// the incompleteness of "Derived" when instantiating "Base<Derived>"
template <typename T>
struct properties {
using type = std::tuple<>;
};
class Derived;
template <>
struct properties<Derived> {
using type = std::tuple<float, std::string, std::string>;
};
// Now that we defined our properties
template <typename Derived>
class Base {
public:
using derived_properties_t = typename properties<Derived>::type; // Should be a tuple
using base_properties_t = std::tuple<int, bool, float>;
using combined_properties_t = decltype(std::tuple_cat(std::declval<base_properties_t>(),
std::declval<derived_properties_t>()));
combined_properties_t properties;
};
class Derived : public Base<Derived> {
public:
using properties_type = std::tuple<float, std::string, std::string>;
};
您可以在Coliru上看到工作演示
相关文章:
- C++使用整数的压缩数组初始化对象
- C++17中函数模板中的静态数组初始化(MSVC 2019)
- 从另一个静态常量数组初始化静态常量数组(只需少量计算)
- 在 Python 和 c++ 2d 数组初始化之间.这是怎麽?为什么呢?
- 字节数组初始化会导致 DirectX 崩溃
- 使用 new 和 值进行数组初始化,但没有显式数量的元素
- 如何在元组初始化向量中删除样板?
- 运行时C++数组初始化问题
- 使用带有参数包的数组的成员数组初始化类
- 仅通过C++中数组初始化的不同方法,即可在同一输入上获得两个不同的答案
- C++ 2 个指针数组初始化 C2440
- C++结构字符数组初始化
- C++中的多维数组初始化
- constexpr数组初始化
- C++引物动态数组初始化程序的数目超过大小
- 使用std::index_sequence对std::数组初始化进行包扩展
- C++ 基元类型初始化与对象初始化
- 当 std 数组初始化太小时,C++会引发错误吗?
- 为什么在元组初始化中构造对象
- 创建一个用 0,1,2,3, 元组初始化的多维数组