[英]C++: Function template specialization for array
I tried to write a function to do whatever to a series of data. 我试着编写一个函数来对一系列数据做任何事情。
//For stl containers
template<typename T>
void foo(T x){
for(auto iter=x.begin();iter!=x.end();++iter)
do_something(*iter);
}
This function was designed to operate STL containers and it's OK. 这个功能是为了操作STL容器而设计的,没关系。 But I want another version for C-array.
但我想要另一个版本的C阵列。 So I tried this:
所以我尝试了这个:
//For C-array
template<typename T,size_t N>
void foo(T x[N]){
//blabla
}
//Error
I've read "Partial template specialization for arrays" (and several another related post), but it's for class template. 我读过“阵列的部分模板专业化” (以及其他几个相关的帖子),但它是用于类模板的。 And I also know that when you're specializing a function template, you are actually overloading it.
而且我也知道,当你专注于一个功能模板时,你实际上正在超载它。 Anyway, the solution in that post can't be implemented here.
无论如何,该帖子中的解决方案无法在此实施。
Any (or maybe no) way could I do this? 我可以做任何(或者没有)方式吗? :-) Thx for tolerating my poor English and thx for your helps.
:-)感谢你容忍我糟糕的英语和thx以获得帮助。
You miss the reference to array: 你错过了对数组的引用:
template<typename T, size_t N>
void foo(T (&x)[N]){
//blabla
}
BTW, in your case, you may simply use ( const
) reference in the generic case: 顺便说一下,在你的情况下,你可以简单地在通用情况下使用(
const
)引用:
template<typename T>
void foo(T& x){
using std::begin;
using std::end;
for (auto iter = begin(x); iter != end(x); ++iter)
do_something(*iter);
}
or even better: 甚至更好:
template<typename T>
void foo(T& x){
for (auto&& e : x)
do_something(x);
}
You could pass it by reference : 你可以通过引用传递它:
template<typename T,size_t N>
void foo(T (&x)[N]){
//blabla
}
But the true solution to your problem is to pass a pair of iterators to a single function template (working for both arrays and standard containers) : 但是问题的真正解决方案是将一对迭代器传递给单个函数模板(适用于数组和标准容器):
template<typename Iterator>
void foo(Iterator begin, Iterator end){
for(auto it = begin; it!=end; ++it)
do_something(*it);
}
int main()
{
int a[] = {1, 2, 3, 4, 5};
foo(std::begin(a) , std::end(a));
std::vector<int> v = {1, 2, 3, 4, 5};
foo(std::begin(v) , std::end(v));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.