StudyNPractice
StudyNPractice

Reputation: 75

c++ class declaration when same routine, different member variable type

I'm trying to make a class something like this

class IPclass {
  void SendData();

  io_service io_service_;
  tcp::socket tcp_socket_{io_service_};
};

class UDSclass {
  void SendData();

  io_service io_service_;
  local::stream_protocol::socket tcp_socket_{io_service_};
};

The thing is, IPclass and UDSclass have same routine with same member variables with one difference: socket type.

I want to make one class named SessionClass instead of these two classes.

These are options I tried and reasons of failure.

Is there any suggestion or known solution for this problem? Thanks a lot.

Upvotes: 0

Views: 399

Answers (1)

Matthieu Brucher
Matthieu Brucher

Reputation: 22023

You can use a templated class:

template <typename NetworkType>
class NetworkClass
{
    NetworkType tcp_socket_{io_service_};
};

and then use:

using IPclass = NetworkClass<tcp::socket>;

If you need more than this, you can use type traits to define more advanced behaviors without dynamic polymorphism.

Upvotes: 5

Related Questions