Search code examples
c++templatesc++11std-functionstdbind

In C++11, is it possible to wrap a template function in a std::function?


If i have a template function in C++11, is it then possible to wrap it in a std::function?

My problem is like this:

I have a generic function (say a sum function) where the return type depends on the types of the arguments:

template <typename T>
auto sum(T const& a, T const& b) -> decltype(a+b)
{
    return a + b;
}

and I want to wrap it in a std:function for specific argument types (say int). I'm trying the following:

int main()
{
  std::function<int(int,int)> intsum = std::bind(static_cast<int(*)(int,int)>(&sum), std::placeholders::_1, std::placeholders::_2);
  auto mysum = intsum(2, 4);

  std::cout << mysum << std::endl;

  return 0;
}

But compiling the above code produces an error:

error: invalid static_cast from type ‘<unresolved overloaded function type>’ to type ‘int (*)(int, int)

Is there some way to achieve what I am trying to do?


Solution

  • You can't wrap a generic function in a specific instance of std::function, which is what you asked for.

    You can, however, wrap a fully-specified instance of a generic function, which is what your code is actually trying to do:

    template <typename T>
    auto sum(T const& a, T const& b) -> decltype(a+b)
    {
      return a + b;
    }
    
    #include <functional>
    #include <iostream>
    
    int main()
    {
      std::function<int(int,int)> intsum =
        std::bind(sum<int>,
                  std::placeholders::_1, std::placeholders::_2);
      auto mysum = intsum(2, 4);
    
      std::cout << mysum << std::endl;
    }
    

    Or more simply

      std::function<int(int,int)> intsum = sum<int>;
    

    Or of course if you don't really need to wrap it, just:

      auto mysum = sum(2, 4);