考虑:
static constexpr unsigned num_points{ 7810 };
std::array< double, num_points > axis;
for (int i = 0; i < num_points; ++i)
{
axis[i] = 180 + 0.1 * i;
}
axis
是一个类范围的常量。我想避免像任何其他全局变量一样对其进行初始化。它能在编译时完成吗?
这是整个类的最终形式:
// https://www.nist.gov/pml/atomic-spectroscopy-compendium-basic-ideas-notation-data-and-formulas/atomic-spectroscopy
// https://www.nist.gov/pml/atomic-spectra-database
struct Spectrum
{
static constexpr unsigned _num_points{ 7810 };
using Axis = std::array< double, _num_points >;
static constexpr Axis _x{ [] () // wavelength, nm
{
Axis a {};
for( unsigned i = 0; i < _num_points; ++i )
{
a[ i ] = 180 + 0.1 * i;
}
return a;
} () };
Axis _y {}; // radiance, W·sr−1·m−2
};
代码和变量混合在一起看起来不太美观,但至少公式呈现在读者眼前。其他解决方案需要大量输入以获取类中定义的常量和类型。
或者,如果我改变主意,可以在运行时简单地返回lambda函数。