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

How to pass a template function in a template argument list

本文关键字:函数 参数 列表      更新时间:2023-10-16

假设我有一个template函数:

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

如何将整个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 >()();

,但我希望能够做到这一点与一个原始的函数模板:

template<??? F>
struct client_template {
  int operator()() const { return F<int>(); }
};
int five = client_template< produce_5_function >()();

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

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

是的,就是这种情况,你不能将函数模板作为模板参数传递。14.3.3:

模板模板形参的模板实参必须是类模板或别名模板的名称,表示为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>()();

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

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);

如何包装这个函数?

template<typename T>
struct produce_5_function_wrapper {
    T operator()() const { return produce_5_function<T>(); }
};

那么您可以使用包装器而不是函数:

int five = client_template< produce_5_function_wrapper >()();

单独使用模板函数是行不通的,没有所谓的"模板模板函数"。