Line data Source code
1 : /**
2 : * @file BItem.h
3 : * @copyright (c) 2014 by Petr Zemek (s3rvac@gmail.com) and contributors
4 : * @license BSD, see the @c LICENSE file for more details
5 : * @brief Base class for all items (integers, strings, etc.).
6 : */
7 :
8 : #ifndef BENCODING_BITEM_H
9 : #define BENCODING_BITEM_H
10 :
11 : #include <memory>
12 :
13 : namespace bencoding {
14 :
15 : class BItemVisitor;
16 :
17 : /**
18 : * @brief Base class for all items (integers, strings, etc.).
19 : */
20 304 : class BItem: public std::enable_shared_from_this<BItem> {
21 : public:
22 : virtual ~BItem() = 0;
23 :
24 : /// @name BItemVisitor Support
25 : /// @{
26 :
27 : /**
28 : * @brief Accepts the item by the given @a visitor.
29 : *
30 : * Subclasses should implement this function in this way:
31 : * @code
32 : * void Subclass::accept(BItemVisitor *visitor) {
33 : * visitor->visit(this);
34 : * }
35 : * @endcode
36 : */
37 : virtual void accept(BItemVisitor *visitor) = 0;
38 :
39 : /// @}
40 :
41 : /**
42 : * @brief Casts the item to the given subclass of BItem.
43 : *
44 : * @tparam T Subclass of BItem.
45 : */
46 : template <typename T>
47 72 : std::shared_ptr<T> as() {
48 : static_assert(std::is_base_of<BItem, T>::value,
49 : "T has to be a subclass of BItem");
50 :
51 72 : return std::dynamic_pointer_cast<T>(shared_from_this());
52 : }
53 :
54 : protected:
55 : BItem();
56 :
57 : private:
58 : // Disable copy construction and assignment for this class and subclasses.
59 : BItem(const BItem &) = delete;
60 : BItem &operator=(const BItem &) = delete;
61 : };
62 :
63 : } // namespace bencoding
64 :
65 : #endif
|