简体   繁体   中英

Can I use a template function as another template's parameter?

For example I have a template function:

template <typename T>
void SizeOf() {
  std::cout << sizeof(T) << std::endl;
}

and another template function:

template <typename T, template<typename S> class F> 
void CallOn(T t) {
  ...
  F<T>();
  ...
}

now I want write code like this:

double pi = 3.14;
CallOn<double, SizeOf>(pi);

Is there anyway I can do this? If so, how to write the code?

PS The error message is:

/home/liu/source/cppsh/main.cpp:14:3: error: no matching function for call to 'CallOn'
  CallOn<double, SizeOf>(pi);
  ^~~~~~~~~~~~~~~~~~~~~~
/home/liu/source/cppsh/main.cpp:8:6: note: candidate template ignored: invalid explicitly-specified argument for template parameter 'F'
void CallOn(T t) {
     ^
1 error generated.

You cannot pass function template as argument (of function or of template).

You can pass template class as template template argument though:

template <typename T>
struct SizeOf
{
  void operator()() const {
    std::cout << sizeof(T) << std::endl;
  }
};

template <typename T, template <typename> class F> 
void CallOn(T t) {
  // ...
  F<T>{}();
  // ...
}

Another way would be to pass non-template functor with template method. In your case (no deduction from arguments as no arguments), it is less convenient (syntax would be f.operator()<T>(); ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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