【问题标题】:How to pass a template function in a template argument list如何在模板参数列表中传递模板函数
【发布时间】:2021-09-26 04:39:08
【问题描述】:

假设我有一个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 >()();

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

【问题讨论】:

    标签: c++ templates c++11 function-templates


    【解决方案1】:

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

    是的,就是这样,您不能将函数模板作为模板参数传递。从 14.3.3 开始:

    模板模板参数的模板参数应为 类模板或别名模板的名称,表示为 id 表达式。

    模板函数需要在之前实例化你将它传递给另一个模板。一种可能的解决方案是传递一个包含静态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);
    

    【讨论】:

    • 模板模板参数不能是函数模板有什么根本原因吗?将来可能会解决这个问题吗?
    • @Olumide:可能是因为它有很多额外的复杂性并且易于解决(请参阅 mfontanini 的回答)。部分特化也是如此,它的使用比模板模板参数要多得多。
    【解决方案2】:

    包装那个函数怎么样?

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

    然后你可以使用包装器代替函数:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-24
      • 1970-01-01
      • 2011-10-03
      • 1970-01-01
      • 1970-01-01
      • 2011-10-13
      相关资源
      最近更新 更多