如果您愿意定义自己的用户定义文字,您可以让它们创建constexpr Colour实例。
" [...] 文字运算符和文字运算符模板是普通函数(和函数模板),它们可以声明为 inline 或 constexpr,它们可能具有内部或外部链接,它们可以显式调用,可以获取它们的地址等。 ”
我还建议使用std::uint8_tRGBA 值,因为它非常适合该[0,255]范围。Astd::byte是“只是位的集合”。
C++14 示例:
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <sstream>
namespace colours {
struct Colour {
std::uint8_t r;
std::uint8_t g;
std::uint8_t b;
std::uint8_t a;
};
// helper to display values
std::ostream& operator<<(std::ostream& os, const Colour& c) {
std::ostringstream oss;
oss << std::hex << std::setfill('0') << '{'
<< std::setw(2) << static_cast<int>(c.r) << ','
<< std::setw(2) << static_cast<int>(c.g) << ','
<< std::setw(2) << static_cast<int>(c.b) << ','
<< std::setw(2) << static_cast<int>(c.a) << '}';
return os << oss.str();
}
// decode a nibble
constexpr std::uint8_t nibble(char n) {
if(n >= '0' && n <= '9') return n - '0';
return n - 'a' + 10;
}
// decode a byte
constexpr std::uint8_t byte(const char* b) {
return nibble(b[0]) << 4 | nibble(b[1]);
}
// User-defined literals - These don't care if you start with '#' or
// if the strings have the correct length.
constexpr int roff = 1; // offsets in C strings
constexpr int goff = 3;
constexpr int boff = 5;
constexpr int aoff = 7;
constexpr Colour operator ""_rgb(const char* s, std::size_t) {
return {byte(s+roff), byte(s+goff), byte(s+boff), 0xff};
}
constexpr Colour operator ""_rgba(const char* s, std::size_t) {
return {byte(s+roff), byte(s+goff), byte(s+boff), byte(s+aoff)};
}
// constants
constexpr auto red = "#ff0000"_rgb;
constexpr auto green = "#00ff00"_rgb;
constexpr auto blue = "#0000ff"_rgb;
}
void foo(const colours::Colour&) {
}
int main() {
using namespace colours;
constexpr Colour x = "#abcdef"_rgb;
std::cout << x << '\n';
std::cout << "#1122337f"_rgba << '\n';
std::cout << red << green << blue << '\n';
foo(red); // become (255, 0, 0, 255)
foo("#00ff00"_rgb); // become (0, 255, 0, 255)
// foo("240,100,50"_hsl); // I don't know hsl, but you get the picture
}
输出:
{ab,cd,ef,ff}
{11,22,33,7f}
{ff,00,00,ff}{00,ff,00,ff}{00,00,ff,ff}