Search code examples
c++templatesyamlspecializationyaml-cpp

Converting with yaml-cpp to a template class


I have my own container:

template<class T>
class MyContainer {}

And I'm using yaml-cpp for loading some data into this container. So I need to write specialization for convert struct:

template<> struct convert< MyContainer<int> > {};
template<> struct convert< MyContainer<double> > {};
template<> struct convert< MyContainer<char> > {};
template<> struct convert< MyContainer<MyClass> > {};

... and so on.

Ultimately, I write:

// ...
node.as< MyContainer<int> >
// ...

But the fact is that every specialization for MyContainer is the same. Therefore, every specialization for convert is the same and they are redundant:

template<> struct convert< MyContainer<int> > { /* the same code */ };
template<> struct convert< MyContainer<double> > { /* the same code */ };
template<> struct convert< MyContainer<char> > { /* the same code */ };
template<> struct convert< MyContainer<MyClass> > { /* the same code */ };

Is it possible to avoid this rubbish using c++ itself or some other features of yaml-cpp?


Solution

  • To the comment

    in fact the situation a bit more complex. What confused me, that MyContainer has two template arguments and convert has only one. So I should have written: template<class A, class B> struct convert< Manager<A, B> > { /**/ };

    Try a variadic partial specialization

    template <typename... Ts> 
    struct convert< MyContainer<Ts...> > { 
    
        using container_type = MyContainer<Ts...>;
    
        // ... the specialized implementation, once
    
    };