繁体   English   中英

模板参数推导/替换失败-std :: find()

[英]Template argument deduction/substitution failed - std::find()

我没有使用模板。 我已经浏览了一些相关的帖子,但是找不到与我的问题完全一样的东西-尽管我确定它们是正确的,但我只是不理解它们。

我有以下代码:

#pragma once

// define logging levels
#define logging 1

// standard includes
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <string.h>
#include <string>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>

using namespace std;
vector<struct sockaddr_in> activeNodes;

-------
bool
RoutingManager::ActivateNewNode(struct sockaddr_in newNode)
{
    find(activeNodes.begin(), activeNodes.end(), newNode) != activeNodes.end())
    [..]
}

当我尝试对此进行编译时,出现一千个错误,例如:

/usr/include/c++/4.8/bits/stl_list.h:276:5: note:   template argument deduction/substitution failed:
In file included from /usr/include/c++/4.8/algorithm:62:0,
                 from globals.h:9,
                 from manager.h:3,
                 from manager.cpp:1:
/usr/include/c++/4.8/bits/stl_algo.h:194:17: note:   ‘sockaddr_in’ is not derived from ‘const std::_List_iterator<_Tp>’
    if (*__first == __val)
                 ^
In file included from /usr/include/c++/4.8/list:63:0,
                 from manager.h:8,
                 from manager.cpp:1:
/usr/include/c++/4.8/bits/stl_list.h:1602:5: note: template<class _Tp, class _Alloc> bool std::operator==(const std::list<_Tp, _Alloc>&, const std::list<_Tp, _Alloc>&)
     operator==(const list<_Tp, _Alloc>& __x, const list<_Tp, _Alloc>& __y)
     ^
/usr/include/c++/4.8/bits/stl_list.h:1602:5: note:   template argument deduction/substitution failed:
In file included from /usr/include/c++/4.8/algorithm:62:0,
                 from globals.h:9,
                 from manager.h:3,
                 from manager.cpp:1:
/usr/include/c++/4.8/bits/stl_algo.h:194:17: note:   ‘sockaddr_in’ is not derived from ‘const std::list<_Tp, _Alloc>’
    if (*__first == __val)
                 ^
make: *** [build/manager.o] Error 1

我在这里做错了什么?

首先,你真的应该

#include <netinet/in.h>

因为这是定义sockaddr_in结构的标头。 其次,您收到的错误消息是由于以下事实导致的: std::find不知道如何比较struct sockaddr_in对象是否相等。 要解决此问题,请为operator==定义重载。

您可以为相等运算符定义非成员重载,如下所示:

#include <netinet/in.h>
bool operator == (const sockaddr_in &lhs, const sockaddr_in& rhs) {
      return lhs.sin_family == rhs.sin_family 
        && lhs.sin_port == rhs.sin_port
        && lhs.sin_addr.s_addr == rhs.sin_addr.s_addr
        && lhs.sin_zero == rhs.sin_zero;
}
bool operator != (const sockaddr_in &lhs, const sockaddr_in& rhs) {
      return !(lhs == rhs);
}

int main()
{
    vector<sockaddr_in> activeNodes;
    sockaddr_in newNode;
    std::find(activeNodes.begin(), activeNodes.end(), newNode);
}

我考虑过使用strcmp但是它们是unsigned char,所以我不确定是否相等会失败。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM