我在构建此代码时遇到链接器错误:
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/