c++ - 如何编写一个将运算符作为参数并具有默认值的函数?
问题描述
我想编写一个函数模板,其函数指针类型为可选参数,默认值为operator+
. 如果在已定义的对象上调用该函数operator+
,则使用默认值。如果在没有预定义的对象上调用该operator+
函数,则调用者可以指定一个函数来进行添加。这是我想做的一个例子:
#include <iostream>
#include <cstdlib>
#include <vector>
#include <algorithm>
template <typename T, typename fun=std::plus<T>>
T addT(T t1, T t2, fun f = {}) {
return f(t1, t2);
}
int main()
{
double a = 1., b= 2.;
auto c = addT(a, b); // use default value of std::plus
std::cout<<c<<std::endl;
using vec_int = std::vector<int>;
vec_int x = {1,1}, y = {2,2};
auto vec_int_add = [](vec_int x, vec_int y){
vec_int res;
std::transform(x.begin(), x.end(), y.begin(), std::back_inserter(res), [](int x, int y){return x+y;});
return res;
};
auto z = addT(x, y, vec_int_add); // supply a lambda as argument
std::cout<<z[0]<<','<<z[1]<<std::endl;
}
问题是默认值std::plus
仅在两个参数与上面示例的类型相同时才有效。我希望默认值是具有两种不同类型参数的函数,例如:
template<typename T>
T default_add(T x, double y) {
T res = x + y;
return res
}
我对如何做到这一点有点迷茫。
解决方案
In C++14, you might use std::plus<void>
template <typename T1, typename T2, typename fun = std::plus<void>>
auto addT(T1 t1, T2 t2, fun f = {}) {
return f(t1, t2);
}
推荐阅读
- reactjs - React.createElement:类型无效但 TypeScript 编译正确。为什么?
- r - 无法在 R Studio 中安装“ez”包
- python-3.x - KeyError: 'TCL_LIBRARY' 使用 cx_freeze 构建时
- visual-studio - 创建自己的包管理器控制台命令?
- android - 手机解锁时的启动器动画
- java - 通过不同方法处理异常进行代码重构
- r - 不能强制增益函数的结果输入“双”
- python - 模块“xml.dom”没有属性“节点”
- java - 如何使用外部 java 库在命令行中编译和运行 kotlin 程序
- mysql - 如何让这个 MySQL 查询运行得更快?