【问题标题】:Determining the Parameter Types of an Undefined Function确定未定义函数的参数类型
【发布时间】:2016-07-19 11:22:01
【问题描述】:

我最近了解到我不能:

  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 是如何制作的?

【问题讨论】:

  • @Barry 这绝不是这个问题的重复,所有答案都需要获取我的函数的地址,我明确表示我不能这样做,因为它是未定义的。请重新打开。
  • 怀疑。你认为你为什么需要这个?
  • @LightnessRacesinOrbit 是的,我也对此表示怀疑。我实际上并不关心未定义的函数。但是,能够获得无法在 SFINAE 中生存的模板化函数的函数签名对我真的很有帮助。
  • @Barry 我做了,所有人。我试过了。他们是我开始怀疑这是可能的原因。我认为没有办法将未定义的函数作为参数传递。因此,我开始认为这是不可能的。
  • @Barry:那&amp;T::operator() 做了什么?

标签: c++ metaprogramming decltype function-parameter addressof


【解决方案1】:

对于非重载函数、指向函数的指针和指向成员函数的指针,只需执行 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&lt;decltype(foo)&gt;。


在 C++17 中,我们将有 template &lt;auto&gt;,所以上面可以是:

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

你会得到decltypeargs&lt;foo&gt; 语法。

【讨论】:

  • 哇,我的心都快炸了。我对decltype 的事情一无所知。我实际上是在写一个关于如何无法完成的答案。 +1 另外,我从未见过 auto 作为模板类型说明符。这只是完美的转发吗?
  • 现在是使用typename 而不是class 的好时机吗?因为你没有通过课程。它们在功能上是等效的,但可读性很重要。
  • 所以在尝试解决这个问题以澄清我的问题后,我有几个问题:1)你说“+ C++ 14 中的几十个”仅与方法有关,对吧?我认为您的“正常功能”定义可以满足我的一切需求 2) 仅使用过 function_args 的特化。您是否选择以这种方式定义它,以便您可以使用特化来模板化传入的内容?
  • @JonathanMee 1) 成员函数。 2) 专业化可以让你分解类型,得到你需要的部分。
猜你喜欢
  • 2015-06-14
  • 1970-01-01
  • 2015-04-12
  • 1970-01-01
  • 2018-02-07
  • 2013-09-30
  • 2014-10-24
  • 2015-05-28
  • 2020-07-20
相关资源
最近更新 更多