【问题标题】:Circular template argument list between circular dependency class members producer/consumer循环依赖类成员生产者/消费者之间的循环模板参数列表
【发布时间】:2021-07-07 10:24:19
【问题描述】:

我在两个模板类之间存在循环依赖关系。

Aggregator 包含模板参数类型DATA_LISTENER 的类成员。但是,DATA_LISTENER 需要包含对Aggregator 的引用才能返回数据。这意味着我不能为每个定义模板,因为它们都需要另一个。

什么是最好的解决方案? Listener1 需要在Aggregator 内部传递,因为我有多个数据源,它们需要在这里聚合,但Aggregator 需要通用才能接受不同的DATA_LISTENERs。

int main()
{
    Aggregator<int, double, Listener1<Aggregator....????>> my_obj;  // Problem: cannot define Aggregator without Listener1
}

template<class NA, class ABC, class DATA_LISTENER>
struct Aggregator
{
   Aggregator() : _sd(*this){}

   void receiveData(int f)
   {
        std::cout << "Received data from SD" << std::endl;
   }

   DATA_LISTENER<Aggregator<NA, ABC, ?????>> _sd;    // Problem cannot define DATA_LISTENER without Aggregator
   NA _na;
   ABC _abc;
};

template<class DESTINATION>
struct Listener1
{
    Listener1(DEST& destination) : _destination(destination){}

    void receiveData(int f)
    {
        _dest.receiveData(f);
    }

    DESTINATION& _destination;
};

【问题讨论】:

  • Aggregator 可以接受template template 参数吗?如传入template&lt;typename...&gt; class Listener,然后在Aggregator 内展开Listener&lt;Aggregator&gt;
  • @Human-Compiler 不确定我完全理解。你提到Listener&lt;Aggregator&gt;,你是说DATA_LISTENER&lt;Aggregator&gt;吗?
  • “但是,DATA_LISTENER 需要包含对 Aggregator 的引用才能返回数据。” -- why?

标签: c++ templates


【解决方案1】:

Aggregator 的第三个模板参数应该是模板参数,而不是类型参数。将其作为模板参数会导致其他所有内容都到位。

template<class NA, class ABC, template<typename> class DATA_LISTENER>
struct Aggregator
{
   Aggregator() : _sd(*this){}

   void receiveData(int f)
   {
   }

   DATA_LISTENER<Aggregator> _sd;
   NA _na;
   ABC _abc;
};

template<class DESTINATION>
struct Listener1
{
    Listener1(DESTINATION& destination) : _destination(destination){}

    void receiveData(int f)
    {
        _destination.receiveData(f);
    }

    DESTINATION& _destination;
};



int main()
{
    Aggregator<int, double, Listener1> my_obj;
}

Live link

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-26
    • 1970-01-01
    • 2017-04-07
    • 1970-01-01
    • 1970-01-01
    • 2019-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多