简体   繁体   English

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

[英]How to pass a template function in a template argument list

Suppose I have a template function:假设我有一个template函数:

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

How can I pass this entire template to another template ?如何将整个template传递给另一个template

If produce_5_function was a functor, there would be no problem:如果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 >()();

but I want to be able to do this with a raw function template:但我希望能够使用原始函数模板来做到这一点:

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

I suspect the answer is "you cannot do this".我怀疑答案是“你不能这样做”。

I suspect the answer is "you cannot do this".我怀疑答案是“你不能这样做”。

Yes, that is the case, you cannot pass a function template as a template argument.是的,就是这样,您不能将函数模板作为模板参数传递。 From 14.3.3:从 14.3.3 开始:

A template-argument for a template template-parameter shall be the name of a class template or an alias template, expressed as id-expression.模板模板参数的模板参数应是类模板或别名模板的名称,表示为 id-expression。

The template function needs to be instantiated before you pass it to the other template.在将模板函数传递给另一个模板之前,需要实例化模板函数。 One possible solution is to pass a class type that holds a static produce_5_function like so:一种可能的解决方案是传递一个类类型,它包含一个静态的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>()();

Using alias templates, I could get a little closer:使用别名模板,我可以更接近一点:

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

How about wrapping that function?包装那个函数怎么样?

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

Then you can use the wrapper instead of the function:然后你可以使用包装器而不是函数:

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

Using the template function alone will not work, there's no such thing as "template template functions".单独使用模板函数是行不通的,没有“模板模板函数”这样的东西。

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

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