让 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?我知道基类和派生类型的属性在编译时是已知的,但我似乎无法弄清楚如何组合不同继承级别的属性。
最佳答案
您可以使用 variadic templates向基类 (B
) 的 properties
成员添加更多类型。如果你希望在派生类中也有基类的构造函数,你可以使用 using-declaration :
#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);
关于c++ - 跨继承树初始化元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45409353/