确定未定义函数的参数类型

Determining the Parameter Types of an Undefined Function

本文关键字:参数 类型 函数 未定义      更新时间:2023-10-16

我最近了解到我不能:

  1. 获取未定义函数的地址
  2. 获取一个模板化函数的地址,该函数的类型将无法编译

但我最近也了解到,我可以调用decltype来获得所述函数的返回类型

因此,一个未定义的函数:

int foo(char, short);

我想知道是否有一种方法可以将参数类型与tuple中的类型相匹配。这显然是一个元编程问题。在这个例子中,我真正想拍摄的是类似decltypeargs的东西:

enable_if_t<is_same_v<tuple<char, short>, decltypeargs<foo>>, int> bar;

有人能帮我理解decltypeargs是如何制作的吗?

对于非重载函数、指向函数的指针和指向成员函数的指针,只需执行decltype(function)即可在未赋值的上下文中获得函数的类型,并且该类型包含所有参数。

因此,要将参数类型作为元组,您只需要进行大量专业化:

// primary for function objects
template <class T>
struct function_args
: function_args<decltype(&T::operator()>
{ };
// normal function
template <class R, class... Args>
struct function_args<R(Args...)> {
    using type = std::tuple<Args...>;
};
// pointer to non-cv-qualified, non-ref-qualified, non-variadic member function
template <class R, class C, class... Args>
struct function_args<R (C::*)(Args...)>
: function_args<R(Args...)>
{ };
// + a few dozen more in C++14
// + a few dozen more on top of that with noexcept being part of the type system in C++17

有了这个:

template <class T>
using decltypeargs = typename function_args<T>::type;

这需要您编写decltypeargs<decltype(foo)>


有了C++17,我们将有template <auto>,所以上面可以是:

template <auto F>
using decltypeargs = typename function_args<decltype(F)>::type;

你会得到decltypeargs<foo>语法。