问题描述
我正在尝试复制这个问题的答案:Selecting between valid and non-valid types,但我不知道如何使用非类型模板参数包来实现这一点。
对于上下文,我正在尝试实现一个模板化的多维数组
template<typename T,std::size_t CurrentDim,std::size_t... Dims>
class Array {
在课堂上,如果 Dims 为空,我试图创建一个 T 类型的数组,如果 Dims 不为空,我将创建一个 Array
using SubType = std::conditional<sizeof...(Dims) == 0,T,Array<T,Dims...>>;
SubType array[CurrentDim];
问题是如果 Dims 为空,则条件失败
error: too few template arguments for class template 'Array'
...因为条件的第二部分是无效的,即使检查为假也会被评估。有谁知道如何实现这一目标?我知道我可以专门研究我的 Array 类,但我相信这需要我复制我的所有代码?
这是另一个相关问题:std::conditional compile-time branch evaluation
解决方法
一种方法是部分专业化:
template<typename T,std::size_t CurrentDim,std::size_t... Dims>
class Array {
Array<T,Dims...> array[CurrentDim];
};
template<typename T,std::size_t Dim>
class Array<T,Dim> {
T array[Dim];
};