如何在模板参数列表中传递模板函数

Yak*_*ont 27 c++ templates function-templates c++11

假设我有一个template功能:

template<typename T>
T produce_5_function() { return T(5); }
Run Code Online (Sandbox Code Playgroud)

我怎么能将这整个传递template给另一个template

如果produce_5_function是仿函数,那就没有问题:

template<typename T>
struct produce_5_functor {
  T operator()() const { return T(5); }
};
template<template<typename T>class F>
struct client_template {
  int operator()() const { return F<int>()(); }
};
int five = client_template< produce_5_functor >()();
Run Code Online (Sandbox Code Playgroud)

但我希望能够使用原始函数模板执行此操作:

template<??? F>
struct client_template {
  int operator()() const { return F<int>(); }
};
int five = client_template< produce_5_function >()();
Run Code Online (Sandbox Code Playgroud)

我怀疑答案是"你不能这样做".

Jes*_*ood 17

我怀疑答案是"你不能这样做".

是的,就是这种情况,您不能将函数模板作为模板参数传递.从14.3.3开始:

模板template-parameter的template-argument应该是类模板或别名模板的名称,表示为id-expression.

在将模板函数传递给其他模板之前,需要实例化模板函数.一种可能的解决方案是传递一个包含静态的类类型,produce_5_function如下所示:

template<typename T>
struct Workaround {
  static T produce_5_functor() { return T(5); }
};
template<template<typename>class F>
struct client_template {
  int operator()() const { return F<int>::produce_5_functor(); }
};
int five = client_template<Workaround>()();
Run Code Online (Sandbox Code Playgroud)

使用别名模板,我可以更接近:

template <typename T>
T produce_5_functor() { return T(5); }

template <typename R>
using prod_func = R();

template<template<typename>class F>
struct client_template {
  int operator()(F<int> f) const { return f(); }
};

int five = client_template<prod_func>()(produce_5_functor);
Run Code Online (Sandbox Code Playgroud)

  • 模板模板参数不能为功能模板有根本原因吗?将来有可能解决这个问题吗? (2认同)

mfo*_*ini 5

包装那个函数怎么样?

template<typename T>
struct produce_5_function_wrapper {
    T operator()() const { return produce_5_function<T>(); }
};
Run Code Online (Sandbox Code Playgroud)

然后你可以使用包装器而不是函数:

int five = client_template< produce_5_function_wrapper >()();
Run Code Online (Sandbox Code Playgroud)

单独使用模板函数是行不通的,没有“模板模板函数”这样的东西。