繁体   English   中英

将函数模板转换为模板化仿函数

[英]Convert function template into templated functor

我想知道是否可以从函数模板创建函数对象。 以下Functor结构从函数创建函数对象:

#include <iostream>

template <typename F, F* f>
struct Functor {
  template <typename... Ar>
  auto operator()(Ar&&... rg) -> decltype(f(std::forward<Ar>(rg)...)) {
    return f(std::forward<Ar>(rg)...);
  }
};

int plus_one(int a) {
  return a + 1;
}

int main () {

  std::cout << Functor<decltype(plus_one), &plus_one>()(1) << "\n";

  return 0;
}

这样就形成了一种结构

struct PlusOne {
  int operator()(int a) {
    return a + 1;
  }
}

现在,我想使用函数模板而不是函数:

template <typename T>
T plus_one(T a) {
  return a + 1;
}

我希望变成类似的东西

struct PlusOne {
  template <class T>
  T operator()(T a) {
    return a + 1;
  }
};

这可能吗? 我问这个的原因之一是我在C ++ 14中读取泛型lambda表达式正在变成类似于我之后的仿函数:

例如,这个包含语句的通用lambda表达式:

  auto L = [](const auto& x, auto& y){ return x + y; }; 

可能会导致创建一个闭包类型,并且该对象的行为类似于下面的结构:

 struct { template <typename T, typename U> auto operator()(const T& x, U& y) const { return x + y; } } L; 

所以我天真地希望有一些设施可以让我成为可能,我可能会存在。 我只限于C ++ 11。

不,这是不可能的。 模板名称本身可以以非常有限的方式使用。 在传递它之前,你必须将它包装在一个类中。 在C ++ 14中,使用lambda来包装对函数的调用似乎是最简单的方法。 然后你可以在很多方面使用它:

auto wrapper = [](const auto& x){ return plus_one(x); }

std::cout << wrapper(42) << "\n";
std::cout << std::invoke(wrapper, 42) << "\n";
std::cout << std::bind(wrapper, 42)() << "\n";
// etc.

在C ++ 11中,我们有点搞砸了。 我们必须自己编写包装器:

struct Wrapper {
    template <typename T>
    auto operator()(const T& x) const
    {
        return plus_one(x);
    }
};

然后

Wrapper wrapper;
// same usage

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM