C++ 函数指针数组的模板
我有一些函数,其中一些是重载函数,一些是模板函数,例如:C++ 函数指针数组的模板,c++,arrays,templates,pointers,C++,Arrays,Templates,Pointers,我有一些函数,其中一些是重载函数,一些是模板函数,例如: void fun1 (vector<string> &a, int b); void fun1 (vector<double> &a, int b); template <typename t> void fun2 (t a[], int b); void fun1(向量&a,int-b); void fun1(向量&a,int-b); 模板 void fun2(t a[],int
void fun1 (vector<string> &a, int b);
void fun1 (vector<double> &a, int b);
template <typename t>
void fun2 (t a[], int b);
void fun1(向量&a,int-b);
void fun1(向量&a,int-b);
模板
void fun2(t a[],int b);
等等。我使用的每个函数都有两种数据类型的版本,一种是数组,另一种是向量(字符串向量、双精度向量、字符串数组和双精度数组)。问题是,我可以为指针数组创建一个模板吗?除了以下方法外,还有其他方法吗
void (*strvecfun[])(vector <string>&, long, long)={fun1, fun2};
void (*dblvecfun[])(vector <double>&, long, long)={fun1, fun2};
void (*strarrfun[])(string [], long, long)={fun1, fun2};
void(*strvecfun[])(向量&长,长)={fun1,fun2};
void(*dblvecfun[])(向量&,long,long)={fun1,fun2};
void(*strarrfun[])(字符串[],long,long)={fun1,fun2};
等等?您可以使用
template<typename Func>
struct func_array {
static Func *const data[];
};
template<typename Func>
Func *const func_array<Func>::data[] = { fun1, fun2 };
模板
结构函数数组{
静态函数*常量数据[];
};
模板
Func*const Func_数组::数据[]={fun1,fun2};
稍后再打电话
func_array<void(std::vector<double>&, long, long)>::data[0](dvec, l1, l2);
func_array<void(std::vector<string>&, long, long)>::data[1](svec, l1, l2);
// ...and so forth
func_数组::数据[0](dvec,l1,l2);
func_数组::数据[1](svec,l1,l2);
//……等等
当然,这需要为您将要使用的所有函数的所有签名提供匹配的重载。而不是两个实现,而是一个实现。让您的数据采用
阵列视图
:
a.size()
std::vector&
比您需要的功能强大得多。通过使用array\u view
,我们只公开您需要的内容(对元素的访问),因此可以同时获取数组和容器
如果传入“实”C样式数组,它将自动推断长度。如果您改为传入指针(或[]
真正的指针数组),则还必须传入长度,如下所示:
fun1( {ptr, length} );
创建一个名为max的函数,该函数将返回数组中最大元素的值
函数的参数应该是数组大小的地址
将此函数设置为模板,以便它可以处理任何数字类型的数组。向量a&
这是一种新语法,也可能是一种拼写错误;)<代码>[postreference]
。您是否真的在编辑这些函数中的向量的长度?或者你只是在编辑元素?如果您不需要2个重载,该怎么办?肯定是输入错误,对此表示抱歉;)不,没有长度编辑,所有的函数都是排序函数。这是我一直在寻找的。但是,有没有办法缩短调用?可以说auto&foo=func\u数组::data代码>并随后调用foo[0](dvec,l1,l2)代码>左右。还有使用
声明的。不过,您必须在某个时候解析函数类型,所以这已经是最好的了。太好了,非常感谢。这已经足够满足我的需要了哦,还有一件事-我如何将它传递给一个接受指针数组作为参数的函数?到目前为止,我已经学会了使用void函数(void(*fun[])(vector&,long),vector&tab,long n)
例如,通过上述实现,您可以编写一个函数void foo(void(*const arr[])(std::vector&,long,long))代码>和调用foo(func_数组::数据)代码>。如果你在那一点上设置了别名,那么总是会有decltype
(否则它不会让事情变得更清楚)。
void fun1 (array_view<std::string> a);
fun1( {ptr, length} );