具有模板未定义引用错误的 C++ 继承

C++ Inheritance with templates undefined reference error

我想用多个children实现一个基础class。

基地Class

    template <typename T>
    class Trigger
    {
    protected:
        T threshold;
        Trigger(T a_threshold) : threshold(std::pow(10, a_threshold / 20)){};
    public:
        void setThreshold(T a_threshold)
        {
            threshold = std::pow(10, a_threshold / 20);
        }
        virtual bool operator()(const T &first, const T &second) const;
        virtual ~Trigger() = default;
    };

派生Class

    template <typename T>
    class ZeroCrossingRisingTrigger : public Trigger<T>
    {
    public:
        ZeroCrossingRisingTrigger(void) : Trigger<T>(0.){};

        bool operator()(const T &first, const T &second) const override
        {
            return (first <= 0) & (second > 0);
        }
    };

主文件中的用法

#include "Trigger.hpp"
int main([[maybe_unused]] int argc, [[maybe_unused]] char const *argv[])
{
    Trigger::ZeroCrossingRisingTrigger<double> trig;
    return 0;
}

但是当我尝试编译它时出现以下错误:

(...): undefined reference to `Trigger::Trigger::operator()(double const&, double const&) const'

我不明白为什么会出现此错误,因为我完全按照错误消息中的说明实现了运算符。

您还没有为 Trigger<T> 定义 operator() 的实现。一种选择是通过使运算符成员函数成为纯虚函数来使 Trigger 成为抽象基础 class:

virtual bool operator()(const T &first, const T &second) const = 0;

或者,您可以提供一个空的实现。

附带说明,在 ZeroCrossingRisingTrigger 的构造函数中,您将 0.0 作为基础 class 构造函数的参数传递。这种提示不需要 ZeroCrossingRisingTrigger 自己模板化,除非你想从外部控制 0.0 文字的类型。