C++ : How to pass function pointer, 存储在局部变量中,作为模板参数

标签 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;
}

这是 g++ 错误:

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

据我了解,问题是局部变量没有链接;因此它不能用作模板参数。

所以,我想知道是否有办法解决这个问题或其他技术来完成同样的事情?

谢谢。

编辑 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_;
}

并称为:

w.wrap<float, float, &test1>("test1");
w.wrap<int, int, &test2>("test2");

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

编辑 2:

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

最佳答案

模板参数必须在编译时已知,因此您必须考虑到这一点重新设计代码。

编辑:对于更新后的问题,请使用 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_;
}

关于C++ : How to pass function pointer, 存储在局部变量中,作为模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6041570/

相关文章:

c++ - 多线程在QT中不起作用

c++ - 通过引用函数 C++ 传递迭代器指向的对象

C++ if 语句

c++ - 混合模板函数重载和继承

c++ - 寻找已排序的容器,其中指向元素的指针在添加/删除时不会改变

c++ - 从 unary_function 继承的谓词仿函数,它不是一个接受 1 个参数的函数

c++ - 为什么必须在哪里放置 “template”和 “typename”关键字?

C++,多次重复一个函数的输入

C 数组指针递增

C++ Getter 方法打印奇怪的数字