Mar*_* R. 1 c++ arrays delegates function-pointers
我有一个关于c ++和数组的问题.
假设我有一个名为CustomArray的类,它只不过是具有大小和容量属性的通用数组,以使数组动态化.定义为:
template<typename T>
class CustomArray
{
public:
int capacity, size;
T* items;
//constructor
//destructor
//function1
//function2
//etc...
};
Run Code Online (Sandbox Code Playgroud)
现在我有点卡住,我想实现一个像以下的功能:"
void performOnAllItems(/*function?*/)
{
for(int i = 0; i < size; i++)
{
//perform function on element
}
}
Run Code Online (Sandbox Code Playgroud)
将另一个函数作为参数(如果可能的话?)并在所有元素上执行它.那可能吗?如果是的话......怎么样?
提前致谢.
添加成员begin,end如下所示:
T *begin() { return items; }
T *end() { return items + size; }
Run Code Online (Sandbox Code Playgroud)
创建一个源自的仿函数std::unary_function.
例如
template <typename T>
class MyFunc : std::unary_function<T, void> {
public:
void operator()(T& t) {
// ...
}
};
Run Code Online (Sandbox Code Playgroud)
然后打电话 std::foreach(foo.begin(), foo.end(), MyFunc);
更新
在C++ 11中,您可以将lambda用于foreach:
std::foreach(foo.begin(), foo.end(),
[/* (1) */](T& t) { /* ... */ }
);
Run Code Online (Sandbox Code Playgroud)
如果(1)不为空,则lambda是一个闭包; 这被称为捕获lambda,而Visual C++ 10 Lambda Expressions提供了一个很好的例子.
template<class functionptr>
void performOnAllItems(functionptr ptr)
{
for(int i = 0; i < size; i++)
ptr(items[i]);
}
Run Code Online (Sandbox Code Playgroud)
要么
typedef void (*functionptr)(T&);
void performOnAllItems(functionptr ptr)
{
for(int i = 0; i < size; i++)
ptr(items[i]);
}
Run Code Online (Sandbox Code Playgroud)
第二个极大地限制了可以使用哪些功能,但第一个不能.