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

时间:2015-01-16 17:49:53

标签: c++ templates casting type-conversion

我有一些大型代码,我需要使用模板化函数,其中包含相互调用的函数层。问题是类型在不同阶段发生变化。下面是类型冲突问题的最小示例。有没有办法从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
}

1 个答案:

答案 0 :(得分:4)

您可能会删除动态多态并只使用静态多态:

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