Nick Roz
Nick Roz

Reputation: 4250

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?

Upvotes: 4

Views: 1010

Answers (1)

sehe
sehe

Reputation: 393487

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

};

Upvotes: 1

Related Questions