你可以使用这样的函子
template <typename T, T* MyType::* TMember, void (T::* TNestedMember)() >
struct Caller {
Caller() {
}
template <typename TObject>
void operator()(TObject object) {
(object.*TMember->*TNestedMember)();
}
};
解决您的问题
struct MyNestedType {
MyNestedType(int a):
a_(a){
}
void func() {
std::cout << "MyNestedType::func " << a_ << std::endl;
}
void foo() {
std::cout << "MyNestedType::foo " << a_ << std::endl;
}
int a_;
};
struct MyType {
MyNestedType* nested;
};
int main()
{
std::vector<MyType> vec;
std::auto_ptr<MyNestedType> nt1(new MyNestedType(2));
std::auto_ptr<MyNestedType> nt2(new MyNestedType(5));
MyType t1 = {nt1.get()};
MyType t2 = {nt2.get()};
vec.push_back(t1);
vec.push_back(t2);
std::for_each(vec.begin(), vec.end(),
Caller<MyNestedType, &MyType::nested, &MyNestedType::func>());
std::for_each(vec.begin(), vec.end(),
Caller<MyNestedType, &MyType::nested, &MyNestedType::foo>());
}