C++:如何将存储在局部变量中的函数指针作为模板参数传递

Cod*_*eak 4 c++ templates pointers callback

using namespace std;

float test1(float i){
    return i * i;
}

int test2(int i){
    return i+9;
}

struct Wrapper{

    typedef void (*wrapper_type)(int);

    template<class R, class A>
    void wrap(string name,R (*fn) (A) ){
        wrapper_type f_ = &Wrapper::wrapper1<R,A,fn>;
        // in the real program, f_ would be passed in an array to some c library
        wrappers[name] = f_;
    }

    void run(int i){
        map<string,wrapper_type>::iterator it, end = wrappers.end();
        for(it=wrappers.begin();it!=end;it++){
            wrapper_type wt = (*it).second;
            (*wt)(i);
        }
    }

    template<class R, class A, R (*fn) (A)>
    static void wrapper1(int mul){
        //do something
        A arg = mul;
        R result = (*fn)( arg );
        cout << "Result: " << result << endl;
    }

    map<string,wrapper_type> wrappers;

};

int main(int argc, char** argv) {
    Wrapper w;
    w.wrap("test1",&test1);
    w.wrap("test2",&test2);
    w.run(89);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是g ++错误:

main.cpp:31: error: ‘fn’ is not a valid template argument for type ‘float (*)(float)’ because function ‘fn’ has not external linkage
Run Code Online (Sandbox Code Playgroud)

据我所知,问题是局部变量没有联系; 因此它不能用作模板参数.

所以,我想知道是否有办法解决这个问题或其他技术来实现同样的目标?

谢谢.

编辑1:

我完全理解我无法将在编译时无法确定的值作为模板参数传递.我要问的是 - 有更好的方法吗?现在,适合我的解决方案是:

template<class R, class A,R (*fn) (A)>
void wrap(string name){
    wrapper_type f_ = &Wrapper::wrapper1<R,A,fn>;
    // in the real program, f_ would be passed in an array to sm c library
    wrappers[name] = f_;
}
Run Code Online (Sandbox Code Playgroud)

并称为:

w.wrap<float, float, &test1>("test1");
w.wrap<int, int, &test2>("test2");
Run Code Online (Sandbox Code Playgroud)

但是在这里我要在包装期间传递参数类型.有什么办法可以避免这种情况吗?

编辑2:

只是为了澄清或添加更多信息:我想要呈现给用户的接口必须类似于LuaBind或Boost.Python,即Wrapper.wrap("test1",&test1); 应该足够了.

APr*_*mer 7

必须在编译时知道模板参数,因此您必须重新设计代码并将其考虑在内.

编辑:对于您更新的问题,请使用Boost function_traits.

template<R (*fn) (A)>
void wrap(string name){
    wrapper_type f_ = &Wrapper::wrapper1<function_traits<A>::result_type, function_traits<A>::arg1_type,fn>;
    // in the real program, f_ would be passed in an array to sm c library
    wrappers[name] = f_;
}
Run Code Online (Sandbox Code Playgroud)