4

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?

Nick Roz
  • 3,918
  • 2
  • 36
  • 57
  • 4
    did you try a partial specialization like: `template struct convert< MyContainer > { /*common code*/ };` ? – Piotr Skotnicki Jan 13 '15 at 11:04
  • @piotr-s, no, i haven't. It seems to work. I skimmed through C++ book yesterday, but was unable to find this structure. Could you drop a line about how it works and give any links? – Nick Roz Jan 13 '15 at 11:13
  • It is a partial specialization. Roughly speaking, any type matching the pattern (in that case, MyContainer) uses that specialization. – Puppy Jan 13 '15 at 11:36
  • @nirname Yes. http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – sehe Jan 13 '15 at 12:00
  • @sehe, thanks. I've been reading 'Straustrup. C++ Programming Language. Special Edition'. Quite good book, but using templates are still not very clear for me. – Nick Roz Jan 13 '15 at 12:34
  • @piotr-s, 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 struct convert< Manager > { /**/ };`. Sometimes templates' syntax is really vague. – Nick Roz Jan 13 '15 at 12:35
  • 1
    @nimame It's not _vague_. It's _generic_. If you're learning C++, probably best to start with _concrete_ classes. And /use/ the generics from the standard library (so you know how they "feel") – sehe Jan 13 '15 at 12:40

1 Answers1

1

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

};
sehe
  • 374,641
  • 47
  • 450
  • 633