Auto variable to store function pointer to std::max

前端 未结 2 1396
南笙
南笙 2021-01-20 11:28

I\'m trying to pass function std::max as template parameter to a templated function, but for some reasons compiler prints error that function type cannot be ded

相关标签:
2条回答
  • 2021-01-20 11:57

    As seen here, std::max<float> isn't a single, unambiguous function. At this point, it's an overload set and there are still two possibilities:

    constexpr const float& max( const float& a, const float& b );
    constexpr float max( std::initializer_list<float> ilist );
    

    You have two main options:

    1. Cast to the appropriate type:

      auto f = static_cast<const float&(*)(const float&, const float&)>(std::max);
      
    2. Wrap it in a lambda:

      auto f = [](float a, float b) { return std::max(a, b); };
      // Note there's no by-reference behaviour in this lambda.
      

    In the future, it is expected that you will be able to do better. Today, you could emulate such a thing today with a macro (most simply done by making the macro expand into a lambda). I've come across at least one LIFT macro that does this.

    0 讨论(0)
  • 2021-01-20 11:59

    std::max has more than one template overloads; you can use static_cast to specify which one should be used.

    static_cast may also be used to disambiguate function overloads by performing a function-to-pointer conversion to specific type

    e.g.

    auto f = static_cast<const float& (*)(const float&, const float&)>(std::max<float>);
    
    0 讨论(0)
提交回复
热议问题