对于具有两个模板化变量的模板类,可以使一个var引用另一个var? [英] for a templated class with two templated variable, can one var be made to reference the other var?

查看:85
本文介绍了对于具有两个模板化变量的模板类,可以使一个var引用另一个var?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来引用A的t从真正的类型B和C.在下面的代码中,你看到我的第一个倾向是尝试并初始化它。其他尝试我尝试使用完美的转发,继承和添加更多的模板参数到B和C.有人可以建议一个路径前进?有什么新的方法可能有帮助吗?我是关闭还是不可能?

I am looking for a way to reference A's t from within real types B and C. In the code below you see that my first inclination is to try and initialize it. Other attempts I have tried were using perfect forwarding, inheritance and adding more templates parameters to B and C. Can someone suggest a path forward? Are there new constructs on the way that may help? Am I close or is this impossible?

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;
}


推荐答案

是模板模板参数。

这是他的代码一次审查:

I think what the OP wants is a template template parameter.
Here is his code once reviewed:

#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;
}

这篇关于对于具有两个模板化变量的模板类,可以使一个var引用另一个var?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆