【问题标题】:Evaluate a metafunction taking a function parameter, DRY and without using a macro?评估采用函数参数 DRY 且不使用宏的元函数?
【发布时间】:2016-06-19 20:10:11
【问题描述】:

我有一个模板,它接受一些不同签名的函数作为参数,并生成一个简单签名的相关函数。细节不是很重要,它是某种代表。大致是这样的。

struct foo;

using desired_signature_t = int(*)(foo*);

template <typename F, F f>
struct make_delegate;

template <typename... Args, int(*target_func)(foo*, Args...)>
struct make_delegate<int(*)(foo*, Args...), target_func> {
   static int delegate(foo *) { ... }
};

要使用它,我目前做的是:

#define MAKE_DELEGATE(f) &make_delegate<decltype(f), (f)>::delegate

int bar(foo *, int, float, double);

desired_signature_t delegated_bar = MAKE_DELEGATE(&bar);

我使用宏是因为,我不喜欢输入两次参数,一次用于 decltype,一次用于实际函数指针。

有没有办法做到这一点,而无需输入两次,也无需使用宏?问题是无法推断出非类型模板参数的类型,并且我找不到在早期模板中首先推断出这些类型的方法。我曾想过尝试使用模板构造函数作为帮助器来构造一个文字对象,但我不确定这是否有帮助——我仍然不能使用 ctor 的参数作为 ctor 内部的模板参数,一旦我'm out of the ctor 我不知道函数类型了。

【问题讨论】:

  • Colud this 有兴趣吗?
  • 您能否详细说明您打算如何在delegate 的定义中使用target_func?此外,知道目标是什么总是很有趣,因为解决方案可能完全不同。
  • @JohanBoule:基本思想是,foo* 可以访问函数所期望的其余参数。如果可能,代理将提取它们,然后调用target_func。如果无法提取它们,则表示错误。
  • 所以我想这不是一个好问题。我想我希望找到的是一些通用的方法,我可以在type of a non-type template parameter cannot be deduced 周围工作。但是,如果有一种通用的方法来解决这个问题,那么这个限制可能就不存在了……有时在 C++ 中,它们有任意的限制和通用的解决方法,但并非总是如此,在这种情况下,我想现在似乎不太可能我……

标签: c++ templates c++11 macros


【解决方案1】:

我认为答案是,在 C++17 中使用 template &lt;auto&gt;,直到那时,继续使用宏。

Advantages of auto in template parameters in C++17

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-21
    • 1970-01-01
    • 2018-10-18
    • 2015-12-01
    • 2018-08-01
    • 1970-01-01
    • 2014-09-14
    • 1970-01-01
    相关资源
    最近更新 更多