首页 > 解决方案 > 如何编写一个将运算符作为参数并具有默认值的函数?

问题描述

我想编写一个函数模板,其函数指针类型为可选参数,默认值为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
}

我对如何做到这一点有点迷茫。

标签: c++operator-keywordfunction-templates

解决方案


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

Demo


推荐阅读