我正在尝试用 C++ 实现一个 JavaScript 映射函数,但无法让它接受 lambda。当我使用函数指针而不是 lambda 时,它可以工作。我知道 lambda 和函数指针是不同的;我只是不明白为什么 foreach 函数很好,而 map 函数不是。
任何帮助您将不胜感激。
template<typename T>
struct List {
void* buffer;
...
void each(void(func)(T))
{
for (u32 index = 0; index < size; index += 1)
{
func(((T*)buffer)[index]);
}
}
template <typename OutType>
List<OutType> map(OutType(func)(T))
{
List<OutType> list;
for (u32 index = 0; index < size; index += 1)
{
list.push(func(((T*)buffer)[index]));
}
return list;
}
};
Run Code Online (Sandbox Code Playgroud)
使用代码:
i64 addTwo(i32 n)
{
return (i64)(n + 2);
}
int main()
{ …
Run Code Online (Sandbox Code Playgroud)