【问题标题】:how can I make variadic template function with a function pointer as non type argument?如何使用函数指针作为非类型参数制作可变参数模板函数?
【发布时间】:2020-02-20 05:06:42
【问题描述】:

我想要实现的是创建一个类似于以下的寺庙:

template<type R, type T, type S, auto F, class ...Fargs>
R create(T input, Fargs... fargs)
{
  S a = F(input, fargs ...);
  return some_func(a, input.b);
} 

那我想这样称呼它

int x = create<int, SomeClass, float, SomeFunc_to_apply>(2, someObj, 8.0f, 3, "whatever", "it", "needs");

【问题讨论】:

  • 您发布的代码(根据您的伪代码解释)只适用于我:gcc.godbolt.org/z/dZ3FFJ您在实现此功能时遇到了特定问题吗?
  • 我认为你的工作正常,因为你没有默认参数。
  • 这就是为什么你应该提供 mcve。(最小完整可验证示例)。

标签: c++ templates c++17


【解决方案1】:

你可以简化一点:

template <auto F, typename T, class ...Fargs>
decltype(auto) create(T input, Fargs... fargs)
{
  auto a = F(input, fargs ...);
  return some_func(a, input.b);
}

并使用它:

SomeClass someObj;
float SomeFunc_to_apply(SomeClass, float, int, const char*, const char*, const char*);
int x = create<SomeFunc_to_apply>(someObj, 8.0f, 3, "whatever", "it", "needs");

Demo

【讨论】:

  • 感谢返回时的自动技巧。但似乎 F 有默认参数。例如:func(SomeClass, float x=1.0f, int b=2, ...)。然后将模板调用为create&lt;func&gt;(someObj) 将不起作用。有什么想法吗?
  • @Wang:void func(SomeClass, float x=1.0f, int b=2) 的签名是void(SomeClass, float, int),所以你失去了默认值。你可以在 C++2a 的 lamdba 中编写它Demo
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-23
  • 2015-06-29
  • 2013-03-30
  • 1970-01-01
  • 1970-01-01
  • 2021-12-10
  • 1970-01-01
相关资源
最近更新 更多