C++ How to Reference Templated Functions using std::bind / std::function

前端 未结 4 1978
小鲜肉
小鲜肉 2020-12-28 17:30

If you have a templated class or a templated function, (or combination of the two), how do you bind that function, (preserving the template type parameter)?

I was gi

4条回答
  •  忘掉有多难
    2020-12-28 17:48

    If I understood you right... :)

    What you want to do is not possible because for template void foo(T) functions foo() and foo are of different types and you can not create vector holding pointers to both that functions directly because vector is homogeneous container.

    To overcome that we can use boost::variant<> to either store pointers to different types of functions or to store arguments of functions.

    template void foo(T);
    typedef boost::variant func_ptr_variant;
    std::vector v;
    v.push_back(foo);
    v.push_back(foo);
    
    typedef boost::variant argument;
    std::vector

    Unfortunately, in any case you will need to instantiate function templates before inserting them to container because C++ can not do code generation on the fly. I think that it is possible that you know all possible types of arguments that the function may be used with so that may be not a problem.

提交回复
热议问题