How to avoid violating ODR with traits classes

给你一囗甜甜゛ 提交于 2019-12-06 00:51:41

问题


On reading code online from production libraries I found something like this

Traits.hpp

template <typename Type>
class Traits {
    template <typename T, 
              detail::EnableIfIsInstantiation<T, Type>* = nullptr>
    static void foo(T& object) { 
        object.foo();
    } 
};

SpecialTraits.hpp

template <>
class Traits<Special> {
    static void foo(Special& object) {
        object.foo();
    }
    static void foo(Special&& object) {
        object.special_foo();
    }
};

This will cause an ODR violation if a library instantiates a type that uses Traits for Something in one translation unit without including SpecialTraits.hpp and then instantiates a type that uses the specialized traits in another translation unit. This would cause an ODR violation when those two translation units are linked together.

What is the suggested way to avoid this problem? Do I have to resort to including all the specializations in the original Traits.hpp file? And what if I am not allowed to edit the file with the definition for Special?

Note Please ignore the fact that foo() could have been specialized by Special itself in the && case. I could not think of a better example..


回答1:


Put the specialization in "WidgetWrapper.hpp" instead of "Widget.hpp" and include "WidgetWrapper.hpp" everywhere. Otherwise, file a bug report with Boost and expect it to go nowhere since this exact problem was discussed 15 years ago with no resolution.



来源:https://stackoverflow.com/questions/44477925/how-to-avoid-violating-odr-with-traits-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!