功能指针是否有一个下降?

问题描述 投票:0回答:1

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

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

调用foo<int, bar>()有两件事:

  1. 设置foo的返回类型与bar具有相同的返回类型
  2. 确保bar是一个接受T类型参数的函数

不幸的是,我无法访问auto模板类型,但我仍然希望完成这两个。我需要的是函数指针的decltype,这将允许我做这样的事情:

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

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

c++ function-pointers sfinae return-type declval
1个回答
2
投票

当然,函数指针没有一个declval。

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

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

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

这是一个用法示例:

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

使用检测习语的另一个例子(可在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代替。我建议模仿那些进行最无缝升级。

© www.soinside.com 2019 - 2024. All rights reserved.