自动变量,用于存储指向std :: max的函数指针 [英] Auto variable to store function pointer to std::max

查看:147
本文介绍了自动变量,用于存储指向std :: max的函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图将函数std::max作为模板参数传递给模板化函数,但是由于某些原因,编译器会打印无法推断出函数类型的错误.一个简单的例子也重现了同样的问题.它可以与自己的max2函数一起使用,但不能与STL std::max:

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 deduced. A simple example reproduces the same issue. It works with own max2 function but doesn't work with STL std::max:

#include <algorithm>

template <class T>
T max2(const T& a, const T& b) { return std::max(a, b); }

int main() {
#if 1
  auto f = max2<float>;
#else
  // error: unable to deduce ‘auto’ from ‘max<float>’
  auto f = std::max<float>;
#endif
  float max_val = f(1.0f, 2.0f);
  return 0;
}

推荐答案

此处所示std::max<float>不是一个明确的功能.此时,它是一个过载集,仍然有两种可能性:

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 );

您有两个主要选择:

  1. 转换为适当的类型:

  1. Cast to the appropriate type:

auto f = static_cast<const float&(*)(const float&, const float&)>(std::max);

  • 将其包装为lambda:

  • 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.
    

  • 预计将来您将能够做得更好.今天,您今天可以使用宏来模仿这样的事情(最简单的方法是将宏扩展为lambda来完成).我遇到了至少一个执行此操作的LIFT宏.

    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.

    这篇关于自动变量,用于存储指向std :: max的函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆