因此,在函数内定义谓词并用作 std::list::remove_if
不允许争论?
考虑以下无法编译的代码:
struct a { };
int main()
{
struct pred { bool operator()( const a& ) { return false; } };
std::list< a > l; // fill l
l.remove_if( pred() );
return 0;
}
error: no matching function for call to
‘std::list<a, std::allocator<a> >::remove_if(main()::pred)’
现在,如果我替换 l.remove_if( pred() );
与
pred()( *l.begin() );
// or
pred p;
p( *l.begin() );
其中remove_if
在内部执行,它会按预期编译并工作。
甚至更多:如果我搬家 struct pred
在 main 之外定义,两个测试都按预期工作。
这对我来说没有任何意义。
我认为它可能是具有从属名称和 ADL 之类的东西,但是...... remove_if
的参数是实例,而不是类型。确实,这是一个模板函数并且参数的类型仍然被解析,但是..
有人可以解释一下发生了什么以及为什么发生吗?
最佳答案
第一个问题的答案是,是的,在 C++11 之前,某些类型(例如本地类型)不允许作为模板参数。参见14.3.1/2:
A local type, a type with no linkage, an unnamed type or a type compounded from any of these types shall not be used as a template argument for a template type parameter.
由于 remove_if
是一个模板,因此您不能使用本地谓词作为其参数。
关于c++ - 没有匹配的函数用于调用 std::list::remove_if( function()::predicate ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21096908/