3

I have noticed that, at least under c++17 ISO with g++, std::type_index seems to reliably match equality in the case of polymorphic dynamically loaded classes through dlsym. This seems to enable a nice little runtime validation of interfaces before instantiating plugin classes. For example:

template<typename T>
std::shared_ptr<T> CreateImplOf(std::string pluginName, std::string className)
{
  auto it = m_pluginDict.find(pluginName);
  if(it == m_pluginDict.end())
    return nullptr;
  auto& plug = it->second;
  const std::type_index& iface_info = plug.GetInfo()->getInterfaceTypeInfo(className.data());
  if (iface_info == std::type_index(typeid(T))) {
    std::cout << "SUCCESS! type " << iface_info.name() << " match impl interface... " << std::endl;
  } else {
    std::cout << "FAILURE! type " << typeid(T).name() << " DOES NOT match impl interface " << iface_info.name() << "... " << std::endl;
    throw std::exception{};
  }
  void* pObj = plug.CreateInstance(className);
  return std::shared_ptr<T>(reinterpret_cast<T*>(pObj));

But since I have the hunch this behavior is not defined in the standard, I wonder how much trust should we put in this runtime check

In an ideal world, equality of std::type_index between two interfaces implies ABI compatibility between them, such that invoking virtual methods through any of the two interfaces would be well defined, but almost positive we don't live anywhere near that ideal world, but exactly what expectations can one have from having this runtime check to pass? can we assume this to work on the same compiler version for the same exact class definition only? or not even that in general?

lurscher
  • 25,930
  • 29
  • 122
  • 185

0 Answers0