代码之家  ›  专栏  ›  技术社区  ›  Tony

未定义对模板专用化中基类成员的引用

  •  2
  • Tony  · 技术社区  · 9 年前

    我创建了一个模板类(ABase),然后将该类扩展(添加了一些额外的功能)到派生类(a)。派生类也是专门的。然而,当我在专用派生类中引用基类中的成员时,我得到一个链接器错误,即存在对基类成员的未定义引用。

    代码布局如下:

    A基本小时:

    #include <vector>
    
    namespace A {
    
    template<typename T>
    class ABase {
    private:
        std::vector<T> items;
    public:
        ABase(){};
        void addItem(T item);
    };
    
    }
    

    ABase.cpp:

    #include "ABase.h"
    
    namespace A {
    
    template<typename T>
    void ABase<T>::addItem(T item) {
        items.push_back(item);
    }
    
    }
    

    A、 小时:

    #include <string>
    #include "ABase.h"
    
    namespace A {
    
    class A : public ABase<std::string> {
    public:
        void foo(std::string item);
    };
    
    }
    

    A、 cpp:

    namespace A {
    
    void A::foo(std::string item) {
        //do some extra stuff
        ABase::addItem(item);
    }
    template class ABase<std::string>;
    }
    

    main.cpp:

    #include <string>
    #include "A.h"
    
    using namespace std;
    
    int main() {
        A::A a;
        string item = "hello";
        a.foo(item);
    }
    

    我搜索过类似的问题,例如:

    1. Undefined reference to partial specialized template class function during link time
    2. Undefined reference to member function of template base class

    哪个建议添加

    template class ABase<std::string>;
    

    到了A.cpp的底部,然而如上所述,我已经尝试过了,但似乎不起作用。我该怎么做才能将此链接到。它确实会编译,但会返回:

    ./src/A.o: In function `A::A::foo(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)':
    /test-proj/Debug/../src/A.cpp:14: undefined reference to `A::ABase<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >::addItem(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
    collect2: ld returned 1 exit status
    make: *** [test-proj] Error 1
    

    当它链接时。谢谢你的帮助!

    1 回复  |  直到 6 年前
        1
  •  1
  •   Brandon    9 年前

    如果您将addItem的实现移动到ABase中,它应该会编译。h标题。类似于:

    #include <vector>
    
    namespace A 
    {
        template<typename T>
        class ABase 
        {
            private:
                std::vector<T> items;
            public:
                ABase(){};
                void addItem(T item)
                {
                    items.push_back(item);
                };
        };
    }
    

    ABase。cpp文件将变得多余(除非您有其他方法实现)