[英]Is there a way to create function template specialization for std::array
I have a function template 我有一个功能模板
template<typename T>
void output(T& value)
{
}
Is there a way to create specialization for output std::array objects? 有没有一种方法可以为输出std :: array对象创建专用化? Yes, I know, that arrays of different sizes are different types.
是的,我知道,不同大小的数组是不同的类型。 ) I just hope that there is a way in c++11
)我只是希望c ++ 11中有办法
template<class T, unsigned N>
void output(std::array<T,N>& value){
}
Would be what you should be using, since specializations are discouraged. 因为不鼓励专业化,所以您将要使用它。 Moreover, you can't partially specialize function templates.
而且,您不能部分专门化功能模板。
You can't specialize it for all arrays, that would require a "partial specialization" of the template. 您不能对所有数组都进行专门化,这需要模板的“部分专门化”。 A full specialization of a template pins down the values of all template parameters (in this case there is only one,
T
, so a full specialization only covers one type in place of T
). 模板的完全专业化会固定所有模板参数的值(在这种情况下,只有一个
T
,因此完全专业化只能覆盖一种类型来代替T
)。 A partial specialization covers multiple possible values of the template parameters (in this case we want to cover any std::array<U,N>
in place of T
), so a partial specialization has template parameters of its own. 部分专业化涵盖模板参数的多个可能值(在这种情况下,我们要覆盖任何
std::array<U,N>
代替T
),因此部分专业化具有自己的模板参数。
C++ permits partial specialization of class templates but not of function templates. C ++允许对类模板进行部分专业化,但不允许对功能模板进行部分专业化。
Instead, you can overload it. 相反,您可以使其过载。 You define another function template with the same name and different parameters:
您定义了另一个具有相同名称和不同参数的功能模板:
template <typename T, size_t N>
void output (const std::array<T,N> &arr); // I guess "const" by the function name
You need an overload , not a specialization (there's just full specialization for function templates). 您需要重载 ,而不是专门化(功能模板只有完全专门化)。
template <typename T, size_t N>
void output (std::array<T,N> &arr);
You are not allowed to put it into namespace std
though. 但是,您不允许将其放入
namespace std
。 And if it just outputs data, you should not pass a non-const reference. 而且,如果仅输出数据,则不应传递非常量引用。
However, go the route the standard library goes, and use iterators instead: 但是,请遵循标准库所遵循的路线,而应使用迭代器:
template <typename Iter>
void output (Iter it, Iter end)
This makes your function flexible wrt the container type: It probably does not need to know whether it's a list
, deque
or an array
. 这使您的函数可以灵活使用容器类型:可能不需要知道它是
list
, deque
还是array
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.