使用模板的未定义的符号

时间:2010-12-08 12:01:28

标签: 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

您有任何提示或建议吗?

P.S。我知道我需要清理向量以避免内存泄漏。我不能在我的编译器中使用boost :: shared_ptr。感叹!

1 个答案:

答案 0 :(得分:3)

isExclude函数中,您可以写:

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

这会调用已声明但未定义的IsExclude::operator(),因此链接器有充分的理由抱怨。在我看来,你会喜欢operator()上有一个多态行为但是你陷入'模板函数不能是虚拟'陷阱。

如果不知道您的要求是什么,很难帮助您,但也许您应该重新考虑使用模板operator()并选择虚拟 operator()