如何在基类(不是模板类)中调用c++模板函数

how to call c++ template function in base class(not template class)

本文关键字:调用 c++ 函数 基类      更新时间:2023-10-16

链接时下面的调用者说未定义引用…

在base.h文件:

class tempc {
    public:
    int a;
} ;
class base                 // base class
{
    public:                // public
    template<T> int func(T*);     //  template defined here
};

base.cpp文件:

template<T>
int base :: func(T*)
{
    std::cout << "base::func called" << std::endl;
    return 0;
}

在derived.cpp文件

class derived : public: base    // class defined
{
     void  caller()
    { 
        tempc a;
        func<tempc>(&a);    // template used here
        base::func<tempc>(&a);
    }
};
int main()
{
    derived d;
    d.caller();
}

错误是:对' void base::func(temp *)'的未定义引用

base是基类

derived是基类

的派生类。

这个调用者说未定义的引用…

//抱歉,因为我的源代码实在太大了,无法显示

代码工作正常(在您纠正了无意义语法之后):

class base
{
    public:
    template<class T> int func();
    //       ^^^^^
    //       use class keyword
}; // <-- semicolon here
template<class T>
//       ^^^^^
//       use class keyword
int base::func()
{
    return 0;
}
class derived : public base
//                    ^
//                    no colon here
{
    void  caller()
    { 
        func<int>(); // it works
        base::func<int>();    // this works too
    }
}; // <-- semicolon here