Category Archives: Programming languages

An example of how r-value reference works in C++

An example of extending the lifetime of a temporary:

#include <iostream>

int main()
{
    int a = 1;
    int&& b = std::move(a);
    int&& c = b + 1;

    b = b + 1;
    c = c + 1;

    std::cout << a << b << c;
}

The output is:

223
(more…)

Using std::future as a coroutine in C++20

In C++20 it is possible to do this:

std::future<int> compute(as_coroutine) {
  int a = co_await std::async([] { return 6; });
  int b = co_await std::async([] { return 7; });
  co_return a * b;
}
 
std::future<void> fail(as_coroutine) {
  throw std::runtime_error("bleah");
  co_return;
}
 
int main() {
  std::cout << compute({}).get() << '\n';
 
  try {
    fail({}).get();
  } catch (const std::runtime_error &e) {
    std::cout << "error: " << e.what() << '\n';
  }
}
(more…)

Switching to a different thread with async/await in C#

The code below switches to a different thread when the execution of Main() is resumed at line 11:

internal class Program
{
    static async Task Main(string[] args)
    {
        try
        {
            HttpClient client = new HttpClient();

            Console.WriteLine($"Thread: {Thread.CurrentThread.ManagedThreadId}");
                
            HttpResponseMessage response = await client.GetAsync("https://developernote.com/");

            Console.WriteLine($"Thread: {Thread.CurrentThread.ManagedThreadId}");

            response.EnsureSuccessStatusCode();

            string responseBody = await response.Content.ReadAsStringAsync();

            Console.WriteLine($"Thread: {Thread.CurrentThread.ManagedThreadId}");

            Console.WriteLine(responseBody);
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine("\nException Caught!");

            Console.WriteLine($"Thread: {Thread.CurrentThread.ManagedThreadId}");

            Console.WriteLine($"Message: {e.Message}");
        }
    }
}
(more…)

My experimentation with QML Repeater

I was able to define a Repeater that displays cryptocurrency market orders:

(more…)

Waitable QTimer with C++20 coroutines

Found an example of overriding co_await operator and was able to implement my own version:

#include <QTimer>
#include <QMetaObject>

#include <chrono>
#include <coroutine>

//QTimer accepts only milliseconds.
class TimeAwaitable
{
public:

    explicit TimeAwaitable(std::chrono::milliseconds d) : m_d(d) {}

    ~TimeAwaitable()
    {
        if (m_connection)
        {
            QObject::disconnect(m_connection);
        }
    }

    bool await_ready() const noexcept
    {
        return m_d <= std::chrono::milliseconds(0);
    }

    void await_suspend(std::coroutine_handle<> h) noexcept
    {
        m_connection = QObject::connect(&m_timer, &QTimer::timeout,
            [this, h]()
            {
                QObject::disconnect(m_connection);

                h.resume();
            });

        m_timer.setSingleShot(true);
        m_timer.start(m_d);
    }

    void await_resume() const noexcept {}

private:

    std::chrono::milliseconds m_d;
        
    QTimer m_timer;

    QMetaObject::Connection m_connection;
};

inline TimeAwaitable operator co_await(std::chrono::milliseconds d) noexcept
{
    return TimeAwaitable{ d };
}

For those who did not work with QT, QTimer::singleShot simply calls the lambda on the current thread after a given interval.

(more…)

An example of real-time TableView in QML

Looks like CheckBox-es respond to clicks and work correctly even if they are in a TableView that is updated once a second:

(more…)

Replace a substring in source file names

For example, the command below

find -name "*android*" -exec rename 's/android/windows/' {} \;

renames the following source files:

androidinappproduct.cpp
androidinappproduct.h
androidinapppurchasebackend.cpp
androidinapppurchasebackend.h
androidinapptransaction.cpp
androidinapptransaction.h
(more…)

Using QML_ELEMENT with CMake

There is an example of using QML_ELEMENT in qt5\qtdeclarative\examples\quick\scenegraph\openglunderqml and qt_add_qml_module in CMake:

qt_add_qml_module(openglunderqml
    URI OpenGLUnderQML
    VERSION 1.0
    QML_FILES main.qml
    RESOURCE_PREFIX /scenegraph/openglunderqml
    NO_RESOURCE_TARGET_PATH
)

In QML it imports the module:

import OpenGLUnderQML 1.0
(more…)

Adding a header to source files

Put the header content into a text file and load it into a variable:

cd ~/temp/
nano h.txt
h=$(<h.txt)
(more…)

Did you already learn what are C++ concepts?

In C++20 we can do this:

#include <ranges>
#include <vector>

template <std::ranges::range Range>
    requires std::same_as<std::ranges::range_value_t<Range>, int>
auto TransformIt(Range r)
{
    return r | std::views::transform([](int n) { return n * n; });
}

int main()
{
    std::vector<int> v;
    auto r = TransformIt(v);
    return 0;
}
(more…)