gpt4 book ai didi

c++ - struct 旁边的 < > 是做什么的?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:22:09 24 4
gpt4 key购买 nike

好的,下面的代码是从另一个stackoverflow问题中复制过来的 here

template<typename T>
struct remove_pointer
{
typedef T type;
};

template<typename T>
struct remove_pointer<T*>
{
typedef typename remove_pointer<T>::type type;
};

虽然我知道这是模板中的递归定义,但令我困惑的是这些行

template<typename T>
struct remove_pointer<T*>

这是否意味着 remove_pointer 将导致 T=int*?为什么不 T=int**?感谢解释。

最佳答案

这是指针类型的特化。特化也可能有模板参数。所以这个模板的 type 在一般情况下只是 T 但是,如果 T 是指针类型,那么它的 type 是指针被移除的 T。给参数起一个不同的名字可能会更清楚:

template<typename T>
struct remove_pointer
{
typedef T type;
};

template<typename S>
struct remove_pointer<S*> // specialization for T = S*
{
typedef typename remove_pointer<S>::type type;
};

即在一般情况下 type 只是 T,但是如果 T 是一个指针,那么模板被实例化为 S,其中 T == S*

PS:我认为这个例子的特别之处在于特化引入了一个新的模板参数。 “正常”特化看起来像这样:

template<>
struct remove_pointer<int*> // specialization for T = int*
{
typedef typename remove_pointer<int>::type type;
};

但是,这不是很有用,因为我们希望它适用于任何类型。解决方案是在特化上引入一个额外的模板参数 (S)。 Afaik 这个附加参数必须从原始模板的参数中推导出来,在这种情况下可以推导出 S,因为 S 只是 T没有指针。

关于c++ - struct 旁边的 < > 是做什么的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40652246/

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