数组衰减为Lambda指针
Array Decays to Pointer in Lambda
template<std::size_t size>
constexpr std::size_t arraySize(int const (&)[size])
{
return size;
}
int main()
{
auto const lambda = [](int const arr[]) -> void
{
std::cout << "The length of the array is: " << arraySize(arr) << std::endl;
};
lambda({1, 2, 3});
return 0;
}
这段代码给出如下输出:
main.cpp: In lambda function:
main.cpp:23:69: error: no matching function for call to 'arraySize(const int*&)'
std::cout << "The length of the array is: " << arraySize(arr) << std::endl;
^
main.cpp:12:23: note: candidate: template<long long unsigned int size> constexpr std::size_t arraySize(const int (&)[size])
constexpr std::size_t arraySize(int const (&)[size])
^
main.cpp:12:23: note: template argument deduction/substitution failed:
main.cpp:23:69: note: mismatched types 'const int [size]' and 'const int*'
std::cout << "The length of the array is: " << arraySize(arr) << std::endl;
^
我想阻止int const arr[]
衰变为指针。如果我使用引用,它需要一个模板来获取大小,就像arraySize一样。模板不能与lambdas一起工作。这是可能的,还是我必须使用一个函数来代替,或者传递长度作为参数?
这不是衰变。衰减是指将数组类型的表达式转换为指针。
函数形参列表中的内容不是表达式;他们是声明者。在这种情况下,数组声明符将调整为指针声明符,例如:
void f(int const arr[]);
等价于:
void f(int const *arr);
lambda也不例外;lambda函数的行为类似于保存捕获变量的自定义类的成员函数。
你可以通过引用传递一个数组,以避免这种调整:
auto const lambda = [](int const (&arr)[size]) -> void
使用c++ 14泛型lambdas,该选项还通过引用接收数组:
auto const lambda = [](auto& arr) -> void
在后一种情况下,由于引用坍缩,const
也被推导出来。
据我所知,不可能让lambda 仅接受数组,但仍然推断数组的大小。
根据您希望使用的数组大小的不同,您可能需要不同的解决方案。
如果你需要的数组大小在编译时是已知的,我会考虑的一件事是使用std::array,也就是说,创建一个模板函数,生成一个适当的lambda函数,该函数接受特定大小的std::array
。并使用lambda函数来处理该大小的数组。
如果可能的数组的大小在编译时不知道,那么我想我会建议将std::vector
传递给lambda。
相关文章:
- 模板函数指针和lambda
- 如何调用存储在指向"std::函数"的指针中的 lambda?
- C++:Lambda 函数指针转换的用例是什么?
- 如何在 lambda 中访问捕获的此指针的"typeid"?
- 如何通过指针传递lambda函数?
- 使用带有 lambda 函数指针的模板
- 函数指针和 lambda 的内存管理
- 获取具有静态局部变量的绑定/推断捕获 lambda 的函数指针
- 如何组合lambda,vairadic函数和函数指针?
- C++将 lambda 函数另存为成员变量,而不使用函数指针进行优化
- Lambda 到函数指针适配器的理解
- 模板参数推导/替换失败,lambda作为函数指针
- 将引用和指针传递给 lambda
- 将捕获的 lambda 包装为模板函数中的函数指针
- 如何从 lambda 表达式中获取函数指针?
- 通过 lambda 在空指针处赋值
- 如何定义与将 Lambda 与捕获作为回调一起使用兼容的函数指针
- C++:读取 Lambda 捕获的指针时出现访问冲突
- 将转发 lambda 转换为函数指针
- 使用 OpenCV 原始指针和 lambda 作为直方图的不同结果