c++ - 使用模板的 undefined symbol

标签 c++ templates linker-errors undefined-reference

我在构建此代码时遇到链接器错误:

Exclude.h文件

class IsExclude
{
    public:
        template<typename T>
        bool operator()(const T* par);
        virtual ~IsExclude() = 0;
};

IsExclude::~IsExclude() {}

class IsExcludeA : public IsExclude
{
    public:
        IsExcludeA(std::string toCompare) : toCompare_(toCompare)  {}
        template<typename T>
        bool operator()(const T* par)
        {
            return strcmp(par->Something, toCompare_.c_str() ) ? false : true ; 
        }
        ~IsExcludeA() {}
    private:
        std::string toCompare_;
};

在同一个文件中:

/*
 * loop over a container of function objects
 * if at least one of them return true the function
 * return true, otherwise false
 * The function was designed to evaluate a set of
 * exclusion rule put in "and" condition.
 */
template<typename T,typename P>
bool isExclude( const T& cont, const P* toCheck )
{
    typename T::const_iterator pos;
    typename T::const_iterator end(cont.end());
    bool ret(false);
    for (pos = cont.begin(); pos != end; ++pos)
    {
        if ( (*pos)->operator()(toCheck) == true )
        {
            ret = true;
            pos = end;
        }
    }    
    return ret;
}

我使用上一个调用的 cpp 文件如下所示:

std::vector<IsExclude* > exVector;

exVector.push_back( new IsExcludeA(std::string("A")) );
exVector.push_back( new IsExcludeA(std::string("B")) );

if (isExclude(exVector,asset) == false)
{
     // Blah
}

代码编译正常,但链接器出错: 未定义的首次引用 文件中的符号 bool IsExclude::operator()(const __type_0*) MyFile.o

您有什么提示或建议吗?

附言我知道我需要清理 vector 以避免内存泄漏。我不能在我的编译器中使用 boost::shared_ptr。叹息!

最佳答案

isExclude 函数中,您编写:

if ( (*pos)->operator()(toCheck) == true )

这会调用已声明但未定义的 IsExclude::operator(),因此链接器有充分的理由提示。在我看来,您希望operator() 上具有多态行为,但您陷入了“模板函数不能是虚拟的”陷阱。

在不知道您的要求是什么的情况下很难为您提供更多帮助,但也许您应该重新考虑使用模板化的 operator() 并选择一个虚拟 operator ()

关于c++ - 使用模板的 undefined symbol ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4387167/

相关文章:

c++ - 简单程序的高CPU使用率

c++ - int64_t 的整数类型歧义

c++ - Netbeans C++ MinGW 设置

c++ - CUDA __device__ 未解析的外部函数

c++ - 传递数组指针并在函数内部使用

C++0x : how to get variadic template parameters without reference?

c++ - 如何使此模板 typedef 在 C++11 中有效?

c++ - 从特征类继承

c++ 一个解决方案两个项目(exe & dll)链接错误

c++ - 无法使用基类构建 DLL