C++11 如何根据类中的编译时常量生成类型别名?
我想写一个利用数值求积的类。正交顺序定义了我将使用的一些容器的大小。我想为这样的容器创建一个类型别名,它必须取决于正交顺序 下面的代码显示了我的测试。我必须重复类型别名定义中的顺序,从这个意义上讲,这感觉不太理想:C++11 如何根据类中的编译时常量生成类型别名?,c++11,C++11,我想写一个利用数值求积的类。正交顺序定义了我将使用的一些容器的大小。我想为这样的容器创建一个类型别名,它必须取决于正交顺序 下面的代码显示了我的测试。我必须重复类型别名定义中的顺序,从这个意义上讲,这感觉不太理想: #include <array> class Quadrature { public: static constexpr unsigned int getOrder() { return 3;
#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;
};
但这感觉是错误的,因为这是类的属性,因此应该在类范围内 您可以做的一件事是将值移动到成员变量中:
class Quadrature
{
private:
static constexpr unsigned int _order = 3;
public:
static constexpr unsigned int getOrder()
{
return _order;
}
using WeightsContainer = std::array<double, _order>;
// ...
};
否则,由于上述原因,您需要将函数拉到类范围之外。?@Quentin-我也看到过类似的帖子。我的问题不是这是否或为什么是非法的,而是这将是一个多么好的解决办法@BenjaminBihler您可以做的一件事就是将其作为成员变量:
static constexpr unsigned int order=3代码>@0x5453-你是对的,这可能是最好的解决方案。我想知道为什么我没有想到它。假设您需要函数的作用域进行计算,C++17具有static constexpr auto getOrder=[]{return 3;}
或甚至static constexpr unsigned int order=[]{return 3;}()代码>,但恐怕C++11没有这样的奢侈品。
class Quadrature
{
private:
static constexpr unsigned int _order = 3;
public:
static constexpr unsigned int getOrder()
{
return _order;
}
using WeightsContainer = std::array<double, _order>;
// ...
};
class Quadrature
{
public:
static constexpr auto getOrder = []()
{
return ...;
};
using WeightsContainer = std::array<double, getOrder()>;
// ...
};