c++ 模板函数迭代其参数

gwo2fgha  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(87)

我有两个模板函数

template <class T>
T &func1(int param, const T &component)
{
    return do_something<T>(param, component);
}

template <class T>
T &func2(int param, const T &component)
{
    return do_something_else<T>(param, component);
}

字符串
我必须使用不同的模板参数多次调用这些函数,这导致了样板代码:

auto object1 = some_func(
    [this](int param, Type1 component) { return func1<Type1>(entity, component); }, 
    [this](int param, Type2 component) { return func1<Type2>(entity, component); }
);


并且类似地

auto object2 = some_func(
    [this](int param, Type1 component) { return func2<Type1>(entity, component); }, 
    [this](int param, Type2 component) { return func2<Type2>(entity, component); }
);


显然,随着我必须这样做的类型数量的增加,这导致了许多重复。因此,我正在寻找一种方法来替换所有内容,如下所示:

auto object1 = some_template_func<Type1, Type2>(&func1);
auto object2 = some_template_func<Type1, Type2>(&func2);


我想我不得不以某种方式重写模板参数,但是我没有找到任何关于语法的信息。如果有关系的话,我使用的是C++17。

m2xkgtsf

m2xkgtsf1#

也许沿着这样的:

struct Func1Wrapper {
  template <typename T>
  T& operator()(int param, const T& component) const
  {
      return func1<T>(param, component);
  }
};
// Func2Wrapper is similar.

template <typename F, typename ... Ts>
auto some_template_func() {
  return some_func(
    [this](int param, Ts component) { return F{}(entity, component); } ...);
}

字符串
你会用它作为

auto object1 = some_template_func<Func1Wrapper, Type1, Type2>();
auto object2 = some_template_func<Func2Wrapper, Type1, Type2>();

相关问题