How do I implement hexagonal/clean architecture in C++?

In implementing hexagonal or clean architecture in C++, it's important to separate your code into different layers. This architecture emphasizes the independence of different components, making it easier to maintain and test. Below is a simplified approach to achieve hexagonal architecture in C++.

Example Implementation

// Domain Layer class User { public: User(std::string name) : name(name) {} std::string getName() const { return name; } private: std::string name; }; // Repository Interface (Ports) class UserRepository { public: virtual ~UserRepository() {} virtual void save(const User& user) = 0; virtual User findById(int id) = 0; }; // Adapter Implementation (Secondary) class InMemoryUserRepository : public UserRepository { public: void save(const User& user) override { users[user.getId()] = user; } User findById(int id) override { return users[id]; } private: std::unordered_map users; }; // Application Layer class UserService { public: UserService(UserRepository& userRepo) : userRepo(userRepo) {} void registerUser(std::string name) { User user(name); userRepo.save(user); } private: UserRepository& userRepo; }; // Main Function int main() { InMemoryUserRepository repo; UserService userService(repo); userService.registerUser("John Doe"); return 0; }

C++ hexagonal architecture clean architecture software design software architecture