c++ - 确定未定义函数的参数类型

标签 c++ metaprogramming decltype function-parameter addressof

我最近了解到我不能:

  1. Take the address of an undefined function
  2. Take the address of a templatized function with a type it would fail to compile for

但我最近也了解到我可以 call decltype to get the return type of said function

所以一个未定义的函数:

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>句法。

关于c++ - 确定未定义函数的参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38457112/

相关文章:

c++ - OpenCV、C++、使用 HoughLinesP 进行线检测

c++ - printf 比 std::cout 快 5 倍以上?

c++ - MPI_广播: Stack vs Heap

recursion - 使用Julia中的元编程优化递归函数

c++ - 最佳实践 C++ 元编程 : logic flow

c++ - 如何获取当前持有的变体类型,并定义该类型的新变量

c++ - C++14 中 decltype(auto) 的转换函数

c++ - 我如何使用 unique_ptr 和 make_unique 正确声明对象数组

Ruby 的 def 和 instance_eval 与 class_eval

C++:可以使用 decltype 从我的头文件中复制类型吗?