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.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++ templates are a powerful feature of the C++ programming language that allow for generic programming. Templates allow developers to write code that works with a wide range of data types, without having to write separate code for each individual type. Templates are defined using the keyword "template", followed by a list of template parameters within angle brackets. These parameters can be data types, values, or other templates. For example, a simple template function that adds two numbers could be written as: ``` template <typename T> T add(T a, T b) { return a + b; } ``` In this example, the template parameter "T" is used to represent the data type of the variables a and b. The function can be called with any data type that supports the "+" operator, such as int, float, or even custom classes that define their own operator overloads. Templates can also be used to define classes, which can be useful for creating generic data structures or algorithms. For example, a template class for a dynamic array could be written as: ``` template <typename T> class DynamicArray { private: T* data; int size; public: // constructor, destructor, and other methods // ... }; ``` In this example, the template parameter "T" is used to represent the data type stored in the dynamic array. The class can be instantiated with any data type, and the data array will be allocated accordingly. Overall, templates are a powerful tool for creating flexible and reusable code in C++. However, they can also be complex and difficult to understand, so they should be used judiciously and with care.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值