Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid violating ODR with traits classes

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..

like image 361
Curious Avatar asked Jun 10 '17 20:06

Curious


1 Answers

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.

like image 86
user8142939 Avatar answered Oct 21 '22 03:10

user8142939