在可变参数模板参数中混合类型和非类型? [英] Mixing types and nontypes in variadic template parameters?
问题描述
是否可以在可变参数模板参数中混合类型和非类型?如果我将一个 std::array
例如作为参数 T
传递给这个类,我还需要传递数组的类型和长度,但是我在下面尝试的方式在遇到值时会导致错误,因为它只需要 Types
的类型:
Is it possible to do mixing of types and nontypes in variadic template parameters? If I were to pass a std::array
for instance to this class as parameter T
, I would need to also pass a type for the array and a length, but the way I tried it below causes an error when encountering a value, because it only expects types for Types
:
template <
template<class, std::size_t> class T,
class ... Types>
class C {
T<Types...> storage;
};
int main(){
C<std::array, int, 3> c;
}
错误信息:
error: template argument for template type parameter must be a
type
Container<std::array, int, 3> c;
^
有没有办法在可变参数上下文中传递类型和值?
Is there a way to pass types and values in a variadic context?
推荐答案
如我所见,您已经对 T
类必须作为模板参数的参数的数量和类型进行了硬编码.此处不需要可变参数模板.只需这样做:
As I see, you alreadty hardcoded the number and types of parameter the class T
must take as template parameter. You don't need variadic templates here. Just do this instead:
template <
template<class, std::size_t> class T,
class A, std::size_t N>
class C {
T<A, N> storage;
};
int main(){
C<std::array, int, 3> c; // works!
}
如果你想使用可变参数模板,那么也把它放在模板模板参数中:
If you wish to use variadic templates, then put it in the template template parameter too:
template <
template<typename...> class T,
typename... Types>
class C {
T<Types...> storage;
};
如果您希望使用该版本但仍想使用 std::array
,您可以为已经具有大小的 std::array
创建别名:
If you wish to use that version but still want to use std::array
, you can create an alias to std::array
that already has a size:
template<typename T>
using array3 = std::array<T, 3>;
C<array3, int> c;
或者,您也可以创建某种模板模板别名,让您选择大小:
Alternatively, you can also create some sort of template template alias that let you choose the size:
template<std::size_t n>
struct sized_array {
template<typename T>
using array = std::array<T, n>;
};
C<sized_array<5>::array, int>;
这篇关于在可变参数模板参数中混合类型和非类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!