C++ Can';类本身是否有静态constexpr成员实例?
此代码给了我不完整的类型错误。 有什么问题?类本身不允许有静态成员实例? 有没有办法达到同样的效果C++ Can';类本身是否有静态constexpr成员实例?,c++,c++11,constexpr,static-members,incomplete-type,C++,C++11,Constexpr,Static Members,Incomplete Type,此代码给了我不完整的类型错误。 有什么问题?类本身不允许有静态成员实例? 有没有办法达到同样的效果 struct Size { const unsigned int width; const unsigned int height; static constexpr Size big = { 480, 240 }; static constexpr Size small = { 210, 170 }; private: Size( ) = defa
struct Size
{
const unsigned int width;
const unsigned int height;
static constexpr Size big = { 480, 240 };
static constexpr Size small = { 210, 170 };
private:
Size( ) = default;
};
类允许具有相同类型的静态成员。但是,类在其定义结束之前是不完整的,并且不能用不完整类型定义对象。您可以声明类型不完整的对象,并稍后在其完整的位置(类外)对其进行定义 请看这里: 但是,这不适用于
constexpr
成员
有没有办法达到同样的效果
struct Size
{
const unsigned int width;
const unsigned int height;
static constexpr Size big = { 480, 240 };
static constexpr Size small = { 210, 170 };
private:
Size( ) = default;
};
通过“相同的结果”,您是否明确表示
Size::big
和Size::small
?在这种情况下,这可能足够接近:
struct Size
{
const unsigned int width = 0;
const unsigned int height = 0;
static constexpr Size big() {
return Size { 480, 240 };
}
static constexpr Size small() {
return Size { 210, 170 };
}
private:
constexpr Size() = default;
constexpr Size(int w, int h )
: width(w),height(h){}
};
static_assert(Size::big().width == 480,"");
static_assert(Size::small().height == 170,"");
作为一种解决方法,您可以使用一个单独的基类,在定义派生类中的常量时,该基类的定义是完整的
struct size_impl
{
//data members and functions here
unsigned int width;
unsigned int height;
};
struct size: public size_impl
{
//create the constants as instantiations of size_impl
static constexpr size_impl big{480,240};
static constexpr size_impl small{210,170};
//provide implicit conversion constructor and assignment operator
constexpr size(const size_impl& s):size_impl(s){}
using size_impl::operator=;
//put all other constructors here
};
//test:
constexpr size a = size::big;
如果愿意,可以将基类放在单独的命名空间中以隐藏其定义
代码使用clang和gcc编译您是否特别询问了
constexpr
静态成员?@PiotrSkotnicki是的。移除关键字并不能让它正常工作。一旦你移除关键字,你可以在类之外初始化它,当它已经是一个完整的类型时,您认为这对constexpr
成员不起作用是因为标准禁止还是因为编译器错误?@nyarlathotep108它不起作用是因为静态constexpr
成员需要内联初始化。那么呢?