C++ 模板问题-无法将函数作为参数传递(非静态成员函数的使用无效)
这是我做的模板。我相信这是不言自明的C++ 模板问题-无法将函数作为参数传递(非静态成员函数的使用无效),c++,templates,static,compiler-errors,C++,Templates,Static,Compiler Errors,这是我做的模板。我相信这是不言自明的 template <class N, class I> std::list<N*> selectiveList(I element, std::list<N*> & container, I (N::*f)() const) { typename std::list<N*>::iterator it; std::list<N*> selectiveListing; f
template <class N, class I>
std::list<N*> selectiveList(I element, std::list<N*> & container, I (N::*f)() const) {
typename std::list<N*>::iterator it;
std::list<N*> selectiveListing;
for (it = container.begin(); it != container.end(); ++it)
if ((*it)->*f == element)
selectiveListing.push_back(*it);
if (selectiveListing.size() == 0)
throw NoItemsFound<I>(element);
return selectiveListing;
}
模板
std::list selectiveList(I元素,std::list和容器,I(N::*f)()常量){
typename std::list::iterator;
std::列表列表;
for(it=container.begin();it!=container.end();+it)
if((*it)->*f==元素)
选择列表。将_向后推(*it);
if(listing.size()==0)
抛出NoItemsFound(元素);
返回列表;
}
我从这个函数中调用它:
void AirportManager::searchAirplanesTypes() {
clrscr();
std::stringstream prompt;
prompt << "Escolha atributo a pesquisar: \n" <<
"1) Tipo\n" <<
"2) Descricao\n" << "3) Categoria\n";
int choice = getNumberInput(prompt.str(), 1, 3);
switch (choice) {
case 1: {
std::string searchElement1 = getStringInput("Tipo: ");
pageNav(selectiveList(searchElement1, airport.airplanesTypes,
&AirplaneType::getType), "", true, true);
break;
}
case 2: {
std::string searchElement2 = getStringInput("Descricao: ");
pageNav(selectiveList(searchElement2, airport.airplanesTypes,
&AirplaneType::getDescription), "", true, true);
break;
}
case 3: {
//Category is an enumerated data type
Category searchElement3 = getCategoryInput("Categoria: ");
pageNav(selectiveList(searchElement3, airport.airplanesTypes,
&AirplaneType::getCategory), "", true, true);
break;
}
}
}
void AirportManager::searchAirplanesTypes(){
clrsc();
std::stringstream提示符;
提示if((((*it)->*f)()==元素)
if(((*it)->*f)()==元素)
已经有一段时间了,但是您是否缺少一个新的
throw new NoItemsFound<I>(element);
抛出新的NoItemsFound(元素);
已经有一段时间了,但您是否错过了一个新的
throw new NoItemsFound<I>(element);
抛出新的NoItemsFound(元素);
复制元素的标准方法是使用否定的std::remove\u copy\u if()
或编写copy\u if()
算法。IMHOcopy\u if()
是更清晰的选择,即使它不是标准函数,也很容易正确编写:
template<class In, class Out, class Pred>
Out std::copy_if(In first, In last, Out res, Pred p)
{
while( first != last ) {
if( p(*first) ) *res++ = *first;
++first;
}
return res;
}
这里的好处是,您可以使用copy\u if()
进行大量的其他操作。它适用于任何容器,而不仅仅是std::list
,它还适用于任何一元谓词,无论是基元函数还是函数对象。复制元素的标准方法是使用否定的std::remove\u copy\u if()
或编写一个copy\u if()
算法。IMHOcopy\u if()
是更清晰的选择,尽管它不是一个标准函数,但很容易正确编写:
template<class In, class Out, class Pred>
Out std::copy_if(In first, In last, Out res, Pred p)
{
while( first != last ) {
if( p(*first) ) *res++ = *first;
++first;
}
return res;
}
这里的好处是,您可以使用copy\u if()对于很多其他的事情,它适用于任何容器,而不是只是代码> STD::清单< /C>。它与任何一元谓词一起工作,不管是原始函数还是函数对象。 C++ C++ FAQ推荐。C++ FAQ推荐。谢谢你的额外输入!我将考虑到最后一个项目,但对。现在重构所有函数的成本太高了。谢谢你的额外投入!我会在下一个项目中考虑到这一点,但现在重构所有函数的成本太高了。