你可以尝试使用Boost元编程库来实现,但需要更改类的模板定义以腾出空间给Boost MPL参数。
使用Boost::MPL实现你想要做的事情的一个例子如下:
#include <boost/mpl/vector.hpp>
#include <boost/mpl/empty.hpp>
#include <boost/mpl/back.hpp>
#include <boost/mpl/pop_back.hpp>
#include <boost/mpl/if.hpp>
#include <iostream>
using namespace boost::mpl;
template<class T>
class Test {
public:
void funcToCall() {
std::cout << "I'm called\n";
}
void update();
};
template<class Y, class T>
struct Update {
static void update(T* t) {
typedef typename pop_back<Y>::type vec_less;
if (back<Y>::type::value > 0)
t->funcToCall();
Update<typename if_<empty<vec_less>, void, vec_less >::type, T>::update(t);
}
};
template<class T>
struct Update<void ,T> {
static void update(T* t) {}
};
template<class T>
void Test<T>::update() {
Update<T, Test<T> >::update(this);
}
int main() {
Test<vector<int_<0>,int_<4>, int_<9> > > t;
t.update();
return 0;
}
类“Test”将是您原始的“TemplatedClass”。现在,您不再需要获取int模板参数列表,而只需获取一个boost :: mpl :: vector参数。其中包含您要传递的所有int,然后调用update函数,该函数将递归调用来自结构“Update”的update方法,该方法将负责在int大于0时调用“funcToCall()”方法。
上面粘贴的程序的输出为:
MacBook-Pro-di-Marcello:〜 Kariddi $ ./test
我被叫了
我被叫了
当然,您需要Boost libs才能使此示例正常工作。
您可以在此处找到有关MPL的信息:
http://www.boost.org/libs/mpl/doc/index.html
祝好,
马塞洛