为什么不支持从模板<类型名 T1、类型名 T2> 到模板<类型名 T1、int i> 的类专用化

Why class specialization from template<typename T1, typename T2> to template<typename T1, int i> not supported

本文关键字:类型 gt T1 lt 专用 不支持 为什么 T2 int      更新时间:2023-10-16

我想知道为什么不支持从template<typename T1, typename T2>template<typename T1, int i>的类专门化。

例如:

template<typename T1, typename T2>
struct B{};
template<typename T1>
struct B<T1, T1>{};  //ok
template<typename T1>
struct B<T1, int>{}; //ok
template<typename T1,int i>
struct B<T1,i>{}; //error:   expected a type, got 'i'
template<typename T1,constexpr int i>
struct B<T1,i>{}; //error:   expected a type, got 'i'

你的主模板需要一个类型参数,但是i不是一个类型,它是一个非类型参数。int为类型。

您可以使用std::integral_constant以某种方式将它们绑定:

template<typename T1, int i>
struct B<T1, std::integral_constant<int, i>>{};

这不是完全相同的事情,但是使用声明的可以帮助解决它:

template<typename T1, int i>
using BT = struct B<T1, std::integral_constant<int, i>>;