给定一个像这样的模板

template<int dim> class Point { ... };

这个模板可以像
template class Point<0>;
template class Point<1>;
template class Point<2>;
template class Point<3>;

与其像上面那样单独实例化每个模板,不如通过一个调用递归地实例化它们。
template class RecursiveInstantiate<Point, 3>;

其中RecursiveInstantiate<T, i>将实例化T<i>T<i-1>,...,T<0>。是否可以以某种方式创建此类RecursiveInstantiate?如果不可能,您是否知道使用预处理器的方法?

实际上,我有兴趣针对{0,1,2,3}中i1,i2,i3的所有组合的具有多个模板参数(如Node<int i1,int i2,int i3>)的类进行通用化。但是我希望能够自己完成第二部分的工作。

任何建议,也解释为什么我想实现的目标是不可能的,我们对此表示赞赏。

更新:谢谢您到目前为止的评论。我现在可以更清楚地看到问题所在。线
template class Point<3>;

实例化模板并将其符号导出到目标文件。形式的实例化
template class RecursiveInstantiate<Point, 3>;

可以实例化类class Point<3>class Point<2>,...。显然,这仅在本地发生。模板不会导出到目标文件。也许我将不得不寻找使用预处理器的解决方案。

正如我现在所看到的,我一开始并没有提出足够准确的问题,我感谢您的回答,并选择了正确的回答。

注意:我正在使用g++/clang作为编译器的linux上尝试此操作。

最佳答案

您可以制作一些Instantinator类:

template <unsigned int N> struct Instantiator
{
  Point<N> p;
  Instantiator<N-1> i;
};

template <> struct Instantiator<0>
{
  Point<0> p;
};

然后只需添加一个显式实例化:template struct Instantiator<81>;
您可以按字典顺序将此思想扩展到任意数量的整数参数。

正如@Georg所说的,让我们使其通用:
template <template <unsigned int> class T, unsigned int N> struct Instantiator
{
  T<N> t;
  Instantiator<T, N-1> i;
};

template <template <unsigned int> class T> struct Instantiator<T, 0>
{
  T<0> t;
};

template struct Instantiator<Point, 82>;

关于c++ - 递归显式模板实例化有可能吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7395113/

10-11 22:46
查看更多