我想写一个利用数值求积的类。正交顺序定义了我将要使用的某些容器的大小。我想为这样的集装箱做一个类型的别名,它必须取决于正交顺序。
下面的代码显示了我的尝试。在某种意义上,我必须在别名定义中重复顺序,这感觉不太理想:
#include <array>
class Quadrature
{
public:
static constexpr unsigned int getOrder()
{
return 3;
}
// This line doesn't compile!
//
// using WeightsContainer = std::array<double, getOrder()>;
//
// g++ says "error: 'static constexpr unsigned int Quadrature::getOrder()'
// called in a constant expression before its definition is complete"
// This line compiles, but repeats the order. :-(
using WeightsContainer = std::array<double, 3>;
private:
WeightsContainer container;
};
我发现的一个解决方案是引入模板参数Order
。但实际上,我想确定求积的顺序,引入模板参数会使它变。
是否有可能使顺序成为编译时常量和在我的类型别名定义中使用它?
编辑:
为了完整起见,我当然可以使用预处理器定义。但这感觉很老套。:-)
编辑2:
好吧,我找到了另一种可能性。我可以在类范围之外添加一个函数,如下所示:
constexpr unsigned int order()
{
return 3;
}
但这感觉是错误的,因为这是类的属性,因此应该在类范围内!
发布于 2019-03-29 05:09:51
您可以做的一件事是将值移动到一个成员变量中:
class Quadrature
{
private:
static constexpr unsigned int _order = 3;
public:
static constexpr unsigned int getOrder()
{
return _order;
}
using WeightsContainer = std::array<double, _order>;
// ...
};
如果您需要更复杂的计算,而不仅仅是return 3
,那么在C++17下可以使用lambda,正如@Quentin所提到的:
class Quadrature
{
public:
static constexpr auto getOrder = []()
{
return ...;
};
using WeightsContainer = std::array<double, getOrder()>;
// ...
};
否则,由于提到的here的原因,您需要将函数拉出类范围之外。
https://stackoverflow.com/questions/55417328
复制相似问题