Warm tip: This article is reproduced from serverfault.com, please click

overloading socket.h method in a template

发布于 2020-11-28 18:46:56

I am trying to use templates to make a generic interface type class. As such, I want to have a "connect()" function in the template class. When I make an implementation of the template for a socket interface, however, the compiler thinks I mean the connect() function of the parent and not the connect() function that is part of the socket.h library. How do I specify I want to use the socket.h library connect() function in the implementation class? See the minimal example below

#include <string>
#include <sys/socket.h>
#include <netdb.h>
template <class Input, class Output> class Parent {
public:
  Parent() : _isConnected(false) {}
  bool connect() {
    return _isConnected || (_isConnected = childConnect());
  }
private:
  bool _isConnected;
  virtual bool childConnect() = 0;
};
class Implementation : public Parent<std::string, std::string> {
  bool childConnect() {
    int sockfd;
    struct addrinfo *p;
    connect(sockfd, p->ai_addr, p->ai_addrlen);
    return true;
  }
};
int main() {
  Implementation ii;
  return 0;
}

and compiler error

g++ main.cc
main.cc: In member function ‘virtual bool Implementation::childConnect()’:
main.cc:22:46: error: no matching function for call to ‘Implementation::connect(int&, sockaddr*&, socklen_t&)’
     connect(sockfd, p->ai_addr, p->ai_addrlen);
                                              ^
main.cc:11:8: note: candidate: bool Parent<Input, Output>::connect() [with Input = std::__cxx11::basic_string<char>; Output = std::__cxx11::basic_string<char>]
   bool connect() {
        ^~~~~~~
main.cc:11:8: note:   candidate expects 0 arguments, 3 provided
Questioner
Quae Modica
Viewed
0
Jarod42 2020-11-29 02:50:29

You might full qualify the call:

::connect(sockfd, p->ai_addr, p->ai_addrlen);