c++ - 有没有办法在 C++ 中复合函数?

标签 c++ inheritance statistics operator-overloading

一般问题:

如果有两个对象 AB 分别具有函数 f_A(arg list)f_B(arg list).

用 f_A(...) 和 f_B(...) 的复合函数创建对象 C 的最佳方法是什么? 例如:f_C() = f_A() + f_B() 或 f_C() = f_A(f_B())

是否可以重载“+”运算符,以便我们可以创建对象 C 来做类似的事情?

auto object_c = object_a + object_b

这是我的代码示例:

class GaussianKernel : public Kernel {
        public:
            GaussianKernel(double sigma) : m_sigma(sigma), m_scale(1) {}

            double covarianceFunction(
                double   X,
                double   Y
            )
            {
                double result;

                result = m_scale  *  exp(-norm(X - Y) / (m_sigma*m_sigma));

                return result;      
            }


            GaussianKernel operator+(const GaussianKernel& b) {
            /*Here I would like to overload the + operator such that 
            I can create a kernel from two others kernels, 
            I mean with a covariance function compound of the previous ones 
            */
            }
        private:
            double m_sigma;
            double m_scale;
        };

谢谢。

最佳答案

给定两个方法 f_Af_B 你可以得到 f_C 通过使用例如 lambda 返回其他方法的总和:

auto f_C = [](/*param*/){ return f_A(/*param*/) + f_B(/*param*/); };
auto sum_result = f_C(param);

要获得复合方法,应该是这样的:

auto f_C = [](/*param*/){ return f_B( f_A(/*param*/)); };
auto compound_result = f_C(param);

PS:我知道这不能直接适用于您的示例,仍在尝试找出您到底想做什么。

关于c++ - 有没有办法在 C++ 中复合函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50719398/

相关文章:

JavaScript 原型(prototype)问题

statistics - 使用两个因变量进行回归

c++ - 矩形交点(垂直线)

java - 具有多个接口(interface)的类

c++ - Armadillo 将 wav 文件加载到 mat

android - 基类成员函数直接访问子类成员函数?

opencv - 将直方图与卡方距离进行比较

r - 使用 R 进行多重对应分析

c++ - 只有typedef的c++结构语法的含义

c++ - 在插槽断开时清除 ExtraSelections Qt