Reputation: 2261
I have some large code where I need to use a templated functor with layers of functions that call each other. The problem is that the type changes at various stages. Below is a minimal example of the type conflict problem. Is there a way to call foo from bar so that the functor will have the necessary type?
template<class T>
class Functor { // Abstract base class
public:
virtual T operator() (const T &a, const T &b) = 0;
virtual ~Functor(){}
};
template<class T>
class Add : public Functor<T> {
public:
T operator() (const T &a, const T &b){ return a+b; }
};
template<class T>
void foo(Functor<T> *functor, const T& a, T &b) {
b = (*functor)(a,a);
}
template<class T>
void bar(Functor<T> *functor, const T &a, T &b ) {
int ai = (int)a;
int bi = (int)b;
// will be functor<double> when called
foo(functor,ai,bi);
b = (T)bi;
}
int main(int argc, char *argv[]){
Functor<double> *add = new Add<double> ;
double a = 1.1;
double b;
foo(add,a,b); // fine
bar(add,a,b); // error: conflicting template types
}
Upvotes: 0
Views: 128
Reputation:
You might drop dynamic polymorphism and just use static polymorphism:
struct Add {
public:
template<class T>
T operator() (const T &a, const T &b){ return a+b; }
};
template<typename Functor, typename T>
void foo(Functor* functor, const T& a, T &b) {
b = (*functor)(a,a);
}
template<typename Functor, typename T>
void bar(Functor* functor, const T &a, T &b ) {
int ai = (int)a;
int bi = (int)b;
foo(functor,ai,bi);
b = (T)bi;
}
int main(int argc, char *argv[]){
Add add;
double a = 1.1;
double b = 2.2;
foo(&add,a,b);
bar(&add,a,b);
}
Upvotes: 4