我有一个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
?
我有一个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
?
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));
}
如果在这里只使用函数,则根本不需要模板。
void DoToAll(void (*f)(B&)) { /*...*/ }
所以你可以写这样的东西
void Change(const B& what)
{
what.ChangeSomething();
}
//...
a.DoToAll(Change) // or a.DoToAll(&Change)