Call a functor with a specific function from an overload set

余生长醉 提交于 2019-12-05 19:34:35

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

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.

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

How could I name a specific function from an overload set?

static_cast. E.g.

std::invoke(static_cast< double(*)(double) >( &std::sin ), 0.0);

There are easier ways to do around this, e.g. use a generic lambda to avoid that horrible syntax:

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

In Qt we've been bit pretty hard by the problem of taking the address of overloaded functions up to the point that helpers have been introduced. I discussed a possible implementation of such a helper here.

Normative reference for the static_cast usage is here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!