【发布时间】:2026-01-30 15:50:02
【问题描述】:
我有一些我想使用函数指针调用的函数。它们有不同的参数和数据类型。
void processVec2(
float a,
float b,
array<vector2> vec2_array,
int i,
int j)
{
/// some code here
}
void processVec3(
float a,
float b,
float c,
float d,
array<vector3> vec3_array,
int i,
int j)
{
/// some code here
}
我想在循环 lunction 中传递函数,并且我想在调用传递的函数之前添加循环迭代索引作为参数。
template<typename T, typename ... Args>
void loopFunction(
int iter,
array<T> array,
void (*function)(Args)
)
{
// loop on iter
for(int i = 0; i < iter; ++i)
{
// Loop on input array size
int arraySize = array.size()
for(int j = 0; j < arraySize, ++j)
{
function(args, i, j) // calling function. I want to pass some arguments and also i and j.
}
}
}
这就是我要设置函数指针的地方。但是,我不知道如何让它接受它的变量,而且我不能在主函数中设置循环索引变量,所以函数指针的参数都会丢失两个 int。
// Main function
void main(
float a,
float b,
float c,
float d,
int vec2_iter,
int vec3_iter,
array<vector2> vec2_array,
array<vector3> vec3_array)
{
// Call loopFunction, passing processVec2 as function pointer argument. I need to set the function's argument here too.
loopFunction<vector2>(vec2_iter, vec2_array, &processVec2(a, b vec2_array));
// Call loopFunction, passing processVec3 as function pointer argument. I need to set the function's argument here too.
loopFunction<vector3>(vec3_iter, vec3_array, &processVec3(a, b, c, d, vec3_array));
}
对于循环函数,我只需要_iter、_array 和函数指针。但是,我需要将参数从主函数传递给函数指针,而不是显式地将它们传递给循环函数。
这可能吗?
【问题讨论】:
标签: c++ function arguments function-pointers variadic-templates