繁体   English   中英

模板参数函数作为类成员

[英]Template argument functions as class members

我在Transforms.h定义了很多方法,如下所示:

#ifndef TRANSFORMS_H
#define TRANSFORMS_H

namespace Transforms
{
    long double asech(long double x);
    long double acsch(long double x);
    long double asechDerivative(long double x);
    long double acschDerivative(long double x);
    long double identity(long double x);
    long double identityDerivative(long double x);
};
#endif //!TRANSFORMS_H

我尝试创建一个这样的模板化类:

// Layer.h
template<typename Forward, typename Backward>
class Layer
{
protected:
    Matrix* previousActivation{ nullptr }, * error{ nullptr }, * delta{ nullptr };
    Matrix& weights;
    Vector& bias;
public:
    const int inputs, neurons;
    Forward applyActivation;
    Backward applyActivationDerivative;

    Layer(int inputs, int neurons, Matrix& weights, Vector& bias);
    ~Layer();

    Matrix& activate(Matrix& x);

    /*virtual Matrix& applyActivation(Matrix& x) = 0;
    virtual Matrix& applyActivationDerivative(Matrix& x) = 0;*/
};

尝试并能够通过这样做来创建新层

class Sigmoid: public Layer<sigmoid, sigmoidDerivative>;

这样我就不必使用纯虚拟方法进行覆盖。 但我似乎无法弄清楚如何在Layer构造函数中设置成员变量applyActivationapplyActivationDerivative

我也是 C++ 模板的新手,我来自 Java,所以请耐心等待。

您需要传递而不是类型作为模板参数。 这是一个使用您的代码的简化示例,删除了所有不必要的细节,并添加了一些方法来演示模板参数的用法。

long double sigmoid(long double x);
long double sigmoidDerivative(long double x);

using FuncT = long double(*)(long double);

template<FuncT Forward, FuncT Backward>
class Layer
{
public:
    long double applyForward(long double x) { return Forward(x); }
    long double applyBackward(long double x) { return Backward(x); }
};

class Sigmoid : public Layer<sigmoid, sigmoidDerivative> {};

演示: https : //godbolt.org/z/99h54a

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM