Skip to content

Learn New Features of Modern CPP Make To Code Simpler

phuonglab edited this page Mar 2, 2022 · 3 revisions

C/C++

1. Tuples(Structured Bindings)

  • what is std::tuple and why do we need it ?

    • A tuple is an object that can hold a number of elements. The elements can be different data types. The elements of tuples are initialized as arguments in the order in which they will be accessed.

    • std::tuple is a type that can bind fixed size heterogeneous values together. We need to specify the type of elements as template parameter while creating tuple object.

  • Creating a std::tuple object

    // C++11
    std:::tuple<int, string> my_tuple(1, "test");
    // C++17
    std::tuple my_tuple(1, "test");
  • Getting elements from a std::tuple

    • In C++11

      int iVal = std::get<0>(my_tuple);
      int iVal = std::get<int>(my_tuple);
      int a, string b;
      std::tie(a,b) = my_tuple;
    • C++17

      auto [a, b] = my_tuple;
  • Get get N-th type from a tuple : std::tuple_element

    • Possible implementation

      auto mytuple = std::make_tuple (10,'a', true);
      std::tuple_element<1,decltype(mytuple)>::type first;
      
      std::tuple_element<1, std::tuple>::type first;
  • Example

    • Function use template parameter packs as argument

      template<typename ...Ts>
      int test(Ts...Args) {
        // capture the Args into a std::tuple for get types or value
        std::tuple<Ts...> input(Args...);
      
        // get 2nd arg
        std::cout << std::get<2>(input) << std::endl;
      
        // get type of 1st arg 
        std::cout << "type id: " << typeid(typename std::tuple_element<1, decltype(input)>::type).name() << std::endl;
        typename std::tuple_element<0, decltype(input)>::type test = 15;
        std::cout << "test: " << test << std::endl;
      }
      int main() {
        test(12, true, "String");
        return 0;
      }
    • Output

      String
      type id: b
      test: 15

2. std::variant and std::visit(safer union)

  • Types:

    • Check type of variant std::holds_alternative

    • compile-time indexed access to the types std::variant_alternative

CONFIG+=object_parallel_to_source
QMAKE_CXXFLAGS += -std=c++11
unix:OBJECTS_DIR = ./tmp
unix|win32: LIBS += -lpthread -lwebsockets -lrestbed -levent -luuid

3. Variadic templates and template parameter packs

  • Hiding C++ template parameter packs in a tuple

4. Structured Bindings

  • Returning compound objects

    // C++17
    if (auto [itelem, success] = mymap.insert(std::pair(‘a’, 100)); success) {
        // Insert success
    }
  • Iterating over a compound collection

    • C++11

      for (const auto& entry : mymap) {
          auto& key = entry.first;
          auto& value = entry.second;
          // Process entry
      }
    • C++17

      for (const auto&[key, value] : mymap) {
          // Process entry using key and value
      }

5. Smart pointer

  • Assign nullptr_t to free up memory object becomes empty, with the same behavior as if calling reset();

6. Tips and Tricks

  • Overload function

    • Syntax

      template<class... Ts>
      struct overload : Ts... { using Ts::operator()...; };
      template<class... Ts>
      overload(Ts...) -> overload<Ts...>;
    • Test code

      int main() {
        auto visitor = overload {
            [](auto arg) { std::cout << arg << std::endl; },
            [](const std::string& arg) { std::cout << arg << std::endl; },
            [](bool& arg) { std::cout << "thesis bool" << std::endl; arg = true;},
        };
        visitor(150);
        return 0;
      }
    • Output

      150
  • local time with timezone

    • time string: Use localtime → format string with std::strftime

      std::tm tm_time;
      char date_buf[64];
      auto now = std::chrono::system_clock::now();
      auto time_tt = std::chrono::system_clock::to_time_t(now);
      ::localtime_r(&time_tt, &tm_time);
      std::strftime(date_buf, sizeof(date_buf), "%Y-%m-%d %H:%M:%S", &tm_time);
    • epoch format: "timezone" is defined in <time.h>

      timestamp = mktime(&tm_time) - timezone;

Ref:

Clone this wiki locally