c++ - 跨继承树初始化元组

标签 c++ inheritance tuples

让 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);

Live Demo

关于c++ - 跨继承树初始化元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45409353/

相关文章:

java - 有什么方法可以测试两个 jobject 是否来自同一个类(class)?

c++ - std::streampos、std::streamoff 和 std::streamsize 到 long long int?

c++ - 继承,错误前的预期类型说明符

python - 将两个列表合并为字典时保留顺序

c++ - 如何遍历嵌套 vector ?

c++ - opencl 程序没有给出正确的输出

SetLayeredWindowAttributes 和 BitBlt 之间的 C++ WinAPI 冲突

java - 是否有支持泛型类型的 XML 模式的替代方案?

java - Java中的 super 关键字,有趣的行为,请解释

swift - 将元组数组作为 AnyObject 返回?