Mig*_*igi 8 c++ lookup-tables compile-time-constant
假设我有一个存储前10个素数的数组,如下所示:
const int primes[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};
Run Code Online (Sandbox Code Playgroud)
只要我有1个.cpp文件,这一切都非常简单和简单.但是,如果我有多个.cpp文件,我真的不知道在哪里放这个数组.
一个明显的解决方案是:
// primes.h:
extern const int primes[10];
// primes.cpp:
extern const int primes[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};
Run Code Online (Sandbox Code Playgroud)
但是,问题是primes数组不再是编译时常量.假设x.cpp想要进行一些涉及素数[k]的繁重计算,使用ka编译时间常数,它必须进行实际的内存查找.我不喜欢那样.
那么我在哪里放置这个数组:
这个怎么样?
inline int prime(int i) {
static const int primes[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};
return primes[i];
}
Run Code Online (Sandbox Code Playgroud)
PS:即使上面的"明显的解决方案"花了我相当长的时间来写.显然const变量默认有内部链接,所以我不得不在primes.cpp文件中添加"extern"以使其工作.
我认为这应该有效(现在在Migi的测试发现一个缺陷后更新):
template <bool dummy>
struct primes_lut
{
static const int values[];
};
template<bool dummy>
const int primes_lut<dummy>::values[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 };
static auto& primes = primes_lut<true>::values;
Run Code Online (Sandbox Code Playgroud)
另一种方法:
struct primes_lut { int values[10]; };
inline const primes_lut& primes_lut_provider(void)
{
static const primes_lut values = { {2, 3, 5, 7, 11, 13, 17, 19, 23, 29} };
return values;
}
static const int (&primes)[10] = primes_lut_provider().values;
Run Code Online (Sandbox Code Playgroud)
最后,现代链接器不需要这些技巧,而不是实现常量折叠.