功能指针是否有declval? [英] Is There a declval for Function Pointers?

查看:87
本文介绍了功能指针是否有declval?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,我需要测试是否可以将给定类型的参数传递给它.例如:

I have a function and I need to test whether I can pass an argument of a given type to it. For example:

template<typename T, auto F>
decltype(F(declval<T>{})) foo();

呼叫foo<int, bar>()有两件事:

  1. 设置foo的返回类型将具有与bar相同的返回类型
  2. 确保bar是接受参数的函数 输入T
  1. Sets the return type of foo would have the same return type as bar
  2. Ensures that bar is a function that accepts an argument of type T

不幸的是,我没有访问auto模板类型的权限,但是我仍然想同时实现这两种功能.我需要的是用于函数指针的decltype,这将允许我执行以下操作:

Unfortunately I don't have access to auto template types, but I still want to accomplish both of these. What I need is a decltype for function pointers, which would allow me to do something like this:

template <typename T, typename F>
decltype(declval<F>(declval<T>{})) foo();

所以我仍然可以调用foo<int, bar>()并获得相同的结果.当然,函数指针没有declval.但是我还有另一种方法可以做到这一点吗?

So I could still call foo<int, bar>() and get the same result. Of course there isn't a declval for function pointers. But is there another way I could accomplish this?

推荐答案

当然,函数指针没有declval.

Of course there isn't a declval for function pointers.

你是什么意思? std::declval与函数指针类型完美配合:

What do you mean? std::declval works perfectly with function pointer types:

template<typename F, typename... Args>
using call_t = decltype(std::declval<F>()(std::declval<Args>()...));

在此示例中,F可以是函数指针类型,lambda类型或任何可调用类型.

In this example, F can be a function pointer type, a lambda type or any callable types.

这是用法示例:

template<typename T, typename F>
auto foo() -> call_t<F, T>;

另一个使用检测习惯用法的示例(可在C ++ 11中实现):

Another example using the detection idiom (implementable in C++11):

template<typename F, typename... Args>
using is_callable = is_detected<call_t, F, Args...>;

static_assert(is_callable<void(*)(int), int>::value, "callable")


请注意,所有这些都可以在C ++ 17中用std::invoke_result_tstd::is_invocable代替.我建议模仿那些具有最无缝的升级.


Note that all this can be replaced by std::invoke_result_t and std::is_invocable in C++17. I'd suggest mimicking those to have the most seamless upgrade.

这篇关于功能指针是否有declval?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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