我想了解更多关于C++模板的知识.我希望能够调用一个函数,我传递一个类型和长度作为参数.这可能吗?
template <class T>
void alloc_arr (int l) {
std::allocator<T[l]> a;
}
alloc_arr<int[]>(64);
Run Code Online (Sandbox Code Playgroud)
它不起作用,因为必须在编译时修复实例化类型(T[l]不固定).
有没有其他方法可以做到这一点,不需要在类型(<T[64]>)中指定长度?
有没有其他方法可以做到这一点,不需要在类型()中指定长度?
在某种程度上,您需要将其作为模板参数传递
你可以按照Lourens Dijkstra的建议明确传递它
template <typename T, std::size_t Dim>
void alloc_arr ()
{
std::allocator<T[Dim]> a;
// ...
}
Run Code Online (Sandbox Code Playgroud)
或者,如果你至少可以使用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;
// ...
}
Run Code Online (Sandbox Code Playgroud)
或者也
template <typename T, typename U>
void alloc_arr (U const &)
{
std::allocator<T[U::value]> a;
// ...
}
Run Code Online (Sandbox Code Playgroud)
alloc_arr用一个std::integral_constant<std::size_t, 5u>{}例子来呼唤.