gpt4 book ai didi

c++ - 对于具有两个模板变量的模板类,一个变量可以引用另一个变量吗?

转载 作者:行者123 更新时间:2023-11-28 05:39:21 25 4
gpt4 key购买 nike

我正在寻找一种从实际类型 B 和 C 中引用 A 的 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;
}

关于c++ - 对于具有两个模板变量的模板类,一个变量可以引用另一个变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37512060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com