How to pass a template function in a template argument list

后端 未结 2 683
温柔的废话
温柔的废话 2020-12-01 11:59

Suppose I have a template function:

template
T produce_5_function() { return T(5); }

How can I pass this ent

相关标签:
2条回答
  • 2020-12-01 12:51

    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:

    A template-argument for a template template-parameter shall be the name of a class template or an alias template, expressed as 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:

    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);
    
    0 讨论(0)
  • 2020-12-01 12:54

    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".

    0 讨论(0)
提交回复
热议问题