0

我有一个A有成员变量的类vector<B>。我想定义一个名为的函数模板DoToAll(funcPtr),它将迭代所有向量并应用该函数。

class A 
{
vector<B> v;
template <?????>
void DoToAll(f);
loop on v and apply the member function f;
}

class B{
void f1();
void f2();
.
.
.
}

我该怎么写DoToAll

4

2 回答 2

4

Do you insist that the argument must be a function pointer? Otherwise, it could be just

template <class F>
void DoToAll(F f) {
  std::for_each(v.begin(), v.end(), f);
}

That works for every f st. f(x), where x is an element of the vector, is valid. That means function pointers and functors such as std::function and std::bind are all right. Unfortunately, that doesn't include member function pointers, since you call them x->*f(), not f(). But that is possible to overcome, too, by wrapping the member function pointer into a functor that would correctly forward the call. The standard already provides such adapters, the one appropriate for you would be mem_fun_ref_t. You could add an overload of DoToAll that takes function pointers:

template <class This, class Ret>
void DoToAll(Ret (*This::f)()) {
  std::for_each(v.begin(), v.end(), std::mem_fun_ref(f));
}
于 2012-06-12T21:58:46.913 回答
0

如果在这里只使用函数,则根本不需要模板。

void DoToAll(void (*f)(B&)) { /*...*/ }

所以你可以写这样的东西

void Change(const B& what)
{
    what.ChangeSomething();
}
//...
a.DoToAll(Change) // or a.DoToAll(&Change)
于 2012-06-12T23:46:01.457 回答