c++ - 将相同的参数转发给 C++ 中的可变元组构造函数

标签 c++ templates constructor variadic-templates stdtuple

TL;DR如下

我正在尝试使用多核处理包编写一些 C++ 代码。该包有一个很好的发送者类,我用它在线程之间发送消息。它看起来像这样:

// structs provided by the package
struct GlobalVarsContainer {
    // some global vars
};

template<typename ...Ts>
struct sender {
    GlobalVarsContainer* my_container;
    sender (GlobalVarsContainer& c) : my_container(&c);
    void send(Ts... args) {
        // send the messages of types Ts
    };
};

这个类的构造函数实际上有点复杂,所以我希望只调用一次构造函数。 我决定对我需要的所有发件人使用容器类型,所以像这样:

typedef std::tuple<
    sender<uint32_t,uint32_t>,
    sender<uint32_t,double>,
    sender<uint32_t,double>
> sender_container_1_t;
typedef std::tuple<
    sender<uint32_t,double>,
    sender<uint32_t,double>,
    sender<uint32_t,double>
> sender_container_2_t;

现在我可以构造一个 sender_container_1_t并通过引用我的所有函数来传递它,万岁! 但这很丑陋,你必须像这样实例化容器:

GlobalVarsContainer gvc1, gvc2;
sender_container_1_t c1(gvc1, gvc1, gvc1);
sender_container_2_t c2(gvc2, gvc2, gvc2);

我想要某种形式的东西

GlobalVarsContainer gvc1, gvc2;
// Should have a tuple of senders of type sender<uint32_t,uint32_t>, sender<uint32_t,double> and sender<uint32_t,double>, all constructed with a reference to gvc as an argument.
sender_container<uint32_t,double,double> c1(gvc1);
// Should have a tuple of senders of type sender<uint32_t,double>, sender<uint32_t, double> and sender<uint32_t, double>, all constructed with a reference to gvc as an argument.
sender_container<double,double,double> c2(gvc2);

所以我想到使用可变参数容器结构,如下所示:

// My sender container
template<typename... Ts>
struct SenderContainer {
    std::tuple<sender<uint32_t, Ts>...> my_senders;
    // What to do for the constructor ?
};

但我不知道该怎么做才能做到SenderContainer<uint32_t,double,double> my_container(gvc1)这样gvc1被转发到所有发送者的构造函数。有人有提示吗?

长话短说: 如果我有一个可变结构模板

template<typename ...Ts>
struct Bar {
    Bar(Foo f){};
}

我可以制作一个以下形式的容器

template<typename ...Ts>
struct BarContainer{
    std::tuple<Bar<int,Ts>...> bars
}

这样我就可以打电话BarContainer<int, double, long> newBarContainer(f)Foo f被转发到 BarContainer::bars 的所有构造函数.

最佳答案

您可以创建虚拟结构以允许您的pack expansion :

template <typename> struct tag{};

template<typename ...Ts>
struct Bar {
    Bar(Foo f){};
};

template<typename ...Ts>
struct BarContainer{
    BarContainer(Foo f) : bars{(tag<Ts>{}, f)...} {}

    std::tuple<Bar<int,Ts>...> bars;
}

Demo

关于c++ - 将相同的参数转发给 C++ 中的可变元组构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65478164/

相关文章:

java - 运行抽象构造函数,然后转换为子类

c++ - C++中事件系统的原理是什么?

c++ - CString.Format 在 32 位中崩溃

c++ - 无法修改传递给 lua 的对象

包含 std::vector 的 C++ 模板

javascript - 我可以在 react 组件的构造函数中使用箭头函数吗?

c++ - ibmemcached 链接错误 : undefined reference to `memcached_exist'

c++ - 元编程,试图避免许多特化

c++ - 如何特化模板

c++ - 将类构造函数作为方法调用