C++: Function as template parameter, example

Function as template parameter.

Code:

#include <iostream>
template <typename F, typename D>
D Funcall(F f, D a, D b) {
  return f(a, b);
}
template <typename D>
D Add(D a, D b) {
  return a + b;
}
template <typename D>
D Sub(D a, D b) {
  return a - b;
}
int main() {
  std::cout << Funcall(Add<long int>, 3, 4) << std::endl;
  std::cout << Funcall(Sub<double>, 5.34, 2.67) << std::endl;
  return 0;
}

This piece of code is useless, just want to show the ability of template.


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章