模板模板变量可以用于捕获传递的模板参数本身就是模板的所有情况吗?
我一直在使用模板为一些基于模板的方法生成调试输出。首先,我创建了一个通用处理程序,然后将其专门用于本机类型:
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";
}
...
然后我尝试添加第二个模板格式来捕获传递的模板类型:
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 << '>';
}
其中 subtype 是一个模板方法,设计用于递归参数列表,将每个参数应用于 ntype( ) 反过来。
问题是当我尝试用以下内容调用它时:
ntype<SomeClass<int> >(out, TypeList<SomeClass<int> >());
它只匹配通用的第一个模板函数 - 没有编译错误,但它永远不会匹配模板模板版本。我确信这只是我缺乏理解,但是当涉及到模板模板的清晰示例时,谷歌结果似乎非常薄弱,对于可变参数模板参数甚至更薄弱。
谁能解释我正在尝试的事情是否可能,如果可以,我做错了什么?
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?
发布评论
评论(1)
看起来我只是有一个拼写错误 - 我在函数声明中的一个 TypeList 后面添加了 (),可能是从凌晨 3 点的函数调用复制和粘贴而来,这导致了不匹配。
因此,如果有人想知道,是的,这是可能的,并且上述是一种完全可以接受的方法。
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.