问问题
2998 次
1 回答
0
如果有人感兴趣,下面是一个可行的解决方案。然而,有重要的代码重复,我担心我无法避免它......
#include <iostream>
#include <vector>
#include <cstdlib>
#include <functional>
using namespace std;
template<typename T,typename D> T fcn_default(const D &obj, const T &phit){
return 3.2 + phit;
}
template<typename T> class Parent{
public:
Parent() {}
virtual T do_something (const T &phit) const = 0;
};
template<typename T> class Child1 : public Parent<T>{
public:
Child1() {
fcn_ptr = &fcn_default< T , Child1<T> >;
}
std::function<T(const Child1<T> &, const T &)> fcn_ptr;
T do_something(const T &phit) const {
return (*this).fcn_ptr(*this,phit);
}
};
template<typename T> class Child2 : public Parent<T>{
public:
Child2() {
fcn_ptr = &fcn_default< T , Child2<T> >;
}
std::function<T(const Child2<T> &, const T &)> fcn_ptr;
T do_something(const T &phit) const {
return (*this).fcn_ptr(*this,phit);
}
T param2;
};
template<typename T> T fcn_mod1 (const Child1<T> &obj, const T &phit){
return 1.2 + phit;
}
template<typename T> T fcn_mod2 (const Child2<T> &obj, const T &phit){
return 2.2 + phit + obj.param2*0.001;
}
typedef double lrtType;
int main(){
std::vector< Parent<lrtType> * > objects;
Child1<lrtType> *test11 = new Child1<lrtType>();
objects.push_back(test11);
Child1<lrtType> *test12 = new Child1<lrtType>();
test12->fcn_ptr = &fcn_mod1<lrtType>;
objects.push_back(test12);
Child2<lrtType> *test2 = new Child2<lrtType>();
test2->fcn_ptr = &fcn_mod2<lrtType>;
test2->param2 = 4;
objects.push_back(test2);
for (size_t i = 0; i < objects.size(); ++i) {
std::cout << objects[i]->do_something(2) << std::endl;
}
std::cout << "test" << std::endl;
}
于 2014-06-18T13:05:08.210 回答