Search code examples
c++c++11std-function

std::function cannot deduce overloaded type in template instance


I have this fairly simple template class :

template <typename Value>
struct Foo {
    typedef Value ValueType;
    Value array[3];
};

Now I am trying to get a function object (std::function) from a simple function using the dependent type of F as function argument and return types.

template <typename F>
void floorfunc(const F& foo) {
    typedef typename F::ValueType Value;
    auto fptr = std::function<Value(Value)>(std::floor);
}

The compiler correctly instantiates the Value types but fails to guess the correct function overload of floor, and sends me this error message

error: no matching function for call to 'std::function<float(float)>::function(<unresolved overloaded function type>

How do I tell the compiler wich overload needs to be used in that case ?


Solution

  • Add a cast:

    std::function<Value(Value)>(static_cast<Value(&)(Value)>(std::floor))
    

    std::floor is overloaded, and the constructor of std::function is a template, so there's no obvious choice of overload and you have to specify it explicitly, which you can do with the cast.