不需要递归。这更简单:
#include <iostream>
#include <string>
#include <typeinfo>
class A {
public:
template<typename parser>
void foohelper() {
std::cout << "handled a " << typeid(parser).name() << std::endl;
// do work here
}
template <typename... parsers>
void foo() {
using expand = int[];
(void) expand { 0, (foohelper<parsers>(), 0)... };
}
};
int main() {
A a;
a.foo<int, int, double, std::string>();
}
样本输出:
handled a i
handled a i
handled a d
handled a NSt3__112basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEEE
编辑:
针对不符合标准的 microsoft 编译器要求,这里有另一个不依赖 unsized 数组的版本:
#include <iostream>
#include <string>
#include <typeinfo>
class A {
public:
template<typename parser>
void foohelper() {
std::cout << "handled a " << typeid(parser).name() << std::endl;
// do work here
}
template <typename... parsers>
void foo() {
// c++ strictly does not allow 0-sized arrays.
// so here we add a NOP just in case parsers is an empty type list
using expand = int[1 + sizeof...(parsers)];
(void) expand {
(foohelper<void>(), 0),
(foohelper<parsers>(), 0)...
};
}
};
// implement the NOP operation. Note specialisation is outside class definition.
template<> void
A::foohelper<void>() {}
int main() {
A a;
a.foo<int, int, double, std::string>();
a.foo<>();
}
编辑 2:
带有前缀、后缀和解析器间调用的完整示例。编写了这么多代码后,您可能会开始想,“嘿!我可以在这里实现一门特定领域的语言!”,你是对的。
但是,比这更复杂的事情可能会让你永远憎恨你的同事,所以我会避免走这条路。
#include <iostream>
#include <string>
#include <typeinfo>
class A {
public:
template<typename parser>
void foohelper() {
std::cout << "handled a " << typeid(parser).name();
// do work here
}
void prepare()
{
std::cout << "starting parsers: ";
}
void separator()
{
std::cout << ", ";
}
void nothing()
{
}
void done() {
std::cout << " done!" << std::endl;
}
template <typename... parsers>
void foo() {
// c++ strictly does not allow 0-sized arrays.
// so here we add a NOP just in case parsers is an empty type list
bool between = false;
using expand = int[2 + sizeof...(parsers)];
(void) expand {
(prepare(), 0),
((between ? separator() : nothing()), between = true, foohelper<parsers>(), 0)...,
(done(), 0)
};
}
};
int main() {
A a;
a.foo<int, int, double, std::string>();
a.foo<>();
}
样本输出:
starting parsers: handled a i, handled a i, handled a d, handled a NSt3__112basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEEE done!
starting parsers: done!