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

前端 未结 4 1972
小鲜肉
小鲜肉 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条回答
  •  萌比男神i
    2020-12-28 17:55

    The key issues is that in C++11 you cannot do something like:

    // Doesn't compile
    template 
    static std::function)> Function;
    

    Classes and Functions can be templated, but not member properties.

    The "Magic" is:

    /*******************************************************************/
    // Define a Function Pointer in a Container
    class Storage
    {
       template 
       struct FunctionContainer {
           static std::function)> Function;
       };
    };
    /*******************************************************************/
    // Initialize FunctionContainer's Static Function Pointer if using static pointer.
    template 
    std::function)> Storage
        ::FunctionContainer::Function;
    

    You can then Bind a templated function to this function like:

    // Bind Function Pointer in Container to a Local Function
    class MyClass
    {
       template 
       void MyFunction(std::shared_ptr parameter)
       {
         // Do something.
         // You can make this templated or non-templated.
       }
       MyClass()
       {
         // If you really want, you can templatize std::string in the following:
         Storage::FunctionContainer::Function 
           = std::bind(&MyFunction, this, std::placeholders::_1);
       }
    }
    

    And you can invoke all of this and provide a templated type parameter like so:

    //Invocation
    std::shared_ptr parameter;
    parameter->get() = "Hello World".
    Storage::FunctionContainer::Function(parameter);
    

提交回复
热议问题