【发布时间】:2022-01-18 04:50:10
【问题描述】:
我想将constexpr 功能赋予Color 类,如下所示:
// color.hpp
struct Color
{
Color(int r, int g, int b, int a);
static const Color Red;
// ...
};
// color.cpp
Color::Color(int r, int g, int b, int a) { /* ... */ }
const Color Color::Red(255, 0, 0, 255);
// ...
我希望保持此类的 API 不变,因此我想完全删除 color.cpp 并对头文件进行以下更改:
// color.hpp
struct Color
{
constexpr Color(int r, int g, int b, int a) { /* ... */ }
inline static constexpr Color Red{255, 0, 0, 255};
// ...
};
但是,上面的代码不会编译为constexpr static data members with the same type as the enclosing class are not allowed in C++。
当然,我可以将 API 更改为 ColorConstants::Red 之类的东西并将 Red 对象移出类,但我不想破坏现有用户。
我想到的唯一解决方法如下:
// color.hpp
struct Color
{
private:
struct ColorInit
{
int r, g, b, a;
constexpr ColorInit(int r, int g, int b, int a) { /* ... */ }
constexpr inline operator Color() const { /* ... */ }
}
public:
constexpr Color(int r, int g, int b, int a) { /* ... */ }
inline static constexpr ColorInit Red{255, 0, 0, 255};
};
上述解决方法允许大多数使用Color 的现有代码在更改后仍能编译,但如果在需要隐式转换为Color 的上下文中未使用Red,它显然会失败。
所以,我的问题是:是否可以解决上面看到的constexpr 限制,将Red 转换为常量表达式,同时仍保留原始Color::Red 语法并避免破坏现有代码?
【问题讨论】:
-
会有什么问题: static constexpr Color Red () { return {255, 0, 0, 255}; } ?
-
@engf-010:那将是 API 更改。
-
这几乎是一个duplicate,尽管完整性要求在不同的类上。
标签: c++ static initialization c++17 constexpr