如果GetObject() 可以返回不同的类型,那么您将需要使用模板。像这样的:
template <class T>
int Foo(const T &o) {
return o->GetValue(x, y);
}
int Bar() {
return Foo(GetObject());
}
这基本上是,编译时多态
编辑:
如果您还需要指定要调用的函数,则可以执行以下操作:
template <class T, int (T::*F)(int,int)>
int Foo(const T &o) {
return (o->*F)(x, y);
}
int Bar() {
// there is probably some template magic you can do to avoid knowing "Type" here..
return Foo<Type, &Type::GetValue>(GetObject());
}
编辑:
这归结为,您可以编写如下代码:
#include <iostream>
struct A {
int GetValue(int x, int y) {
return 42;
}
};
struct B {
int GetValue(int x, int y) {
return 123;
}
};
template <class T, int (T::*F)(int,int)>
int Foo(T &o) {
return (o.*F)(0, 1);
}
int main() {
A a;
B b;
std::cout << Foo<A, &A::GetValue>(a) << std::endl;
std::cout << Foo<B, &B::GetValue>(b) << std::endl;
}
类型 A 和 B 是不相关的,但我可以将一个通用处理程序传递给两者。问题是,为什么这是必要的?为什么不做这样的事情(避免整个混乱):
#include <iostream>
struct A {
int GetValue(int x, int y) {
return 42;
}
};
struct B {
int GetValue(int x, int y) {
return 123;
}
};
int Foo(int x) {
return x
}
int main() {
A a;
B b;
std::cout << Foo(a.GetValue()) << std::endl;
std::cout << Foo(b.GetValue()) << std::endl;
}
我看不出将类型、对象和要调用的函数全部由模板确定可以得到什么,也可以直接执行,或者使用一些简单的薄包装器。
另外,为什么不让GetObject 返回的所有类型都使用它们继承自的公共接口,这样您就可以按预期使用虚函数?这有点“代码味道”...