我曾经写过一些代码,在编译时为某些模板元编程生成静态表/数组(这个想法是可以在编译时构建 C 风格的字符串(它们只是char
数组))。这个想法和代码是基于林大卫's answer:
#include <iostream>
const int ARRAY_SIZE = 5;
template <int N, int I=N-1>
class Table : public Table<N, I-1>
{
public:
static const int dummy;
};
template <int N>
class Table<N, 0>
{
public:
static const int dummy;
static int array[N];
};
template <int N, int I>
const int Table<N, I>::dummy = Table<N, 0>::array[I] = I*I + 0*Table<N, I-1>::dummy;
template <int N>
int Table<N, 0>::array[N];
template class Table<ARRAY_SIZE>;
int main(int, char**)
{
const int *compilerFilledArray = Table<ARRAY_SIZE>::array;
for (int i=0; i < ARRAY_SIZE; ++i)
std::cout<<compilerFilledArray[i]<<std::endl;
}
使用 GCC 4.9.2 编译此代码有效:
$ g++-4.9 -Wall -pedantic b.cpp
$ ./a.out
0
1
4
9
16
不过,Clang 3.5 抱怨道:
$ clang++ -Wall -pedantic b.cpp
Undefined symbols for architecture x86_64:
"Table<5, 0>::dummy", referenced from:
___cxx_global_var_init in b-b8a447.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
dummy
and array
都在外部给出了定义Table
类(声明它们的地方)。据我所知,这应该满足链接器的要求。
这是 clang 的错误吗?