对于具有两个模板化变量的模板化类,是否可以使一个 var 引用另一个 var

for a templated class with two templated variable, can one var be made to reference the other var?

本文关键字:var 可以使 一个 引用 另一个 是否 于具 两个 变量      更新时间:2023-10-16

我正在寻找一种从实际类型B和C中引用A's t的方法。在下面的代码中,你可以看到我的第一个倾向是尝试初始化它。我尝试过的其他尝试是使用完美的转发、继承和向 B 和 C 添加更多模板参数。有人可以提出前进的道路吗?是否有新的结构可能会有所帮助?我接近还是不可能?

struct D {};
struct E {};
template< typename U1 > 
struct B 
{
  B() : u1(???)
  U1& u1; // how to reference A's t variable?
};
template< typename U2 > 
struct C 
{ 
  C() : u2(???)
  U2& u2; // how to reference A's t variable?
};
template< typename T, typename U >
struct A
{
  T t;
  U u;
};
int main()
{
  A< D, B< D > > a1;
  A< E, C< E > > a2;
  return 0;
}

我认为OP想要的是一个模板模板参数。
以下是他曾经审查过的代码:

#include<memory>
struct D {};
struct E {};
template< typename U > 
struct B 
{
    B(std::shared_ptr<U> v) : u{v} {}
    std::shared_ptr<U> u;
};
template< typename U > 
struct C 
{ 
    C(std::shared_ptr<U> v) : u{v} {}
    std::shared_ptr<U> u;
};
template< typename T, template<typename> typename U >
struct A
{
    A(): t{std::make_shared<T>()}, u{t} {}
    std::shared_ptr<T> t;
    U<T> u;
};
int main()
{
    A< D, B > a1;
    A< E, C > a2;
    return 0;
}