Question

Can a template template variadic be used to catch all cases of a template parameter being passed that is itself a template?

I've been using templating to produce debug output for some template based methods. Firstly, I created a generic handler, then specialised it for native types:

template<typename... PARAMS> struct TypeList{};

template<typename TYPE> inline void ntype(ostream &out, TypeList<TYPE>) {
    out << typeid(TYPE).name();
}

template<> inline void ntype(ostream &out, TypeList<int>) {
    out << "int";
}

...

Then I tried to add a second template format to catch template types being passed:

template<typename ... SUB, template<typename...> class TYPE> void ntype(ostream &out, TypeList<TYPE<SUB...> >) {
    ntype(out, TypeList<typename TYPE>());
    out << '<';
    subtype(out, TypeList<SUB...>());
    out << '>';
}

Where subtype is a template method designed to recurse through the param list, applying each to ntype() in turn.

The problem is when I attempt to call this with something to the effect of:

ntype<SomeClass<int> >(out, TypeList<SomeClass<int> >());

It only ever matches the generic first template function - no compilation errors, but it never matches the template template version. I'm sure its merely a lack of understanding on my part, but google results seem very thin on the ground when it comes to clear examples of template templates, and even thinner with regards to variadic template params.

Can anyone explain whether what I'm attempting is even possible and, if so, what I'm doing wrong?

Was it helpful?

Solution

It appears I merely had a typo - I had added () after one of my TypeLists in a function declaration, probably from copy and pasting from a function invocation at 3am, which was causing the mismatch.

So, in case anyone is wondering, yes it is possible, and the above is a perfectly acceptable way to do it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top