c++ - 没有匹配的函数用于调用 std::list::remove_if( function()::predicate )

标签 c++ predicate stdlist argument-dependent-lookup

因此,在函数内定义谓词并用作 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/

相关文章:

c# - 属性谓词

c++ - std::list<std::future> 析构函数不阻塞

c++ - 删除 boost::shared_ptr 的内容

c++ - 使用 ofstream 写入二进制数据时出现问题

c++ - 为什么我的代码没有使用类型转换进行编译?

java - 在 Java 中将谓词作为 lambda 返回

c++ - 映射唯一值和重复值的有效方法。可以访问键或值的位置

scala - Scala中的基本逻辑编程

c++ - 有没有办法从 std::list 中提取一个节点,类似于 std::map::extract 的作用?

c++ - 通过不使用模板的迭代器返回 std::list