5

I am currently working at a small and simple serialization-library for my project. This involves an archive calling a free template function that by default calls a save member function of T:

template<typename Archive, typename T> 
inline void save(Archive& a, const T& v)
{
    v.save(ar);
}

Now I want to overload this function outside of the library to support types without the save method:

/* A.h */

Class A {/**/};

template<typename Archive>
inline void save(Archive& a, const A& v)
{
    a << member; //etc
}

And in main.cpp:

#include "serialization/OStreamArchive.h
#include "a.h"

int main() 
{
    OStreamArchive<std::ofilestream> ar(somefstream);
    A a;

    ar << a;
}

So conceptionally it should work like the boost serialization library: http://www.boost.org/doc/libs/1_59_0/libs/serialization/doc/tutorial.html#nonintrusiveversion The problem is that I don't know how I get the compiler to find the overloaded function. I spent the last hours looking at the boost code and I tried to find the trick.

The complete call structure of save is the following:

/* OFileStream.h */
template<typename T>
OStreamArchive& operator<<(const T& value)
{       
    serialization::commonSave(*this, value);
}

/* save.h */

template<typename Archive, typename T>
inline void save(Archive& archive, const T& value)
{
    serialization::Access::save(archive, value); //call T::save
}

template<typename Archive, typename T>
inline void commonSave(Archive& archive, const T& value, std::false_type)
{
    serialization::save(archive, value);
}

template<typename Archive, typename T>
inline void commonSave(Archive& archive, const T& value)
{
    //primitives get extra treatment
    serialization::commonSave(archive, value, typename std::is_fundamental<T>::type()); 
}
0

1 Answer 1

2

When you create a customization point which is used from within a template, it is being looked up using ADL. That is, customized versions of the function need to be found in a namespace associated with at least on of the parameters. Of course, you'd also need to make sure you don't call the function defining the customation point using a qualified call.

The special version of the save() should be found if you use this definition:

template <typename Archive, typename T>
inline void commonSave(Archive& archive, T const& value, std::false_type) {
    using serialization; // find things in namespace serialization if
                         // if there is no better version
    save(archive, value);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.