gpt4 book ai didi

c++ - 在给定模板参数的模板类类型的类中声明变量

转载 作者:太空狗 更新时间:2023-10-29 20:35:36 25 4
gpt4 key购买 nike

我正在尝试实例化一个包含在作为模板参数给出的类中的模板类。通过示例可能更容易理解:

struct A {
static constexpr int a = 42;

class B {
int b;
};

template<typename X>
class C {
X c;
};
};

template<typename U, typename T>
class D {
int a = U::a;

using B = typename U::B;
B b;

//using C = typename U::C;
// C<T> c;
A::C<T> e;
};


int main(void) {
D<A, int> d;
return 0;
}

如果我取消对注释行的注释,编译器会给我一个错误,提示 C 不是模板。我尝试了其他方法来实例化这个变量,但没有用。我想要 e 变量的等价物,但使用 U 类型名。

最佳答案

注意你没有声明C作为模板类型,然后 C<T> c将导致错误,因为您不能将其用作模板类型。

你要的是alias template (类型族的名称),正确的语法是:

template <typename Z>
using C = typename U::template C<Z>;

然后

C<T> c;  // same as U::template C<T>; Z is substituted with T 

D<A, int> d; , U = AT = int , 然后 C<T>里面DA::C<int> 相同.

LIVE

关于c++ - 在给定模板参数的模板类类型的类中声明变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42068277/

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