从重载集中调用具有特定功能的函子 [英] Call a functor with a specific function from an overload set

查看:85
本文介绍了从重载集中调用具有特定功能的函子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在与数学相关的上下文中,我想定义在<cmath>函数上使用的函子.出于此问题的目的,我们将使用 std::invoke 作为我们的函子.

In mathematics-related context, I'd like to define functors working on <cmath> functions. For the purpose of this question, we will be using std::invoke as our functor.

这是格式错误的(实时演示):

std::invoke(std::sin, 0.0);

(g ++-8.1)错误:没有匹配的函数可调用'invoke(<未解析的重载函数类型,double)'

(g++-8.1) error: no matching function for call to 'invoke(<unresolved overloaded function type>, double)'

实际上, std::sin 是一个重载集合,并且编译器缺少类型信息来选择这些功能之一.

Indeed, std::sin is an overload set and the compiler lacks the type information to choose one of those functions.

如何从重载集中命名特定功能?

How could I name a specific function from an overload set? With what could we replace LEFT and RIGHT so that the following is well-formed and does what is expected (say, select double std::sin(double))?

#include <functional>
#include <cmath>

int main()
{
    (void) std::invoke(LEFT std::sin RIGHT, 0.0);
}

如果这不可能,是否有一种方法可以定义函子,使其能够感知过载设置?

If this is not possible, is there a way to define a functor so it is overload-set-aware?

推荐答案

我知道的最简单方法是使用lambda启用过载查找

The easiest way I know to do this is to use a lambda to enable overload lookup

std::invoke([](auto val){return std::sin(val);}, 0.0);

将允许您将任何值传递给invoke,然后lambda主体将处理实际的调用,然后将提供重载解决方案.

Will allow you to pass any value to invoke and then the lambda body will handle the actual call and overload resolution will come in then.

您可以使用宏将lambda主体从对invoke的调用中提取出来,例如使用

You can use a macro to abstract the lambda body out of the call to invoke using something like

#define FUNCTORIZE(func) [](auto&&... val) noexcept(noexcept(func(std::forward<decltype(val)>(val)...))) -> decltype(auto) {return func(std::forward<decltype(val)>(val)...);}
//...
std::invoke(FUNCTORIZE(std::sin), 0.0);

这篇关于从重载集中调用具有特定功能的函子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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