假设,我有这样定义的类:
template<unsigned int N>
class A { ... }
问题是如何用 N 遍历这个类?
for(unsigned int i = 0; i < 10; ++i) {
A<i>().doStuff();
}
也许 C++ 11 中有一些新功能或者 contrexp 的一些很酷的用法。
下一个问题是:如果可能的话——如何存储这些类?
更新 我知道它在编译时有效。假设,我有多达 10 个这样的全局类,它们仅在 N 上有所不同。例如:
A<1> first;
A<2> second;
A<42> third;
A<1034> fourth;
并且假设,我应该调用比我的值大 N 的那个人。如果没有机会迭代,那么我就得写很长的if-else结构。
void doAppropriateStuff(int value) {
if (value < 1) {
first.doStuff();
} else if (value < 2) {
second.doStuff();
} else if (value < 42) {
third.doStuff();
} else if (value < 1034) {
fourth.doStuff();
} else {
...
}
}
希望,问题变得更清楚了。 当我用谷歌搜索时,这是不可能的,我明白为什么。只寄希望于 C++11 和 SO 社区。 谢谢。
最佳答案
for 循环显然是不可能的,因为它是在运行时运行的,模板参数需要是编译时常量。以下是您可以如何做到这一点。
这些是用于构造整数序列作为模板参数包的实用程序类:
template< std::size_t... Ns >
struct indices {
typedef indices< Ns..., sizeof...( Ns ) > next;
};
template< std::size_t N >
struct make_indices {
typedef typename make_indices< N - 1 >::type::next type;
};
template<>
struct make_indices< 0 > {
typedef indices<> type;
};
完成工作的函数:
#include <initializer_list>
template<size_t... Is>
void foo(indices<Is...>)
{
auto list = { (A<Is>().doStuff(), 0)... };
}
然后你这样调用这个函数:
foo(make_indices<10>::type());
关于c++ - 在 C++ 11 中迭代模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22642097/