Service: allow registering non-polymorphic service types

ServiceRegistry::provide<I> cross-cast to IService via dynamic_cast, which
fails to compile when I is a plain (non-polymorphic) value type. Guard the
cross-cast with std::is_polymorphic_v<I>; non-polymorphic services are
stored and resolvable but carry no lifecycle aspect. Test added.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Opus 4.8 committed 2026-06-22 16:59:02 +03:00
1 parent cb639a713d
commit adc0de310e
2 files changed
+26 -2

No files matched your search

+7 -2
View File
@@ -61,11 +61,16 @@ namespace Void::Service
entry.impl = std::shared_ptr<void>(impl, impl.get());
if constexpr (std::is_base_of_v<IService, I>) {
entry.service = static_cast<IService*>(impl.get());
} else {
} else if constexpr (std::is_polymorphic_v<I>) {
// The interface I doesn't derive IService, but the
// concrete implementation might — recover the lifecycle
// aspect by cross-cast.
// aspect by cross-cast. (dynamic_cast requires a
// polymorphic I.)
entry.service = dynamic_cast<IService*>(impl.get());
} else {
// A plain, non-polymorphic service type: storable and
// resolvable, but has no IService lifecycle aspect.
entry.service = nullptr;
}
const std::type_index key{typeid(I)};
std::unique_lock lock{m_mutex};
+19
View File
@@ -53,8 +53,27 @@ namespace
[[nodiscard]] std::string greet() const override { return "hi"; }
std::vector<std::string>* m_log;
};
// A plain, non-polymorphic value type registered directly as a service.
struct Config {
int port = 8080;
std::string host = "localhost";
};
} // namespace
Void::Testing::Test registry_provides_non_polymorphic_service()
{
ServiceRegistry reg;
reg.provide<Config>(std::make_shared<Config>(Config{.port = 9000}));
auto cfg = reg.get<Config>();
Void::Testing::expect(cfg != nullptr);
Void::Testing::expect_eq(cfg->port, 9000);
Void::Testing::expect(reg.has<Config>());
// No IService lifecycle aspect, but start_all/stop_all must not choke.
reg.start_all();
reg.stop_all();
}
Void::Testing::Test registry_provide_and_get()
{
ServiceRegistry reg;