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

前端 未结 4 1974
小鲜肉
小鲜肉 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:41

    The template argument for std::function should be the signature of the function after template type substitution has been done. In your case, neither TemplateType nor FunctionTemplateType have an effect on the signature of the member function MyFunction - it will always return a std::string and take a single std::string argument. Therefore, the std::function you're going to store in your std::vector should be:

    static std::vector> Functions;
    

    Recall that a member function has an implicit first argument this. You need to bind the first argument of MyClass<...>::MyFunc<...> to the object you want it to be called on. Presumably, since you're binding the function in MyClass's constructor, you want the object to be that MyClass instance. That means your push_back should look like this:

    Storage::Functions.push_back(
      std::bind(&MyClass::MyFunction, this,
        std::placeholders::_1)
    );
    

    Now the function that is pushed into Functions is bound to your MyClass object and takes a single argument of type std::string. You can call one of these functions like so:

    Storage::Functions[0]("something");
    

提交回复
热议问题