使用模板时出现未定义的符号

3
我正在构建这段代码时遇到链接器错误:
排除.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。叹息!

应该将 return strcmp(par->Something, toCompare_.c_str() ) ? false : true ; 改写为 return par->Something == toCompare; - user102008
1个回答

3
isExclude 函数中,你写道:
if ( (*pos)->operator()(toCheck) == true )

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

如果不知道您的要求,很难为您提供更多帮助,但也许您应该重新考虑使用模板化的operator(),而改用虚拟operator()


我明白了!我觉得我需要重新考虑我的设计。谢谢。 - Alessandro Teruzzi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接