Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

c++ - How to pass a template function in a template argument list

Suppose I have a template function:

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

How can I pass this entire template to another template?

If produce_5_function was a functor, there would be no problem:

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...