我想在一个简单的模板类中包装一些东西:
template <int dim>
class internal {
static unsigned int table[dim][dim];
};
并为不同的模板化参数填写表格:
template <>
unsigned int
internal<1>::table[1][1] = {{0}};
template<>
unsigned int
internal<2>::table[2][2] =
{{0, 1},
{2, 3}
};
但我遇到了重复符号问题:
12 duplicate symbols for architecture x86_64
出了点问题,但是什么? p/s/快速搜索主题并不能解决类似问题。
最佳答案
定义需要在 .cpp 文件中。由于您肯定不会为大量维度给出这些定义,因此如果选择了错误的维度,您将希望得到编译器错误。那么您的实现可能如下所示:
标题:
template <int dim>
class internal {
static unsigned int table[dim][dim];
static_assert(dim <= 3, "Dimension too big!");
};
来源:
template <>
unsigned int
internal<1>::table[1][1] = {{0}};
template<>
unsigned int
internal<2>::table[2][2] =
{{0, 1},
{2, 3}
};
template<>
unsigned int
internal<3>::table[3][3] =
{{0, 1, 2},
{3, 4, 5},
{6, 7, 8}
};
注意:与普通静态模板成员变量不同,您不需要也不能在 header 中定义表,因为您没有它的模板版本,而是所有的完全特化。
关于c++ - 定义模板化静态类成员的不同实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17166093/