【发布时间】: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<typename...> class Listener,然后在Aggregator内展开Listener<Aggregator>? -
@Human-Compiler 不确定我完全理解。你提到
Listener<Aggregator>,你是说DATA_LISTENER<Aggregator>吗? -
“但是,
DATA_LISTENER需要包含对Aggregator的引用才能返回数据。” -- why?