-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy path09_factory_functions.cpp
More file actions
53 lines (41 loc) · 1.38 KB
/
09_factory_functions.cpp
File metadata and controls
53 lines (41 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <cstddef>
namespace factory_method {
class Pixel final {
public:
static Pixel fromRgba(std::byte r, std::byte g, std::byte b, std::byte a) {
return Pixel{r, g, b, a};
}
static Pixel fromBgra(std::byte b, std::byte g, std::byte r, std::byte a) {
return Pixel{r, g, b, a};
}
// other members
private:
Pixel(std::byte r, std::byte g, std::byte b, std::byte a)
: r_(r), g_(g), b_(b), a_(a) {}
std::byte r_, g_, b_, a_;
};
} // namespace factory_method
namespace factory_function {
struct Pixel {
std::byte r, g, b, a;
private:
Pixel(std::byte r, std::byte g, std::byte b, std::byte a)
: r(r), g(g), b(b), a(a) {}
friend Pixel makePixelFromRgba(std::byte r, std::byte g, std::byte b,
std::byte a);
friend Pixel makePixelFromBgra(std::byte b, std::byte g, std::byte r,
std::byte a);
};
Pixel makePixelFromRgba(std::byte r, std::byte g, std::byte b, std::byte a) {
return Pixel{r, g, b, a};
}
Pixel makePixelFromBgra(std::byte b, std::byte g, std::byte r, std::byte a) {
return Pixel{r, g, b, a};
}
} // namespace factory_function
int main() {
auto black_pixel = factory_method::Pixel::fromRgba(
std::byte{0}, std::byte{0}, std::byte{0}, std::byte{0});
auto white_pixel = factory_function::makePixelFromRgba(
std::byte{255}, std::byte{255}, std::byte{255}, std::byte{0});
}