实现原理,
代码示例是照着《深入应用C++11》抄的。
- 使用变长模板参数构造任意对象。
- 使用std::aligned_storage实现任意长度对象的内存对齐。
- 使用std::forward减少参数拷贝,实现右值引用的完美转发。
optional.hpp
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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 |
#ifndef _OPTIONAL_HPP_
#define _OPTIONAL_HPP_ #include <type_traits> template <typename T> public: Optional(T&& v) { ~Optional() { Optional(const Optional& other) { Optional(Optional&& other) { Optional& operator=(Optional&& other) { Optional& operator=(const Optional& other) { template <class … Args> explicit operator bool() const { T& operator*() { T const& operator*() const { bool operator == (const Optional<T>& rhs) const { bool operator < (const Optional<T>& rhs) const { bool operator != (const Optional<T>& rhs) const { bool IsInit() const { private: void Destroy() { void Assign(const Optional& other) { void Assign(Optional&& other) { // 调用移动构造函数移动构造 void Copy(const data_t& val) { private: |
main.cpp测试代码
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 |
#include “optional.hpp”
#include <iostream> #include <string> using std::cout; #include <cstdlib> struct MyStruct { MyStruct(int a, int b): m_a(a), m_b(b) {} void testOp() { Optional<string> d = a; Optional<MyStruct> op; MyStruct t; cout << “t.m_a= ” << t.m_a << ” t.m_b= ” << t.m_b << endl; if(op) { cout << “t.m_a= ” << t.m_a << ” t.m_b= ” << t.m_b << endl; int main(void) { testOp(); cout << “请按任意键继续…” << endl; |
Makefile文件代码
1
2 3 4 5 6 7 8 9 10 11 12 13 |
TAR=main
WORKSPACE_DIR=. CC:=g++ .PHONY: build clear all build: all: clear build clear: |
测试程序的输出如下,