c++ - 在 C++ 11 中迭代模板类

标签 c++ templates c++11 constexpr

假设,我有这样定义的类:

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/

相关文章:

c++ - 从父模板中使用 child 的内部类

c++ - Variadic 模板在多个参数上给出错误

c++ - 在 C++ 的父构造函数中调用重写的方法

c++ - 如何在 C++ 中使用转义序列指定 INFINITY (U+221E)?

c++ - output_tensor 出现 dlib fatal error

具有默认参数的 C++ 模板参数

c++ - boost::enable_if 类模板方法

c++ - 在被调用函数中更改函数指针(std::function)是否安全?

c++ - 如何在 gdb 中的内存位置添加断点

第三方库和同名类的 C++ 命名空间问题