通过更改类型在函数之间传递模板对象

Pass template object between functions with a change of type

我有一些大型代码,我需要在其中使用模板仿函数,其中包含相互调用的函数层。问题是类型在不同阶段发生变化。下面是类型冲突问题的一个最小示例。有没有办法从 bar 调用 foo 以便函子具有必要的类型?

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
}

您可以放弃动态多态性而只使用静态多态性:

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);
}