C++ 使用模板的未定义符号
生成此代码时出现链接器错误: 排除.h文件C++ 使用模板的未定义符号,c++,templates,linker-errors,undefined-reference,C++,Templates,Linker Errors,Undefined Reference,生成此代码时出现链接器错误: 排除.h文件 class IsExclude { public: template<typename T> bool operator()(const T* par); virtual ~IsExclude() = 0; }; IsExclude::~IsExclude() {} class IsExcludeA : public IsExclude { public:
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_;
};
类不包括在内
{
公众:
模板
布尔运算符()(常数T*par);
virtual~IsExclude()=0;
};
IsExclude::~IsExclude(){}
类别IsExcludeA:公共IsExclude
{
公众:
IsExcludeA(std::string toCompare):toCompare((toCompare){}
模板
布尔运算符()(常数T*par)
{
返回strcmp(par->Something,toCompare_u.c_str())?false:true;
}
~IsExcludeA(){}
私人:
std::用于比较的字符串;
};
在同一文件中:
/*
* 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;
}
/*
*在函数对象的容器上循环
*如果其中至少有一个返回true,则函数
*返回true,否则返回false
*该函数用于评估一组
*排除规则置于“和”条件下。
*/
模板
布尔值不包括在内(常数T&cont,常数P*toCheck)
{
typename T::const_迭代器pos;
typename T::const_迭代器end(cont.end());
bool-ret(假);
对于(pos=cont.begin();pos!=end;++pos)
{
if((*pos)->operator()(toCheck)==true)
{
ret=真;
pos=结束;
}
}
返回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
}
std::vector exVector;
push_back(新的IsExcludeA(std::string(“A”));
push_back(新的IsExcludeA(std::string(“B”));
if(isExclude(exVector,asset)==false)
{
//废话
}
代码可以编译,但我从链接器中得到一个错误:
未定义的首次引用
文件中的符号
bool IsExclude::operator()(常量类型0*)MyFile.o
你有什么提示或建议吗
另外,我知道我需要清理向量以避免内存泄漏。我无法在编译器中使用boost::shared_ptr。唉 在
isExclude
函数中,您可以编写:
if ( (*pos)->operator()(toCheck) == true )
这将调用已声明但未定义的IsExclude::operator()
,因此链接器有理由抱怨。在我看来,您希望在operator()
上具有多态性行为,但您落入了“模板函数不能是虚拟的”陷阱
在不知道您的需求的情况下,很难为您提供更多帮助,但也许您应该重新考虑使用模板化的
操作符()
,然后使用虚拟操作符()
我明白了!我想我需要重新考虑我的设计。谢谢。返回strcmp(par->Something,to compare_u.c_str())?假:真代码>应该写为returnpar->Something==toCompare代码>