【问题标题】:unresolved overloaded function error when binding to std::operator== [duplicate]绑定到 std::operator== 时未解决的重载函数错误 [重复]
【发布时间】:2015-02-02 04:15:16
【问题描述】:

我正在尝试绑定到bool std::operator==(const std::string&, const std::string&),但我遇到了一个错误,希望有人能帮助我。

std::string v1 = "foo";
std::string v2 = "foo";

bool r = 
    std::bind(
        static_cast<bool(*)(const std::string&, const std::string&)>(&std::operator== ),
        std::placeholders::_1,
        std::cref(v1))(v2);


error: invalid static_cast from type '<unresolved overloaded function type>' to type 'bool (*)(const string&, const string&) {aka bool (*)(const std::basic_string<char>&, const std::basic_string<char>&)}'
             &std::operator== ), 
                              ^

示例:ideone.com

【问题讨论】:

  • 你内心的声音不是在告诉你可能不应该使用这些东西吗? std::bind 是用来开玩笑的,不是用来当真事的……

标签: c++


【解决方案1】:

消除歧义 std::operator== 解决了您的问题,但它不是看起来最干净的代码:

bool r = 
        std::bind(
            static_cast<bool(*)(const std::string&, const std::string&)>(operator==<char, std::string::traits_type, std::string::allocator_type>),
            std::placeholders::_1,
            std::cref(v1))(v2);

【讨论】:

    【解决方案2】:

    Pradhan 为您提供了在此位置使用 bind 的正确语法。这似乎是在这个地方不使用bind 并更喜欢 lambda 的一个很好的理由:

    bool r = [&v1](const std::string& rhs){
        return rhs == v1;
    }(v2);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-19
      • 2010-11-11
      • 2014-07-03
      • 2013-02-20
      • 1970-01-01
      相关资源
      最近更新 更多