Hasty Briefsbeta

Bilingual

Using C++ type aliasing to avoid the ODR problem with conditional compilation

a year ago
  • #Template Programming
  • #One Definition Rule
  • #C++
  • The article discusses the C++ concept of 'ill-formed no diagnostic required' (IFNDR), particularly focusing on violations of the One Definition Rule (ODR).
  • A common source of ODR violations is defining a class or function differently based on compile-time switches, such as `#ifdef` directives.
  • The article provides an example where `Widget` is defined differently in different translation units, leading to ODR violations.
  • Type aliases are highlighted as a solution since they are not subject to the ODR, allowing different definitions in different translation units without introducing new types.
  • The article introduces a template-based approach (`WidgetT<true>` and `WidgetT<false>`) to avoid ODR violations by using type aliases (`using Widget = WidgetT<true/false>`).
  • The template approach involves explicit template instantiation and boilerplate code but ensures type safety across different compilation units.
  • Potential issues with static members in the template approach are discussed, suggesting that they could lead to surprising behavior if not handled carefully.
  • The article hints at a future discussion on resolving these issues, possibly by moving static members to a shared base class.
  • A bonus section mentions a similar technique used to handle multiple definitions of `wchar_t`.