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

Jon*_*Mee 7 c++ metaprogramming addressof decltype function-parameter

我最近得知我不能:

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

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

所以一个未定义的函数:

int foo(char, short);
Run Code Online (Sandbox Code Playgroud)

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

enable_if_t<is_same_v<tuple<char, short>, decltypeargs<foo>>, int> bar;
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮助我了解如何decltypeargs制作?

Bar*_*rry 3

对于非重载函数、函数指针和成员函数指针,只需执行即可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
Run Code Online (Sandbox Code Playgroud)

接着就,随即:

template <class T>
using decltypeargs = typename function_args<T>::type;
Run Code Online (Sandbox Code Playgroud)

这需要你写decltypeargs<decltype(foo)>


对于 C++17,我们将有template <auto>,因此上面可以是:

template <auto F>
using decltypeargs = typename function_args<decltype(F)>::type;
Run Code Online (Sandbox Code Playgroud)

你就会得到decltypeargs<foo>语法。

  • 现在可能是使用“typename”而不是“class”的好时机吗?因为你没有通过课程。它们在功能上是等效的,但可读性很重要。 (2认同)