gpt4 book ai didi

c++ - 模板数组长度作为参数

转载 作者:太空宇宙 更新时间:2023-11-04 15:30:34 25 4
gpt4 key购买 nike

我想学习更多关于 C++ 模板的知识。我希望能够调用一个函数,我将类型和长度作为参数传递给它。这可能吗?

template <class T>
void alloc_arr (int l) {
std::allocator<T[l]> a;
}

alloc_arr<int[]>(64);

它不起作用,因为实例化类型必须在编译时固定(T[l] 未固定)。

有没有其他不需要在类型中指定长度的方法 ( <T[64]> )?

最佳答案

Is there some other way to do this which doesn't require the length to be specified in the type ()?

在某种程度上,你需要将它作为模板参数传递

您可以按照 Lourens Dijkstra 的建议显式传递它

template <typename T, std::size_t Dim>
void alloc_arr ()
{
std::allocator<T[Dim]> a;
// ...
}

或者,如果你至少可以使用 C++11,你也可以从参数的类型中推导出它;举例来说,

template <typename T, std::size_t Dim>
void alloc_arr (std::integral_constant<std::size_t, Dim> const &)
{
std::allocator<T[Dim]> a;
// ...
}

或者还有

template <typename T, typename U>
void alloc_arr (U const &)
{
std::allocator<T[U::value]> a;
// ...
}

调用 alloc_arrstd::integral_constant<std::size_t, 5u>{} , 例如。

关于c++ - 模板数组长度作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54445481/

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