jeudi 31 août 2023

C++ syntax problem when template-ifying a source [duplicate]

When making some code more geeric by turning some classes into class templates, I am getting the following syntax error with C++11 and g++ v11.4:

foo.cpp: In member function ‘const EP<F>::Id* EP<F>::Lex::search(const char*) const’:
foo.cpp:64:29: error: expected primary-expression before ‘,’ token
   64 |         return ids_.search<S, const char*> (name); // ERROR 1 HERE
      |                             ^
foo.cpp:64:31: error: expected primary-expression before ‘const’
   64 |         return ids_.search<S, const char*> (name); // ERROR 1 HERE
      |                               ^~~~~
foo.cpp:64:31: error: expected ‘;’ before ‘const’
foo.cpp:64:42: error: expected unqualified-id before ‘>’ token
   64 |         return ids_.search<S, const char*> (name); // ERROR 1 HERE
      |                                          ^
foo.cpp: In member function ‘EP<F>::Id* EP<F>::Lex::search(const char*)’:
foo.cpp:69:40: error: expected primary-expression before ‘const’
   69 |         return ids_.search<Id::Search, const char*> (name); // ERROR 2 HERE
      |                                        ^~~~~
foo.cpp:69:40: error: expected ‘;’ before ‘const’
foo.cpp:69:51: error: expected unqualified-id before ‘>’ token
   69 |         return ids_.search<Id::Search, const char*> (name); // ERROR 2 HERE
      |                                                   ^

So maybe the < is read as less-than instead of as template argument?

Unfortunately, the error messages don't help with finding the correct syntax. Checking with diff shows no obvious typos.

For reference, here is (a reduced test case of) my take on the templated version of EP and the original version where EP is a plain struct:

EP as class template (syntax error)

#include <cstring>
#include <iostream>
#include <cmath>

template<class X>
struct XTree
{
    typedef X element_type;
    X a_, b_;
    static X nan_;

    template<class S, class V>
    const X* search (V const& val) const
    {
        const S& s = S();
        if (s (a_, val) == 0) return &a_;
        if (s (b_, val) == 0) return &b_;
        return &nan_;
    }

    template<class S, class V>
    X* search (V const& val)
    {
        const S& s = S();
        if (s (a_, val) == 0) return &a_;
        if (s (b_, val) == 0) return &b_;
        return &nan_;
    }
};

template<class F>
struct EP
{
    struct Id;
    struct Lex;
};

template<class F>
struct EP<F>::Id
{
    const char* name_ = "NaN";
    F value_;

    Id (const char* name, F val) : name_(name), value_(val) {}

    struct Search
    {
        int operator () (const Id& i, const char* const& name) const
        {
            return std::strcmp (i.name_, name);
        }
    };
};

template<class F>
struct EP<F>::Lex
{
    typedef XTree<EP<F>::Id> Tree;
    Tree ids_ { { "aa", 11.0 }, { "cc", 22.0 } };

    auto search (const char* name) const -> const typename EP<F>::Id*
    {
        using S = typename Id::Search;
        return ids_.search<S, const char*> (name); // ERROR 1 HERE
    }

    auto search (const char* name) -> typename EP<F>::Id*
    {
        return ids_.search<Id::Search, const char*> (name); // ERROR 2 HERE
    }

    F value (const char *str) const
    {
        const EP<F>::Id *id = search (str);
        return id->value_;
    }
};

template<> EP<double>::Id XTree<EP<double>::Id>::nan_ { "NaN", std::nan("") };


int main()
{
    auto lex = EP<double>::Lex();
    std::cout << lex.value ("aa") << std::endl;
    std::cout << lex.value ("bb") << std::endl;
    std::cout << lex.value ("cc") << std::endl;

    return 0;
}

EP as class (works)

#include <cstring>
#include <iostream>
#include <cmath>

template<class X>
struct XTree
{
    typedef X element_type;
    X a_, b_;
    static X nan_;

    template<class S, class V>
    const X* search (V const& val) const
    {
        const S& s = S();
        if (s (a_, val) == 0) return &a_;
        if (s (b_, val) == 0) return &b_;
        return &nan_;
    }

    template<class S, class V>
    X* search (V const& val)
    {
        const S& s = S();
        if (s (a_, val) == 0) return &a_;
        if (s (b_, val) == 0) return &b_;
        return &nan_;
    }
};


struct EP
{
    struct Id;
    struct Lex;
};


struct EP::Id
{
    const char* name_ = "NaN";
    double value_;

    Id (const char* name, double val) : name_(name), value_(val) {}

    struct Search
    {
        int operator () (const Id& i, const char* const& name) const
        {
            return std::strcmp (i.name_, name);
        }
    };
};


struct EP::Lex
{
    typedef XTree<EP::Id> Tree;
    Tree ids_ { { "aa", 11.0 }, { "cc", 22.0 } };

    auto search (const char* name) const -> const EP::Id*
    {
        using S = typename Id::Search;
        return ids_.search<S, const char*> (name); // fine
    }

    auto search (const char* name) -> EP::Id*
    {
        return ids_.search<Id::Search, const char*> (name); // fine
    }

    double value (const char *str) const
    {
        const EP::Id *id = search (str);
        return id->value_;
    }
};

template<> EP::Id XTree<EP::Id>::nan_ { "NaN", std::nan("") };


int main()
{
    auto lex = EP::Lex();
    std::cout << lex.value ("aa") << std::endl;
    std::cout << lex.value ("bb") << std::endl;
    std::cout << lex.value ("cc") << std::endl;
    return 0;
}

Maybe someone is so kind to show me the correct syntax. FYI, the output of the non-template EP version is:

11
nan
22

Replace handwritten for loop in C++ when index has to be accessed inside lambda

I am trying to replace the hand written for loop in using_for_loop() by algorithm methods. no_for_loop() is the version that would replace using_for_loop(). Any clue on how to implement the lambda? In general, for a vector of vectors how to iterate the inner for loop in the lambda or a function object. It would require access to the outer loop index. If I were to use std::distance() to compute the index inside the lambda, I would need access to the the iterator. But I have only the value/object inside passed to the lambda. Is there is a way to pass the iterator to the lambda?
The motivation is to follow the suggestion made by the book Effective STL: 50 Specific Ways to Improve Your Use of the Standard Template Library by Scott Meyers. One of them is Item 43: Prefer algorithm calls to hand-written loops

Note: In the real program "vec" is the inputs. I made it local and added assign_vec(10'000'000,vec); call to make it stand alone.

#include <algorithm> 
void assign_vec(const int64_t &count, std::vector<std::array<int64_t, 3>> &v)
{
  for (int i = 0; i < count;++i)
  {
    std::array<int64_t, 3 > a{i,i+1,i+2};
    v.emplace_back(a);
  }
}

int using_for_loop() {
  std::vector<std::array<int64_t, 3>> vec;
  assign_vec(10'000'000,vec);
  size_t k{};
  for (auto i = (size_t)0, n = vec.size(); i < n; )
  {
    auto j = i + (size_t)1;
    for (; j < n; ++j)
    {
      if (vec[i][0] != vec[j][0] || std::minmax(vec[i][1], vec[i][2]) != std::minmax(vec[j][1], vec[j][2]))
        break;
    }

    if (i + (size_t)1 == j)
      vec[k++] = vec[i];

    i = j;
  }
  vec.resize(k);
  return 0;
}

int no_for_loop() {
  std::vector<std::array<int64_t, 3>> vec;
  assign_vec(10'000'000, vec);
  size_t k{};
  //??std::for_each(std::begin(vec), std::end(vec), []() {});
  vec.resize(k);
  return 0;
}

How to add an hyperlink to a QImage in a QTextTableCell?

My application has a pdf report creator which displays a table with some information. One of the columns must display a location pin icon and when clicked this must open a link to a google maps location.

I tried to use a HTML-formatted QString to create the link, something like this:

const QString html = "\<a style='font-size:8px;' href='http://www.google.com/maps/place/" + xPosStr + "," + yPosStr + "'\>" + "Location" + "</a>"

Then I insert this string by using the insertHtml method.

And as expected the table cell displays the link with the text "Location" on it. This text can be clicked and it opens my browser with the website correctly. But now I try to change the "Location" text to an image. This image is loaded using a QImage, not a QWidget, so I can't use any QWidget property because this process occurs outside of my UI thread. So when I change the HTML-formatted QString to something like this:

const QString html = "<a href='http://www.google.com/maps/place/" + xPosStr + "," + yPosStr + "'>" + "<img src='" + locationIcon + "'>" + "</a>";

This loads the image correctly but the href part is seemingly lost. Maybe it's because the QImage is not a clickable object. I'm not sure why this happens.

This method below will give more information about my problem:

void _setCellPositionImage(QTextTableCell cell, const Point& position, QTextChatFormat& charFormat)
{
    QTextBlockFormat centerAlignment;
    centerAlignment.setAlignment(Qt::AlignCenter);

    QTextCursor cellCursor = cell.firstCursorPosition();
    cellCursor.setBlockFormat(centerAlignment);
    cellCursor.mergeBlockCharFormat(imgFormat);

    const bool isValidPosition = !(is_near_zero(position.x) && is_near_zero(position.y));
    if (isValidPosition)
    {
        const QString xPosStr = QString::number(position.x, 'f', 6);
        const QString yPosStr = QString::number(position.y, 'f', 6);

        // This loads the image correctly but the href is lost.
        const QString html = "<a href='http://www.google.com/maps/place/" + xPosStr + "," + yPosStr + "'>" + "<img src='" + locationIcon + "'>" + "</a>";

        cellCursor.insertHtml(html);
    }
    else
    {
        cellCursor.insertText("--");
    }
}

I'm using C++11 and Qt 5.14. Thanks in advance.

Some issues with time on x axis

I have a vector with date and with values. The problem is that the graph does not correctly display time on the x-axis. For example, if the time is 17:27:... the chart displays 05:49:... and because of this it is plotted incorrectly!

#include "qcustomplot.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QCustomPlot* plot = new QCustomPlot();
    setCentralWidget(plot);
    plot->xAxis->setLabel("Time");
    plot->yAxis->setLabel("Position");

    QSharedPointer<QCPAxisTickerDateTime> dateTicker(new QCPAxisTickerDateTime);
    dateTicker->setDateTimeFormat("HH:mm:ss.zzz");
    plot->xAxis->setTicker(dateTicker);

    QVector<double> xData, yData;

    QVector<QString> dateTime = {"2023-08-15 17:27:02.994591",
                                   "2023-08-15 17:27:16.240445",
                                   "2023-08-15 17:27:16.441496",
                                   "2023-08-15 17:27:16.639997",
                                   "2023-08-15 17:27:16.841136",
                                   "2023-08-15 17:27:17.424592",
                                   "2023-08-15 17:27:17.240649",
                                   "2023-08-15 17:27:17.441818",
                                   "2023-08-15 17:27:17.640868",
                                   "2023-08-15 17:27:17.841120",
                                };

    for (const QString& value : dateTime)
    {
        QStringList values = value.split(" ");
        QDateTime dataTime = QDateTime::fromString(values[1].chopped(3), "HH:mm:ss.zzz");
        xData.append(dataTime.toMSecsSinceEpoch());
    }

    for (int i = 0; i < dateTime.size(); ++i)
    {
        yData.append(i + 1);
    }
    QCPGraph* graph = plot->addGraph();
    graph->setData(xData, yData);
    plot->setInteractions(QCP::iRangeZoom | QCP::iRangeDrag);
    plot->rescaleAxes();
    plot->replot();
}

mercredi 30 août 2023

OpenMP atomic update of map value

Is the follwing increment operation thread safe?

std::map<uint64_t, uint64_t> val_counts{};

#pragma omp parallel for num_threads(32)
for (uint16_t ix = 0; ix < 96; ++ix) {

#pragma omp atomic update
    val_counts[ix%5]++;

}

Based on my experiments, it seems to be thread safe. Howewer, I wanted to be sure, as I am not sure what this translates into. An alternative would be using #pragma omp critical, of course.

mardi 29 août 2023

How to use in std::variant a type that uses the same std::variant?

I need a type to store variables of various types, including vectors and maps with this type, how can I do this in C++17?

The example below shows what I need to get, but it does not work.

#include <map>
#include <variant>
#include <vector>

template<class V>
using var_type_base = std::variant<bool, int, double, std::string, std::vector<V>, std::map<std::string, V>>;
using var_type = var_type_base<var_type_base>;


int main()
{
    std::map<std::string, int> m;
    var_type v = m;
    return 0;
}

Why override keyword in C++ is altering code flow

I came across a very strange C++ code where adding a override keyword in header file seems to alter the code flow.

I was debugging a issue where a virtual function was being invoked. Strangely, the code jumped to some different virtual function in derived class. There was nothing in call stack so I assume something is messed up with vtable. After some trial and error I saw that the function where my code was jumping did not have override keyword mentioned. I added it and it seem to fix issue of control being jumped into that function.

What I knew till date is that override is just a syntactic sugar. If so, can anyone who has deep understanding of vtables, overrides help me to understand what might be happening?

  • virtual string prefEnv() const;
  • virtual string prefEnv() const override;

how to hide tracer and label on chart

I have one problem, i cant hide label and tracer after moving mouse cursor from one chart to another. My task is to make a tracer with a label appear when you move the mouse cursor over the chart, and when you move the cursor to another chart, it should disappear on the chart on which it was.

The problem is that the tracer does not disappear after switching to another chart.

void Plotter::onMouseMoveEvent(QMouseEvent* event)
{
    QPoint mousePos = event->pos();
    double coordX = xAxis->pixelToCoord(event->pos().x());
    double coordY = yAxis->pixelToCoord(event->pos().y());


    if (rect().contains(mousePos))
    {
        customizeTracer(coordX, coordY);
        QPointF tracerCoords = mTracer->position->coords();
        double xTracerCoord = tracerCoords.x();
        double yTracerCoord = tracerCoords.y();

        QTime time = QTime(0, 0).addMSecs(static_cast<int>(xTracerCoord));
        QString formattedTime = time.toString("HH:mm:ss.zzz");
        customizeLabel(xTracerCoord, yTracerCoord, formattedTime);
        replot();
    }
    else
    {
        removeItem(mTracer);
        removeItem(mLabel);
        replot();
    }
}


void Plotter::customizeTracer(const double coordX, const double coordY)
{
    mTracer->setGraph(graph());
    mTracer->setStyle(QCPItemTracer::tsCircle);
    mTracer->position->setType(QCPItemPosition::ptPlotCoords);
    mTracer->position->setCoords(coordX, coordY);
    mTracer->setGraphKey(coordX);
    mTracer->setPen(QPen(QColor("red")));
    mTracer->setSize(5);
    mTracer->setBrush(QColor("red"));
    mTracer->setInterpolating(true);
    mTracer->setVisible(true);
    mTracer->updatePosition();
}


void Plotter::customizeLabel(const double coordX, const double coordY, const QString& formattedTime)
{
    mLabel->setPositionAlignment(Qt::AlignLeading | Qt::AlignBottom);
    mLabel->position->setCoords(coordX, coordY);
    mLabel->setText(QString("Time %1 | Position %2").arg(formattedTime).arg(coordY));
}

How to use pwrite to write files in parallel on Linux by C++?

I'm tring to create several threads to write some data chunks into one file in parallel. Some part of my code is below:

void write_thread(float* data, size_t start, size_t end, size_t thread_idx) {
    auto function_start_time = std::chrono::high_resolution_clock::now();
    auto start_duration = std::chrono::duration_cast<std::chrono::milliseconds>(function_start_time - global_start_time).count();

    std::cout << "Thread " << thread_idx << " started after " << start_duration << " ms from global start time." << std::endl;

    pwrite(fd, data + start, (end - start) * sizeof(float), start * sizeof(float));
    close(fd);

    auto function_end_time = std::chrono::high_resolution_clock::now();
    auto end_duration = std::chrono::duration_cast<std::chrono::milliseconds>(function_end_time - global_start_time).count();

    std::cout << "Thread " << thread_idx << " ended after " << end_duration << " ms from global start time." << std::endl;

    thread_durations[thread_idx] = std::chrono::duration_cast<std::chrono::milliseconds>(function_end_time - function_start_time);

int main() {
    fd = open(FILENAME, O_RDWR | O_CREAT, 0666);
    if (fd < 0) {
        perror("Failed to open file");
        return 1;
    }
    float* data = new float[FLOATS_COUNT];
    for (size_t i = 0; i < FLOATS_COUNT; i++) {
        data[i] = static_cast<float>(i);
    }

    auto globalStartTime = std::chrono::high_resolution_clock::now();

    std::vector<std::thread> write_threads;
    size_t floats_per_thread = FLOATS_COUNT / THREADS_COUNT;
    for (size_t t = 0; t < THREADS_COUNT; t++) {
        size_t start = t * floats_per_thread;
        size_t end = (t == THREADS_COUNT - 1) ? FLOATS_COUNT : start + floats_per_thread;
        write_threads.emplace_back(write_thread, data, start, end, t);
    }
    for (auto& t : write_threads) {
        t.join();
    }
    ....
}

On my Ubuntu server, I create some data chunks and create the same numbers threads to write these chunks into one file. However, by printing the function which threads excutes, I find that all threads start at the same time, but the threads are ending one by one, each at the same interval. So I think it's sequential execution.

However, when I run the same code on my MACOS, I find that all threads end at the same time!(interval less than 2ms)

I'm wondering what was happended on my Ubuntu server? What's casuing this difference and how to deal with it?

Thanks!

dimanche 27 août 2023

Bagaimana cara membuat hello world menggunakan bahasa C [closed]

Bagaimana cara membuatnya?

Saya berharap bisa mendapat jawaban beserta langkah-langkah secara detail,agar saya dapat mencobanya. Coding untuk membuat hello world. Saya sudah mencoba berkali-kali namun tidak bisa.Saya tidak tahu langkah-langkah membuatnya.

samedi 26 août 2023

linker loading same file even though have header guards

It seems like my linker is including the serialize.h file multiple times based on the error but this file is of the format

// // Created by mctrivia on 06/07/23. //

#ifndef DIGIASSET_CORE_SERIALIZE_H
#define DIGIASSET_CORE_SERIALIZE_H

//all code here

#endif //DIGIASSET_CORE_SERIALIZE_H

I will post entire file at end but pretty sure this part is what should prevent everything from being added more than once. The error codes I am getting are bellow. What am I doing wrong?

error message:

/home/mctrivia/Programs/clion-2023.1.3/bin/cmake/linux/x64/bin/cmake --build /home/mctrivia/Code/CLionProjects/DigiAsset-Core/cmake-build-debug --target Google_Tests_run -j 18
[1/1] Linking CXX executable tests/Google_Tests_run
FAILED: tests/Google_Tests_run 
: && /usr/bin/c++ -std=c++11 -g -Wall -g  tests/CMakeFiles/Google_Tests_run.dir/BitIO.cpp.o tests/CMakeFiles/Google_Tests_run.dir/DatabaseChain.cpp.o tests/CMakeFiles/Google_Tests_run.dir/DigiByteCore.cpp.o tests/CMakeFiles/Google_Tests_run.dir/IPFS.cpp.o tests/CMakeFiles/Google_Tests_run.dir/Base58Tests.cpp.o tests/CMakeFiles/Google_Tests_run.dir/DigiAssetTest.cpp.o tests/CMakeFiles/Google_Tests_run.dir/DigiAssetRulesTest.cpp.o tests/CMakeFiles/Google_Tests_run.dir/DigiAssetTransactionTest.cpp.o tests/CMakeFiles/Google_Tests_run.dir/TestHelpers.cpp.o -o tests/Google_Tests_run  src/libdigiasset_core_lib.a  -ldigibyteapi  -lsqlite3  -lcryptopp  -lcurl  lib/libgtest.a  lib/libgtest_main.a  lib/libgtest.a && :
/usr/bin/ld: src/libdigiasset_core_lib.a(DigiAssetTypes.cpp.o): in function `std::vector<unsigned char, std::allocator<unsigned char> >::_S_nothrow_relocate(std::integral_constant<bool, true>)':
/home/mctrivia/Code/CLionProjects/DigiAsset-Core/src/serialize.h:22: multiple definition of `serialize(std::vector<unsigned char, std::allocator<unsigned char> >&, unsigned char const&)'; src/libdigiasset_core_lib.a(DigiAssetRules.cpp.o):/home/mctrivia/Code/CLionProjects/DigiAsset-Core/src/serialize.h:22: first defined here
/usr/bin/ld: src/libdigiasset_core_lib.a(DigiAssetTypes.cpp.o): in function `std::move_iterator<unsigned char*>::move_iterator(unsigned char*)':
/home/mctrivia/Code/CLionProjects/DigiAsset-Core/src/serialize.h:26: multiple definition of `deserialize(std::vector<unsigned char, std::allocator<unsigned char> > const&, unsigned long&, unsigned char&)'; src/libdigiasset_core_lib.a(DigiAssetRules.cpp.o):/home/mctrivia/Code/CLionProjects/DigiAsset-Core/src/serialize.h:26: first defined here
/usr/bin/ld: src/libdigiasset_core_lib.a(DigiAssetTypes.cpp.o): in function `serialize(std::vector<unsigned char, std::allocator<unsigned char> >&, unsigned long const&)':
/home/mctrivia/Code/CLionProjects/DigiAsset-Core/src/serialize.h:32: multiple definition of `serialize(std::vector<unsigned char, std::allocator<unsigned char> >&, unsigned long const&)'; src/libdigiasset_core_lib.a(DigiAssetRules.cpp.o):/home/mctrivia/Code/CLionProjects/DigiAsset-Core/src/serialize.h:32: first defined here
/usr/bin/ld: src/libdigiasset_core_lib.a(DigiAssetTypes.cpp.o): in function `deserialize(std::vector<unsigned char, std::allocator<unsigned char> > const&, unsigned long&, unsigned long&)':
/home/mctrivia/Code/CLionProjects/DigiAsset-Core/src/serialize.h:39: multiple definition of `deserialize(std::vector<unsigned char, std::allocator<unsigned char> > const&, unsigned long&, unsigned long&)'; src/libdigiasset_core_lib.a(DigiAssetRules.cpp.o):/home/mctrivia/Code/CLionProjects/DigiAsset-Core/src/serialize.h:39: first defined here
/usr/bin/ld: src/libdigiasset_core_lib.a(DigiAssetTypes.cpp.o): in function `serialize(std::vector<unsigned char, std::allocator<unsigned char> >&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)':
/home/mctrivia/Code/CLionProjects/DigiAsset-Core/src/serialize.h:50: multiple definition of `serialize(std::vector<unsigned char, std::allocator<unsigned char> >&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)'; src/libdigiasset_core_lib.a(DigiAssetRules.cpp.o):/home/mctrivia/Code/CLionProjects/DigiAsset-Core/src/serialize.h:50: first defined here
/usr/bin/ld: src/libdigiasset_core_lib.a(DigiAssetTypes.cpp.o): in function `deserialize(std::vector<unsigned char, std::allocator<unsigned char> > const&, unsigned long&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&)':
/home/mctrivia/Code/CLionProjects/DigiAsset-Core/src/serialize.h:60: multiple definition of `deserialize(std::vector<unsigned char, std::allocator<unsigned char> > const&, unsigned long&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&)'; src/libdigiasset_core_lib.a(DigiAssetRules.cpp.o):/home/mctrivia/Code/CLionProjects/DigiAsset-Core/src/serialize.h:60: first defined here
collect2: error: ld returned 1 exit status
ninja: build stopped: subcommand failed.

full serialize.h:

//
// Created by mctrivia on 06/07/23.
//

#ifndef DIGIASSET_CORE_SERIALIZE_H
#define DIGIASSET_CORE_SERIALIZE_H

#include <vector>
#include <cstdint>
#include <cstddef>
#include <string>
#include <stdexcept>

using namespace std;




/**
 * Serialize function.  Takes input serializes it and adds it to the serializedData
 */
void serialize(vector<uint8_t>& serializedData, const uint8_t& input) {
    serializedData.push_back(input);
}

void deserialize(const vector<uint8_t>& serializedData, size_t& i, uint8_t& output) {
    if (i >= serializedData.size()) throw out_of_range("read past end of data");
    output = serializedData[i];
    i++;
}

void serialize(vector<uint8_t>& serializedData, const uint64_t& input) {
    for (size_t shift = 56; shift > 0; shift -= 8) {
    serializedData.push_back((input >> shift) & 0xff);
    }
    serializedData.push_back(input & 0xff);
}

void deserialize(const vector<uint8_t>& serializedData, size_t& i, uint64_t& output) {
    if (i + 8 > serializedData.size()) throw out_of_range("read past end of data");
    output = 0;
    for (size_t shift = 56; shift > 0; shift -= 8) {
    output += ((uint64_t) serializedData[i] << shift);
    i++;
    }
    output += serializedData[i];
    i++;
}

void serialize(vector<uint8_t>& serializedData, const string& input) {
    //store number of elements
    serialize(serializedData, (uint64_t) input.size());

    //store elements
    for (const char& letter: input) {
    serialize(serializedData, (uint8_t) letter);
    }
}

void deserialize(const vector<uint8_t>& serializedData, size_t& i, string& output) {
    //get length
    uint64_t size;
    deserialize(serializedData, i, size);

    //error check
    if (i + size > serializedData.size()) throw out_of_range("read past end of data");

    //decode element
    output.clear();
    output.resize(size);
    for (size_t ii = 0; ii < size; ii++) {
    output[ii] = serializedData[i];
    i++;
    }
}

/**
 * Generic function to serialize vector of any type
 * Still need a function to serialize the type inside the vector for this to work
 */
template<typename T>
void serialize(vector<uint8_t>& serializedData, const vector<T>& input) {
    //store number of elements
    serialize(serializedData, (uint64_t) input.size());

    //store elements
    for (const T& element: input) {
    serialize(serializedData, element);
    }
}


template<typename T>
void deserialize(const vector<uint8_t>& serializedData, size_t& i, vector<T>& output) {
    //get length
    uint64_t size;
    deserialize(serializedData, i, size);

    //decode element
    output.clear();
    output.resize(size);
    for (T& value: output) {
    deserialize(serializedData, i, value);
    }
}


#endif //DIGIASSET_CORE_SERIALIZE_H

How to prevent creating new instance with the default initialization or the new keyword? [duplicate]

My goal is to prevent initializing FibonacciMemoization class except with the FibonacciMemoization::getInstance() function.

Goal:

  • [ ] prevent initializing with FibonacciMemoization* object1 = new FibonacciMemoization();
  • [ ] prevent initializing with FibonacciMemoization object1;

The code

// https://en.cppreference.com/w/cpp/memory/weak_ptr
// https://refactoring.guru/design-patterns/singleton/cpp/example#example-1

#ifndef FIBONACCI_MEMOIZATION_HPP
#define FIBONACCI_MEMOIZATION_HPP

#include <unordered_map>
#include <mutex>

class FibonacciMemoization {
public:
    static std::shared_ptr<FibonacciMemoization> getInstance();

    /**
     * Singleton should not be cloneable.
     * 
     * auto object1 = FibonacciMemoization(); // no matchng constructor for initialization of 'FibonacciMemoization'
     * This line creates an instance of the `FibonacciMemoization` class using its constructor and then assigns this newly created instance to the `object1`.
     * This involves both construction and assignment.
     * 
     * FibonacciMemoization object1;
     * FibonacciMemoization object2 = object1; // function "FibonacciMemoization::FibonacciMemoization(FibonacciMemoization &other)" cannot be referenced -- it is a deleted function
     * This line does not create a new instance of the `FibonacciMemoization` class. 
     * Instead, it creates a new variable `object2` and attempts to initialize it by copying the value of `object1`.
     * Without deleting the copy constructor `object2` would be a separate instance that could behave independently of `object1`.
     * 
     * auto object1 = FibonacciMemoization::getInstance();
     * FibonacciMemoization object2 = *object1; // function "FibonacciMemoization::FibonacciMemoization(FibonacciMemoization &other)" cannot be referenced -- it is a deleted function
     * `object2` would be a separate instance that could behave independently of `object1`.
     */
    FibonacciMemoization(FibonacciMemoization &other) = delete;

    /** 
     * Singleton should not be assignable.
     * auto object1 = FibonacciMemoization();
     * auto object2 = FibonacciMemoization();
     * object2 = object1; // function "FibonacciMemoization::operator=(const FibonacciMemoization &)" cannot be referenced - it is a deleted function
     */
    void operator=(const FibonacciMemoization &) = delete;

    ~FibonacciMemoization();

    unsigned long calculate(unsigned n);
private:
    static std::weak_ptr<FibonacciMemoization> instance;
    static std::mutex mutex;

    FibonacciMemoization();

    int id;
    std::unordered_map<unsigned, unsigned> cache;

    unsigned long fibonacci(unsigned n);
};

#endif

#include "fibonacciMemoization.hpp"
#include <iostream>

FibonacciMemoization::FibonacciMemoization() {
    srand(time(0));
    id = rand();
    std::cout << typeid(*this).name() << " " << __func__ << " " << id << "\n\n";
}

FibonacciMemoization::~FibonacciMemoization() {
    std::cout << typeid(*this).name() << " " << __func__ << " " << id << "\n\n";
}

std::weak_ptr<FibonacciMemoization> FibonacciMemoization::instance;
std::mutex FibonacciMemoization::mutex;

std::shared_ptr<FibonacciMemoization> FibonacciMemoization::getInstance() {
    std::shared_ptr<FibonacciMemoization> sp;

    std::lock_guard<std::mutex> lock(mutex);
    if (instance.expired()) {
        sp = std::make_shared<FibonacciMemoization>();
        instance = sp;
    }

    return instance.lock();
}

unsigned long FibonacciMemoization::calculate(unsigned n) {
    cache.clear();
    return fibonacci(n);
}

unsigned long FibonacciMemoization::fibonacci(unsigned n) {
    if (n < 2)
        return n;

    if (cache.find(n) != cache.end())
        return cache[n];

    unsigned long fib_n = fibonacci(n - 1) + fibonacci(n - 2);
    cache[n] = fib_n;

    return fib_n;
}

The usage code

#include <chrono>
#include <iostream>

#include "fibonacci.cpp"
#include "fibonacciMemoization.hpp"

void fibonacciExample() {
    const auto start = std::chrono::steady_clock::now();
    const auto fb = fibonacci(42);
    const auto end = std::chrono::steady_clock::now();
    const std::chrono::duration<double> elapsed_seconds = end - start;
 
    std::cout << "fibonacci example\n";
    std::cout << "f(42) = " << fb << '\n' << "elapsed time: ";
    std::cout << elapsed_seconds.count() << "s\n\n"; // Before C++20
// std::cout << elapsed_seconds << "\n\n"; // C++20: operator<< chrono::duration
}

void fibonacciMemoizationExample() {
    const auto start = std::chrono::steady_clock::now();

    // example A pf the unexpected usage.
    // FibonacciMemoization object;
    // const auto fb = object.calculate(42);

// example B of the unexpected usage.
// auto object = new FibonacciMemoization();
// const auto fb = object->calculate(42);
    
// the expected usage
auto object = FibonacciMemoization::getInstance();
const auto fb = object->calculate(42);

    const auto end = std::chrono::steady_clock::now();
    const std::chrono::duration<double> elapsed_seconds = end - start;
 
    std::cout << "fibonacci memoization example\n";
    std::cout << "f(42) = " << fb << '\n' << "elapsed time: ";
    std::cout << elapsed_seconds.count() << "s\n\n";

// example B of the unexpected usage.
// need to explicitly call destructor after use due to use of the `new` keyword.
// delete object;
}

The problem is that std::make_shared<FIbonacciMemoization>() require public constructor and destructor.

What I've tried:

  1. set FibonacciMemoization constructor to private.

The expected result: the compiler and run do not generate error.

The actual result: the compiler generate error.

g++ -std=c++11 main.cpp fibonacciMemoization.cpp -o main && ./main
In file included from main.cpp:1:
In file included from ./menu.cpp:3:
./fibonacciexample.cpp:23:26: error: calling a private constructor of class 'FibonacciMemoization'
    FibonacciMemoization object;
                         ^
./fibonacciMemoization.hpp:48:5: note: declared private here
    FibonacciMemoization();
    ^
1 error generated.
In file included from fibonacciMemoization.cpp:1:
In file included from ./fibonacciMemoization.hpp:7:
In file included from /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/unordered_map:523:
In file included from /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/__hash_table:25:
In file included from /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/memory:860:
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/__memory/shared_ptr.h:294:37: error: calling a private constructor of class 'FibonacciMemoization'
        ::new ((void*)__get_elem()) _Tp(_VSTD::forward<_Args>(__args)...);
                                    ^
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/__memory/shared_ptr.h:953:55: note: in instantiation of function template specialization 'std::__shared_ptr_emplace<FibonacciMemoization, std::allocator<FibonacciMemoization>>::__shared_ptr_emplace<>' requested here
    ::new ((void*)_VSTD::addressof(*__guard.__get())) _ControlBlock(__a, _VSTD::forward<_Args>(__args)...);
                                                      ^
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/__memory/shared_ptr.h:962:19: note: in instantiation of function template specialization 'std::allocate_shared<FibonacciMemoization, std::allocator<FibonacciMemoization>, void>' requested here
    return _VSTD::allocate_shared<_Tp>(allocator<_Tp>(), _VSTD::forward<_Args>(__args)...);
                  ^
fibonacciMemoization.cpp:22:19: note: in instantiation of function template specialization 'std::make_shared<FibonacciMemoization, void>' requested here
        sp = std::make_shared<FibonacciMemoization>();
                  ^
./fibonacciMemoization.hpp:48:5: note: declared private here
    FibonacciMemoization();
    ^
1 error generated.

vendredi 25 août 2023

Why operator < overload isn't recognized

I have a struct that I defined as following:

struct MyStruct {
  string key;
  MyStruct(const string& k) :key(k) {}
  bool operator<(const MyStruct& p1) {return this->key < p1.key; }
};

I also created a v = vector<MyStruct> and now I want to sort this vector based on the key values in each MyStruct by calling std::sort(v.begin(), v.end())

However, the program failed to compile with the following error message:

error: invalid operands to binary expression ('const MyStruct' and 'const MyStruct')

I searched for < overloading and found the solution by defining it as non member function. But I wonder what went wrong in my code? It seems that the < overload wasn't recognized by the sort?

Any help or reference is appreciated. Thank you!

Didn't getting the modern C++ syntax, just wanting to know what they mean and how it works on dry run with this LeetCode problem [closed]

Problem statement :

Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].

The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

You must write an algorithm that runs in O(n) time and without using the division operation.

Example 1:

Input: nums = [1,2,3,4] Output: [24,12,8,6] Example 2:

Input: nums = [-1,1,0,-3,3] Output: [0,0,9,0,0]

Solution :

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        int prod = 1, zeroCnt = count(begin(nums), end(nums), 0);
        if(zeroCnt > 1) return vector<int>(size(nums));               // Case-1
        for(auto c : nums) 
            if(c) prod *= c;                                          // calculate product of all elements except 0
        for(auto& c : nums)
            if(zeroCnt) c = c ? 0 : prod;                             // Case-2
            else c = prod / c;                                        // Case-3
        return nums;
    }
};

*Didn't get what is return vector<int>(size(nums)); and how it works why not return vector<int>v(size(nums));.

*Also, please explain what is auto keyword, what is its use in here i.e. mainly I'm asking about the auto keyword like what is for(auto c : nums) and how it works ?

*what is : in for(auto c : nums)

*What is for(auto& c : nums) and how it works i.e. what is & here ?

*What is if(c) and how it works ?

*Please explain this line i.e. if(zeroCnt) c = c ? 0 : prod; what is ? here ?

std::swap says could not find matching operands on Mac however it works on compiler explorer [closed]

I was writing a swap function for my class. It looks like this

class foo:public base
{
    void swap(foo& lhs, foo& rhs) {
        base& lhs_b = static_cast<base&>(lhs);
        base& rhs_b = static_cast<base&>(rhs);
        std::swap(lhs_b,rhs_b);
        std::swap(lhs.a,rhs.a);
    }
}

The above swap works and I don't see a problem with it. What I was a little curious was that before doing that I mistyped the above and it looked like this

void swap(foo& lhs, foo& rhs) {
        foo& lhs_b = static_cast<foo&>(lhs);
        foo& rhs_b = static_cast<foo&>(rhs);
        std::swap(lhs_b,rhs_b); <---Error here - No matching function call for swap
        std::swap(lhs.a,rhs.a);
    }

My question is why did swap tell me that there is no matching function call for swap for those parameters . Why did swap not work for foo& types but works for base& types ?

Update:

Here is a minimal reproducible example. Seems like the swap does not like the copy constructor. I would be interested in knowing why and how to make my type work with std::swap

#include <iostream>

class base {

};

class foo : public base {
public:
    foo() {
        std::cout << "Regular constructor \n" ;
    }

    //The swap ensures bases are swapped as well
    void swap(foo& lhs, foo& rhs) {
        foo& lhs_b = static_cast<foo&>(lhs);
        foo& rhs_b = static_cast<foo&>(rhs);
        std::swap(lhs_b,rhs_b);
        std::swap(lhs.a,rhs.a);
    }

    foo(const foo& f) : base(f) {
        this->a = f.a;
    }

private:
    int a;
};

int main()
{
    std::cout << "Hello";
}

Seems like it has an issue with the copy constructor of foo This is the error that I am getting

 cmake-build-debug /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++   -g -arch arm64 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk -fcolor-diagnostics -std=gnu++17 -MD -MT CMakeFiles/test.dir/main.cpp.o -MF CMakeFiles/test.dir/main.cpp.o.d -v -o CMakeFiles/test.dir/main.cpp.o -c /Users/user12/CLionProjects/test/main.cpp
Apple clang version 14.0.3 (clang-1403.0.14.5)
Target: arm64-apple-darwin22.4.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
 "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang" -cc1 -triple arm64-apple-macosx13.0.0 -Wundef-prefix=TARGET_OS_ -Wdeprecated-objc-isa-usage -Werror=deprecated-objc-isa-usage -Werror=implicit-function-declaration -emit-obj -mrelax-all --mrelax-relocations -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name main.cpp -mrelocation-model pic -pic-level 2 -mframe-pointer=non-leaf -fno-strict-return -ffp-contract=on -fno-rounding-math -funwind-tables=1 -fobjc-msgsend-selector-stubs -target-sdk-version=13.3 -fvisibility-inlines-hidden-static-local-var -target-cpu apple-m1 -target-feature +v8.5a -target-feature +crc -target-feature +lse -target-feature +rdm -target-feature +crypto -target-feature +dotprod -target-feature +fp-armv8 -target-feature +neon -target-feature +fp16fml -target-feature +ras -target-feature +rcpc -target-feature +zcm -target-feature +zcz -target-feature +fullfp16 -target-feature +sm4 -target-feature +sha3 -target-feature +sha2 -target-feature +aes -target-abi darwinpcs -fallow-half-arguments-and-returns -mllvm -treat-scalable-fixed-error-as-warning -debug-info-kind=standalone -dwarf-version=4 -debugger-tuning=lldb -target-linker-version 850 -v -resource-dir /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/14.0.3 -dependency-file CMakeFiles/test.dir/main.cpp.o.d -skip-unused-modulemap-deps -MT CMakeFiles/test.dir/main.cpp.o -sys-header-deps -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk -stdlib=libc++ -internal-isystem /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/include/c++/v1 -internal-isystem /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/local/include -internal-isystem /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/14.0.3/include -internal-externc-isystem /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/include -internal-externc-isystem /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include -Wno-reorder-init-list -Wno-implicit-int-float-conversion -Wno-c99-designator -Wno-final-dtor-non-final-class -Wno-extra-semi-stmt -Wno-misleading-indentation -Wno-quoted-include-in-framework-header -Wno-implicit-fallthrough -Wno-enum-enum-conversion -Wno-enum-float-conversion -Wno-elaborated-enum-base -Wno-reserved-identifier -Wno-gnu-folding-constant -std=gnu++17 -fdeprecated-macro -fdebug-compilation-dir=/Users/user12/CLionProjects/test/cmake-build-debug -ferror-limit 19 -stack-protector 1 -fstack-check -mdarwin-stkchk-strong-link -fblocks -fencode-extended-block-signature -fregister-global-dtors-with-atexit -fgnuc-version=4.2.1 -fno-cxx-modules -no-opaque-pointers -fcxx-exceptions -fexceptions -fmax-type-align=16 -fcommon -fcolor-diagnostics -clang-vendor-feature=+disableNonDependentMemberExprInCurrentInstantiation -fno-odr-hash-protocols -clang-vendor-feature=+enableAggressiveVLAFolding -clang-vendor-feature=+revert09abecef7bbf -clang-vendor-feature=+thisNoAlignAttr -clang-vendor-feature=+thisNoNullAttr -mllvm -disable-aligned-alloc-awareness=1 -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o CMakeFiles/test.dir/main.cpp.o -x c++ /Users/user12/CLionProjects/test/main.cpp
clang -cc1 version 14.0.3 (clang-1403.0.14.5) default target arm64-apple-darwin22.4.0
ignoring nonexistent directory "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/local/include"
ignoring nonexistent directory "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/Library/Frameworks"
#include "..." search starts here:
#include <...> search starts here:
 /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/include/c++/v1
 /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/14.0.3/include
 /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/include
 /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include
 /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/System/Library/Frameworks (framework directory)
End of search list.
/Users/user12/CLionProjects/test/main.cpp:32:9: error: no matching function for call to 'swap'
        std::swap(lhs_b,rhs_b);
        ^~~~~~~~~
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/include/c++/v1/__utility/swap.h:33:85: note: candidate template ignored: requirement 'is_move_constructible<foo>::value' was not satisfied [with _Tp = foo]
inline _LIBCPP_INLINE_VISIBILITY __swap_result_t<_Tp> _LIBCPP_CONSTEXPR_AFTER_CXX17 swap(_Tp& __x, _Tp& __y)
                                                                                    ^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/include/c++/v1/__utility/pair.h:416:1: note: candidate template ignored: could not match 'pair<_T1, _T2>' against 'foo'
swap(pair<_T1, _T2>& __x, pair<_T1, _T2>& __y)
^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/include/c++/v1/__utility/swap.h:42:1: note: candidate template ignored: could not match '_Tp[_Np]' against 'foo'
swap(_Tp (&__a)[_Np], _Tp (&__b)[_Np]) _NOEXCEPT_(__is_nothrow_swappable<_Tp>::value) {
^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/include/c++/v1/tuple:251:6: note: candidate template ignored: could not match '__tuple_leaf<_Ip, _Hp, _Ep>' against 'foo'
void swap(__tuple_leaf<_Ip, _Hp, _Ep>& __x, __tuple_leaf<_Ip, _Hp, _Ep>& __y)
     ^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/include/c++/v1/tuple:259:6: note: candidate template ignored: could not match '__tuple_leaf<_Ip, _Hp, _Ep>' against 'foo'
void swap(const __tuple_leaf<_Ip, _Hp, _Ep>& __x, const __tuple_leaf<_Ip, _Hp, _Ep>& __y)
     ^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/include/c++/v1/tuple:1334:1: note: candidate template ignored: could not match 'tuple<_Tp...>' against 'foo'
swap(tuple<_Tp...>& __t, tuple<_Tp...>& __u)
^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/include/c++/v1/__memory/compressed_pair.h:159:6: note: candidate template ignored: could not match '__compressed_pair<_T1, _T2>' against 'foo'
void swap(__compressed_pair<_T1, _T2>& __x, __compressed_pair<_T1, _T2>& __y)
     ^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/include/c++/v1/__memory/unique_ptr.h:553:1: note: candidate template ignored: could not match 'unique_ptr<_Tp, _Dp>' against 'foo'
swap(unique_ptr<_Tp, _Dp>& __x, unique_ptr<_Tp, _Dp>& __y) _NOEXCEPT {__x.swap(__y);}
^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/include/c++/v1/__memory/shared_ptr.h:1332:1: note: candidate template ignored: could not match 'shared_ptr<_Tp>' against 'foo'
swap(shared_ptr<_Tp>& __x, shared_ptr<_Tp>& __y) _NOEXCEPT
^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/include/c++/v1/__memory/shared_ptr.h:1627:1: note: candidate template ignored: could not match 'weak_ptr<_Tp>' against 'foo'
swap(weak_ptr<_Tp>& __x, weak_ptr<_Tp>& __y) _NOEXCEPT
^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/include/c++/v1/variant:1733:6: note: candidate template ignored: could not match 'variant<_Types...>' against 'foo'
auto swap(variant<_Types...>& __lhs, variant<_Types...>& __rhs)
     ^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/include/c++/v1/array:442:1: note: candidate template ignored: could not match 'array<_Tp, _Size>' against 'foo'
swap(array<_Tp, _Size>& __x, array<_Tp, _Size>& __y)
^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/include/c++/v1/__hash_table:2667:1: note: candidate template ignored: could not match '__hash_table<_Tp, _Hash, _Equal, _Alloc>' against 'foo'
swap(__hash_table<_Tp, _Hash, _Equal, _Alloc>& __x,
^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/include/c++/v1/optional:1543:1: note: candidate template ignored: could not match 'optional<_Tp>' against 'foo'
swap(optional<_Tp>& __x, optional<_Tp>& __y) noexcept(noexcept(__x.swap(__y)))
^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/include/c++/v1/unordered_map:635:1: note: candidate template ignored: could not match '__unordered_map_hasher<_Key, _Cp, _Hash, _Pred, __b>' against 'foo'
swap(__unordered_map_hasher<_Key, _Cp, _Hash, _Pred, __b>& __x,
^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/include/c++/v1/unordered_map:748:1: note: candidate template ignored: could not match '__unordered_map_equal<_Key, _Cp, _Pred, _Hash, __b>' against 'foo'
swap(__unordered_map_equal<_Key, _Cp, _Pred, _Hash, __b>& __x,
^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/include/c++/v1/unordered_map:1870:1: note: candidate template ignored: could not match 'unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>' against 'foo'
swap(unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>& __x,
^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/include/c++/v1/unordered_map:2576:1: note: candidate template ignored: could not match 'unordered_multimap<_Key, _Tp, _Hash, _Pred, _Alloc>' against 'foo'
swap(unordered_multimap<_Key, _Tp, _Hash, _Pred, _Alloc>& __x,
^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/include/c++/v1/__bit_reference:106:1: note: candidate template ignored: could not match '__bit_reference<_Cp>' against 'foo'
swap(__bit_reference<_Cp> __x, __bit_reference<_Cp> __y) _NOEXCEPT
^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/include/c++/v1/__bit_reference:116:1: note: candidate template ignored: could not match '__bit_reference<_Cp>' against 'foo'
swap(__bit_reference<_Cp> __x, __bit_reference<_Dp> __y) _NOEXCEPT
^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/include/c++/v1/__bit_reference:126:1: note: candidate template ignored: could not match '__bit_reference<_Cp>' against 'foo'
swap(__bit_reference<_Cp> __x, bool& __y) _NOEXCEPT
^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/include/c++/v1/__bit_reference:136:1: note: candidate template ignored: could not match '__bit_reference<_Cp>' against 'foo'
swap(bool& __x, __bit_reference<_Cp> __y) _NOEXCEPT
^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/include/c++/v1/__split_buffer:639:1: note: candidate template ignored: could not match '__split_buffer<_Tp, _Allocator>' against 'foo'
swap(__split_buffer<_Tp, _Allocator>& __x, __split_buffer<_Tp, _Allocator>& __y)
^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/include/c++/v1/vector:3285:1: note: candidate template ignored: could not match 'vector<_Tp, _Allocator>' against 'foo'
swap(vector<_Tp, _Allocator>& __x, vector<_Tp, _Allocator>& __y)
^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/include/c++/v1/__functional/function.h:1250:1: note: candidate template ignored: could not match 'function<_Rp (_ArgTypes...)>' against 'foo'
swap(function<_Rp(_ArgTypes...)>& __x, function<_Rp(_ArgTypes...)>& __y) _NOEXCEPT
^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/include/c++/v1/string:4504:1: note: candidate template ignored: could not match 'basic_string<_CharT, _Traits, _Allocator>' against 'foo'
swap(basic_string<_CharT, _Traits, _Allocator>& __lhs,
^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/include/c++/v1/__mutex_base:262:1: note: candidate template ignored: could not match 'unique_lock<_Mutex>' against 'foo'
swap(unique_lock<_Mutex>& __x, unique_lock<_Mutex>& __y) _NOEXCEPT
^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/include/c++/v1/list:2335:1: note: candidate template ignored: could not match 'list<_Tp, _Alloc>' against 'foo'
swap(list<_Tp, _Alloc>& __x, list<_Tp, _Alloc>& __y)
^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/include/c++/v1/__tree:2734:1: note: candidate template ignored: could not match '__tree<_Tp, _Compare, _Allocator>' against 'foo'
swap(__tree<_Tp, _Compare, _Allocator>& __x,
^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/include/c++/v1/map:668:1: note: candidate template ignored: could not match '__map_value_compare<_Key, _CP, _Compare, __b>' against 'foo'
swap(__map_value_compare<_Key, _CP, _Compare, __b>& __x,
^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/include/c++/v1/map:1727:1: note: candidate template ignored: could not match 'map<_Key, _Tp, _Compare, _Allocator>' against 'foo'
swap(map<_Key, _Tp, _Compare, _Allocator>& __x,
^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/usr/include/c++/v1/map:2318:1: note: candidate template ignored: could not match 'multimap<_Key, _Tp, _Compare, _Allocator>' against 'foo'
swap(multimap<_Key, _Tp, _Compare, _Allocator>& __x,

However when I run it on compiler explorer I don't get that error

This is my build info enter image description here

setRangeDrag/setRangeZoom how to make limit

Is there a way to limit setRangeDrag/setRangeZoom limit? For example, let's say I have valid data for X [0,100] and Y [0,1000]. If I enable drag on X axis, the plot can go below 0 and above 100 in the X axis and similarly in the Y axis. I can keep dragging on and on without limitation. Same thing for zoom, I'd like the initial view to be the minimum zoom, and the user can only zoom in and then zoom out to the initial view.

I try to use QWheelEvent.

jeudi 24 août 2023

Condition_variable wait_for timeout issue

I am trying to learn how to get conditional variables working with some threads, but am having some troubles. The goal is to get the main thread to spawn some 'tasks' for a set period of time which instantiates a Countdown object that includes a thread which uses the timeout of the condition_variable to know that the requested time has indeed lapsed before notifying the caller.

Each time I run the example below it gets a different result, sometimes erroring out, sometimes running, but the timeout for both child threads is shorter than requested (assuming it gets that far).

I appreciate that there are other ways to skin-the-cat to time threads and I could for instance use atomic_x or other means instead of a callback, but I just would like to see how to get the spirit of this implementation (i.e. conditional variable so I don't have to poll).

#include <chrono>
#include <condition_variable>
#include <functional>
#include <iostream>
#include <map>
#include <mutex>
#include <thread>

using Time = std::chrono::system_clock;
using Seconds = std::chrono::seconds;
using Timepoint = Time::time_point;

class Countdown {
private:
    Timepoint               target;
    std::thread             t;
    std::condition_variable cv;
    std::mutex              cv_m;
    unsigned int            guid;
    std::string             name;

public:
    Countdown() 
    { // Needed to compile, but doesn't appear to run 
        std::cout << "empty Countdown constructor" << std::endl;
    }

    Countdown(unsigned int guid_, std::string name_, unsigned int waitFor, std::function<void(unsigned int)> callback)
        : guid(guid_)
        , name(name_)
        , target(Time::now() + Seconds(waitFor))
    {

        auto exec_run = [this, guid_, waitFor, callback]() mutable {
            std::unique_lock<std::mutex> lk(cv_m);
            std::cout << "[Thread " << guid_ << "] waiting for " << waitFor << " seconds." << std::endl;
 
            Timepoint before = Time::now();
            if (cv.wait_until(lk, target) == std::cv_status::timeout)
            {
                Timepoint after = Time::now();
                std::chrono::duration<float> difference = after - before;
                std::cout << "[Thread " << guid_ << "] Elapsed " << difference.count() << " seconds." << std::endl;
                callback(guid_);
            } 
        };
        
        t = std::thread(exec_run);
    }

    Countdown(Countdown &&from) // move constructor
    {
        //std::cout << "Countdown move constructor" << std::endl; 
        target = from.target;
        t = std::move(from.t);
        name = from.name;
        guid = from.guid;
    }

    ~Countdown()
    {
        //std::cout << "~Countdown()" << std::endl; 
        if (t.joinable()) t.join();
    }
};

class Holder {
private:
    std::map<unsigned int, Countdown>   waitlist;
    unsigned int                        id;
    std::vector<unsigned int>           completed;

public:
    Holder()
        : id(0)
    { }

    // Create a new task with a name for WaitFor (s) period of time
    unsigned int addTask(std::string name, unsigned int waitFor) {
        id++;
        waitlist.emplace(std::pair(id, Countdown(id, name, waitFor, 
                                  std::bind(&Holder::taskComplete, this, std::placeholders::_1))));

        return id;
    }

    void taskComplete(unsigned int id)
    {
        std::cout << "[Thread " << id << "] taskComplete" << std::endl;
        // Add task id to the completed list to be picked up by main thread
        completed.push_back(id);
    }

    void cleanupCompleted()
    {
        // Purge the completed entries from the waitlist
        for (auto& id : completed)
        {
            std::cout << "[Main] Erasing task: " << id << std::endl;
            waitlist.erase(id);
        }

        // Empty the completed list
        completed.clear();
    }
};

int main()
{
    Holder *h = new Holder();
    // Create a task which spawns a thread, which notifies us when complete
    unsigned int id1 = h->addTask("fluffy", 1); // 1 second task
    unsigned int id2 = h->addTask("woof", 4);   // 4 second task
    std::cout << "[Main]: Done adding tasks.." << std::endl;
 
    // Rest a while..
    std::this_thread::sleep_for(Seconds(5));
    h->cleanupCompleted();

    // Just to show the main thread continues on.
    std::cout << "[Main]: Doing other stuff.." << std::endl;
    delete(h);

    return 0;
}

Actual / Expected Result:

[Main]: Done adding tasks..
[Thread 2] waiting for 4 seconds.
[Thread 1] waiting for 1 seconds.
[Thread 2] Elapsed 8.243e-06 seconds. **(This should be ~ 4 seconds)**
[Thread 2] taskComplete
[Thread 1] Elapsed 0.000124505 seconds. **(This should be ~1 second)**
[Thread 1] taskComplete
[Main] Erasing task: 2
[Main] Erasing task: 1
[Main]: Doing other stuff..

I 'think' the problem might be around the in-place addition of the 'Countdown' object to the map in the 'Holder' class. It needs a move constructor whereby I manually set each field (except the mutex and conditional_variable).

Any advice on how to do this correctly?

Confusion about the necessity of "using" keyword with inheritance and constructors in C++11

I'm new to learning C++, and while exploring C++11 concepts, I came across the relationship between the "using" keyword and inheritance. My code consists of Base and derived Derived classes.The Base class has a member function named foo().In the Derived class, I utilize the "using" keyword to make the Base class's foo() function accessible.

class Base {
public:
void foo() { std::cout << "Base::foo()" << std::endl; }
};

class Derived : public Base {
public:
using Base::foo;  
};

int main() {
Derived obj;
obj.foo();  
return 0;
}

However, even without the "using" keyword(by commenting the using Base::foo; line), the program compiles and runs without errors.

I'm confused about whether the "using" keyword is mandatory here. Can you explain in which scenarios using the "using" keyword is crucial and what issues I might face if I omit it?

Thank you in advance for your answers!

I attempted to run the code by removing the "using" keyword, and the code executed smoothly.However, when I asked this to ChatGPT, it stated that the code would be incorrect without the "using" keyword and advised me to use it.

Is it legal to call the pointer which points to a lambda that is out of scope?

Is it legal to call the pointer which points to a lambda that does not exist anymore?

Here is the demo code snippet.

#include <iostream>

typedef int (*Func)(int a);

int main()
{
 Func fun;

 {
    auto lambda = [](int a)->int{std::cout << a << std::endl; return a;};   
    fun =lambda;
 }

 fun(6); //Is it legal? The variable lambda does not exist anymore.
}

What about generic condition, say lambdas which have captures?

mercredi 23 août 2023

Adding a weak_ptr scenario

I am trying to come up with a simple example of when a shared_ptr would be used and when a unique or a weak pointer will be used. Trying to better understand smart pointers. In my case. I came up with a Recipe scenario. A recipe will have ingredients(eggs,meat) which it will own(unique_ptr) and then a recipe is passed to a burner. The same recipe can be cooked on multiple burners (hence) a shared_ptr. This shows the basic

class Recipe {
public:
    std::vector<std::unique_ptr> ingrediants;
    void addIngrediant(std::unique_ptr<Ingrediants> i){
        ingrediants.push_back(std::move(i));
    }
};

class Burner {
public:
   std::vector<std::shared_ptr<Recipe>> recipes;
   void addRecipe(const std::shared_ptr<Recipe>& r) {
    recipes.emplace_back(r);
   }
}

In the above case I have managed to use a shared_ptr and a unique_ptr. Can someone help me come up with a situation and add a scenario on when I would use a weak_ptr ?

Can I use a friend function definied within a class as my thread function

I'm new to C++ and trying to understand concepts in threads. My reading material surrounding this question is "Anthony Williams - C++ Concurrency in Action" - Listing 3.6. I have written the listing by myself but can't seems to get the code to work. I believe the problem I'm facing is calling an in-class friend function as the thread function, I have referred to this article as well.

Here is my code

#include <iostream>
#include <mutex>
#include <thread>

class some_big_object
{
};
void swap(some_big_object &lhs, some_big_object &rhs);

class X
{
private:
    some_big_object some_detail;
    std::mutex m;

public:
    X(some_big_object const &sd) : some_detail(sd) {}
    friend void swap(X &lhs, X &rhs)
    {
        if (&lhs == &rhs)
        {
            return;
        }
        std::lock(lhs.m, rhs.m);
        std::lock_guard<std::mutex> lock_a(lhs.m, std::adopt_lock);
        std::lock_guard<std::mutex> lock_b(rhs.m, std::adopt_lock);
        swap(lhs.some_detail, rhs.some_detail);
    }
};

int main(void)
{
    some_big_object s1;
    some_big_object s2;
    X a(s1);
    X b(s2);
    std::thread t1(swap(a, b));
    t1.join();

    return 0;
}

Compilation error enter image description here

Thank you

I have tried referring to the article, and couple of other materials in Tutorials Point and GeekforGeeks

how to build multiple graphs on widget QCustomPlot

i want to build 5 graphs on my grid layout located on the scroll area.

Name of grid layout is "grap" But every time, when i run my code, i only see 1 graph on my widget. Down below i attached class of my graph. And i know that i will receive 5 equals graphs.

GraphBuilder.h

#ifndef GRAPHBUILDER_H
#define GRAPHBUILDER_H

#include "qcustomplot.h"

#include <QWidget>
#include <QObject>

class GraphBuilder : public QWidget
{
    Q_OBJECT
public:
    explicit GraphBuilder(QWidget* parent = nullptr);
    ~GraphBuilder();

    void build();

private:
    QCustomPlot* _customPlot = nullptr;
};

#endif // GRAPHBUILDER_H

GraphBuilder.cpp

#include "graphbuilder.h"

GraphBuilder::GraphBuilder(QWidget* parent)
    : QWidget(parent)
{
    _customPlot = new QCustomPlot(this);
}

GraphBuilder::~GraphBuilder()
{
    delete _customPlot;
}


void GraphBuilder::build()
{
    QVector<double> xData = {1, 2, 3, 4, 5};
    QVector<double> yData = {1, 4, 9, 16, 25};

    _customPlot->addGraph();
    _customPlot->graph()->setData(xData, yData);

    _customPlot->xAxis->setLabel("X");
    _customPlot->yAxis->setLabel("Y");

    _customPlot->xAxis->setRange(0, 6);
    _customPlot->yAxis->setRange(0, 30);

    _customPlot->replot();
}

MainWindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include "graphbuilder.h"

#include <QMainWindow>



QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();


private:

    void printGraph();

    Ui::MainWindow *ui;
    GraphBuilder* graph = nullptr;

};
#endif // MAINWINDOW_H

MainWindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);


    graph = new GraphBuilder();
    printGraph();
}

MainWindow::~MainWindow()
{
    delete ui;
    delete graph;
}


void MainWindow::printGraph()
{
    for (int i = 0; i < 5; i++)
    {
        ui->grap->addWidget(graph);
        graph->build();
    }
}

Photo->

graph show

mardi 22 août 2023

Why rvalue references behave differently based on types?

I'm reading about C++ rvalue references and value categories for expressions. However, I'm not able to grasp (from a lvalue, xvalue, prvalue point of view) why the following code works as expected:

struct S {
    int a;
};

S&& t(S& a) {
    return (S&&)a;
}

int main()
{   
    S s = { 1 };
    t(s) = S{ 2 };
    cout << s.a; // prints 2
    return 0;
}

Whereas the following one doesn't even compile, and shows error: using rvalue as lvalue:

int&& t(int& a) {
    return (int&&)(a);
}

int main()
{   
    int s = 1;
    t(s) = 2; // error
    std::cout << s;
    return 0;
}

To me, in both cases t(s) should behave as an xvalue. Hence, it can appear to the left of the assignment operator (not discussing operator overriding in this context). The standard literally says that The result of calling a function whose return type is an rvalue reference is an xvalue. Why is it behaving differently for int and for struct S? Is this behavior, in any way, predicted by the standard (or by cppreference.com)? I couldn't realize what order of ideas gets into this scenario.

I was expecting the second code to print 2, based on the reasoning that the memory location of s, initially holding 1 would be overwritten by 2 by means of the rvalue reference.

QtChart, how to make mouse wheel zoom

Anyone know, how to make zoom with mouse, like:

plot->setInteraction(QCP::iRangeZoom,true);
plot->setInteraction(QCP::iRangeDrag, true);

Also i want to use QtCharts, but i dont know how to make mouse zoom using the mouse wheel.

Why doesn't std::forward preserve the lvalue-ness of this variable?

In the code below (which is run in C++20), when I call the UseForward function, I expect the first overload to be called (which is template <typename T> void UseForward(T& value)) and it does get called. Then in the body of the function I use std::forward which I expect to preserve the lvalue-ness of variable value and call the copy constructor, BUT it calls the move constructor. What am I missing here?

class SomeClass
{
public:
    SomeClass()
    {
        std::cout << "default constructor" << std::endl;
    }

    SomeClass(const SomeClass& other)
    {
        std::cout << "const copy constructor" << std::endl;
    }

    SomeClass(SomeClass&& other) noexcept
    {
        std::cout << "move constructor" << std::endl;
    }
};

template <typename T>
void UseForward(T& value)
{
    std::cout << "UseForward pass by reference!" << std::endl;
    auto sc = SomeClass(std::forward<T>(value));
}

template <typename T>
void UseForward(T&& value)
{
    std::cout << "UseForward pass by rvalue reference!" << std::endl;
    auto sc2 = SomeClass(std::forward<T>(value)); 
}

int main()
{
    auto sc = SomeClass();
    UseForward(sc);
}

Linker error undefined symbols for arm64 symengine

I'm trying to work with symengine on my Mac, however there is a persistent linking error I'm unable to solve. I installed symengine the "default" way with condo install symengine. I'm trying to compile the following minimal example random.cpp

#include <iostream>
#include <symengine/expression.h>

using SymEngine::Expression;


int main() {
    Expression e("e");
    std::cout << "Defined Expression: " << e << "\n";
    return 0;
};

with clang++ -std=c++11 -I/path/to/symengine/include random.cpp. However, I get the following error telling me that ld is unable to find symbols for my arm64 architecture:

Undefined symbols for architecture arm64:
  "SymEngine::Expression::Expression(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)", referenced from:
      _main in random-79496f.o
  "SymEngine::Basic::__str__() const", referenced from:
      SymEngine::operator<<(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, SymEngine::Expression const&) in random-79496f.o
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

After a google search I tried to compile with -stdlib=libc++, but the error persists. -v gives the following additional output:

"/Library/Developer/CommandLineTools/usr/bin/ld" -demangle -lto_library /Library/Developer/CommandLineTools/usr/lib/libLTO.dylib -no_deduplicate -dynamic -arch arm64 -platform_version macos 13.0.0 13.1 -syslibroot /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -o a.out -L/usr/local/lib /var/folders/58/n0sq8txx0bn1cz6w6kxzyh500000gn/T/random-79496f.o -lc++ -lSystem /Library/Developer/CommandLineTools/usr/lib/clang/14.0.0/lib/darwin/libclang_rt.osx.a

For me it seems that the linker cannot find the right library, but I'm not quite sure what the error message tells me. Any help is very much appreciated!

lundi 21 août 2023

Emulating lambdas in C++03 for flow-control purposes in macros

I have some existing code in a header file which needs to be useable in the context of C++03 & C++11

It defines a macro TABORT that takes in a printf-style format string & arguments to be formatted using that string, prints the result to stdout, and then calls std::abort

Essentially, something similar to

#define TABORT(...) do { fprintf(stderr, "Aborting at %s:%d for reason: ", __FILE__, __LINE__); fprintf(stderr, __VA_ARGS__); std::abort(); } while(0)

I wanted to add some logic to catch the case where evaluating __VA_ARGS__ would throw an exception, preventing the call to std::abort. For example, in the following:

if (SomethingReallyBadHappened())
    TABORT("Aborting because %s", GetReallyBadDetails().c_str());

if GetReallyBadDetails throws an exception, I want to ensure that abort gets called (here, not after some exception unwinding).

So, I did something like:

#define TABORT(...) do { fprintf(stderr, "Aborting at %s:%d for reason: ", __FILE__, __LINE__); try { fprintf(stderr, __VA_ARGS__); } catch (...) { fprintf(stderr, "<Failed to evaluate abort message>\n"); } std::abort(); } while(0)

But this is causing the C4714 warning in visual studio when the macro is used in functions marked __forceinline, probably due to

In some cases, the compiler will not inline a particular function for mechanical reasons. For example, the compiler will not inline:

  • A function with a try (C++ exception handling) statement.

So, to avoid that warning (& to keep inlining functions which were previously determined to need inlining inlined [I hope this was done alongside profiling...]), I was thinking to do something like

// In header

// Assume this is like std::function except construction from a lambda can't throw
template <typename Sig>
class function_ref;
using PrintAbortMsg = function_ref<void(const char*)>;
void [[noreturn]] do_tabort(const char* file, int line, function_ref<void(PrintAbortMsg &)> msgGenerator) noexcept;
#define TABORT(...) do_tabort(__FILE__, __LINE__, [&](PrintAbortMsg& print) { print(SprintfToStdString(__VA_ARGS__).c_str()); })

// In cpp

void do_tabort(const char* file, int line, function_ref<void(PrintAbortMsg&)> msgGenerator) noexcept
{
    fprintf(stderr, "Aborting at %s:%d for reason: ", __FILE__, __LINE__);
    try
    {
        msgGenerator([](const char* msg) { fprintf(stderr, "%s\n", msg); });
    }
    catch (...)
    {
        fprintf(stderr, "<Failed to evaluate abort message>\n");
    }
    std::abort();
}

Which I think would work in the context of C++11, but I'm not sure how to do something which will work for for C++03. There are existing usages of the macro which I don't want to touch.

QTCharts building charts with time

I have QVector<QTime> time, with "hh:mm:ss.zzz" format, how can i build a normal QtCharts with this format on X. On Y i will use QVector<double>.

I try to use append in QLineSeries, but nothing work

I try to build to graphs with equals data

    QVector<double> test(30);
    for (int i = 0; i < test.size(); ++i)
    {
        test.push_back(0.03);
    }
    
    
    QChartView* chartView = nullptr;
    QLineSeries* series = nullptr;
    QChart* chart = nullptr;
    QDateTimeAxis* axisX = nullptr;
    QDateTimeAxis* axisY = nullptr;
    
    for (size_t i = 0; i < 2; ++i)
    {
        chartView = new QChartView(this);

        ui->graphPrint->addWidget(chartView);

        series = new QLineSeries;
        
        for (int j = 0; j < time.size(); ++j)
        {
            QString formattedTime = time[i].toString("hh:mm:ss.zzz");
            series->append(formattedTime, test[i]);
        }
        
        chart = new QChart();
        
        
        axisX = new QDateTimeAxis();
        axisX->setFormat("hh:mm:ss.zzz");
        chart->addAxis(axisX, Qt::AlignBottom);
        
    }
    
    delete chartView;
    delete series;
    delete axisX;
    delete axisY;

dimanche 20 août 2023

thread stopped after detach

I use the codes below to test detach (in ubuntu18.5, g++7.5):

#include <thread>
#include <fstream>
#include <chrono>
#include <iostream>

using namespace std;


void long_process()
{
    ofstream ofs("test.log", ios::app);
    ofs<<"long process start" <<endl;
    std::this_thread::sleep_for(std::chrono::milliseconds(3*1000)); //wait 3 seconds
    ofs<<"long process end" <<endl;

}

int main()
{
    ofstream ofs("test.log", ios::app);
    ofs << "main start" <<endl;
    std::thread th(long_process);
    th.detach();
    ofs << "main end" <<endl;                                                                                                                                                               }

But in the test.log, I only see 3 lines, it seems long_process stopped after detach.

main start
main end
long process start

I think the result of detach should be:

main start
main end
long process start
long process end

If I change detach to join, it works.

main start
long process start
long process end
main end

I don't know why.

Specializing function templates in C++

I am familiar with class specialization but came across this piece of code which I believe is function specialization

A:
template <bool include_negatives>
int average(int* array, int len) {
....
}

I could rewrite the above as this C . I know that I am specializing a class so I need to provide B. My question is what is happening in A. Why does that not need a generic type since its being specialized.

B:
template<typename t>
int average(){

}

C:
template<>
int average<bool>(){
  ...
}

My question is why does the

Why doesn't qDebug output anything after clicking the button

I'm trying to implement one thing with signals and slots, and the problem arises that after pressing the button nothing happens, although the path to the file should be displayed. The button is made using the QT graphic designer.

#ifndef CONTROLLER_H
#define CONTROLLER_H

#include "mainwindow.h"
#include "model.h"
#include <QMainWindow>
#include <QObject>
#include <QDebug>

class Controller : public QObject
{
    Q_OBJECT

public:

explicit Controller(QObject *parent = nullptr);
~Controller();

public slots:
    void onFileSelected(const QString& filePath);

private:
    // Model* model = nullptr;
    MainWindow* view = nullptr;
};

#endif // CONTROLLER_H

controller.cpp

#include "controller.h"

Controller::Controller(QObject *parent)
    : QObject(parent)
{
    // model = new Model(this);
    view = new MainWindow();

    connect(view, &MainWindow::fileSelected, this, &Controller::onFileSelected);
}

Controller::~Controller()
{
    // delete model;
    delete view;
}

void Controller::onFileSelected(const QString& filePath)
{
     qDebug() << "File selected: " << filePath;
     // qDebug() << model->getHeaders();
}

mainwindow.h

ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
   Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
   ~MainWindow();

signals:
    void fileSelected(const QString& filePath);

private slots:
    void on_pushButton_clicked();

private:
    Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QFile>
#include <QFileDialog>
#include <QTextStream>
#include <QDebug>
#include <QMessageBox>
#include <QtCharts>

using namespace QtCharts;


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_pushButton_clicked()
{
    QString filePath = QFileDialog::getOpenFileName(this, "choose file", QDir::currentPath());

    emit fileSelected(filePath);
}

main.cpp

#include <QApplication>
#include <QWidget>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QWidget window;

    window.show();

    return app.exec();
 }

If you try to send the signal to the same file it was sent from, everything works fine!

samedi 19 août 2023

Pointer after initialization in an exception subclass

I was casually doing some challenges on HackerRank and I stumbled on "Inherited Code", which I've tried to solve with this:

class BadLengthException : public exception    {
    private:
        const char* message;
    public:
        BadLengthException(int n_)  {
            this->message = to_string(n_).c_str();
        }
        
        const char * what() const throw() {
            return this->message;
        }
};

Since it did not work (the output was empty), I've searched on SO the reason why and I found this question on the same problem. I think I do understand the solution proposed, but I'm still very confused about my try:

I get that the string to_string(n_).c_str() could be seen as a local variable, like the example in the mentioned question, but why it's still treated as such when what() is called? Shouldn't it have been kept in message via initialization, thus being available whenever calling what()?

(Pallindrome checker) [LEETCODE problem] I know I'm commiting some minor mistake but i don't know what it is

class Solution {
public:
    bool isPalindrome(string s) {
        getline(cin,s);
                bool answer;
                vector<int>l;
                vector<int>r;
                for(auto i=0;i<s.size();i++){
                    char c = s[i];
                    l.push_back(c);
                }
                for(auto i=s.size()-1;i<s.size();i--){
                    char a = s[i];
                    r.push_back(a);
                }
                for(auto i=0;i++;){
                    if(l[i]==r[i]) answer = true;
                    if(l[i]!=r[i]) answer = false;
                }
                return answer;
    }
};

I was expecting it to work fine but i think i am commiting some logical error while writing bool datatype.

the output in vscode is just blank output.

This program has cleared 2 testcases out of 3 in leetcode compiler.

vendredi 18 août 2023

How to use universal reference in C++11

We would like to combine the following 2 map_at() functions into one, using universal reference T&&. Could somebody help?

template<typename T> // version const
const typename T::mapped_type& map_at(const T& m, const typename T::key_type& key)
{
    if (const auto& iter = m.find(key); iter != m.cend()) {
        return iter->second;
    }
    else {
        throw std::exception("blah");
    }
}

template<typename T> // version non-const
typename T::mapped_type& map_at(T& m, const typename T::key_type& key)
{
    if (const auto& iter = m.find(key); iter != m.cend()) {
        return iter->second;
    }
    else {
        throw std::exception("blah");
    }
}

int main()
{
    using T = std::map<int, float>;
    T t;
    const T ct;

    try {
        map_at(ct, 3); // calls version const
    }
    catch (...){}

    try {
        map_at(t, 3); // calls version non-const
    }
    catch (...){}
}

We tried the following with T&&, but get error

1> ConsoleApplication1.cpp(557,9): error C2672: 'map_at': no matching overloaded function found

template<typename T> // version T&&
typename T::mapped_type&& map_at(T&& m, const typename T::key_type& key)
{
    if (const auto& iter = m.find(key); iter != m.cend()) {
        return iter->second;
    }
    else {
        throw std::exception("blah");
    }
}

what happens if thread object is destroyed, but the thread isn't finish?

Suppose I have the following code:

//do job1;

{
   std::thread th(long_process_func);
   th.detach();
}

//do job2;

In the codes above, th is destroyed immediately after calling detach, but the thread isn't finished yet because the long process function. Is the code above safe?

It runs without any problem in my test, but not sure how it works

Klockwork Error: RH.LEAK (2:Error) Analyze Resource acquired to 'socFd' at line 385 may be lost here

When we are trying to generate the Klockwork report it is showing

FrameTxRxMngr::sendStrmReqInfoToTarget(
    void
) {

    uint32_t           retVal    = IPNEXT_SUCCESS;
    uint32_t           timeout   = TIMEOUT_IN_MS;
    stFrameHeader      frameHdr{};
    struct sockaddr_in destAddr{};

    SOCKET socFd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

    if (socFd == INVALID_SOCKET)
    {
        printf("sendStrmReqInfoToTarget() Socket creation failed");
        retVal = IPNEXT_ERR_SCKT_CRT_FAIL;
    }
    else
    {
        struct sockaddr_in localAddr;

        localAddr.sin_family = AF_INET;

        // ! Copy the IP address to localAddr.sin_addr
        memcpy(&(localAddr.sin_addr.s_addr),
                &m_pIpCfginfo->x86SrcIPAddr,
                sizeof(m_pIpCfginfo->x86SrcIPAddr));

        localAddr.sin_port = htons(PORT_NUM);

        //! attempt to bind the socket to specific IP address
        int32_t bindResult = bind(socFd,
                                (SOCKADDR *)&localAddr,
                                sizeof(localAddr));

        if (bindResult == SOCKET_ERROR)
        {
            printf("ERROR: bind failed with %d for sendStrmReqInfoToTarget\n",
                    WSAGetLastError());
            retVal = IPNEXT_ERR_UDP_BIND_FAIL;
        }
        else
        {
            //! set the address family to IPv4
            destAddr.sin_family = AF_INET;

            // ! Copy the IP address to m_destAddr.sin_addr
            memcpy(&(destAddr.sin_addr.s_addr),
                    &m_pIpCfginfo->c10DestIPAddr,
                    sizeof(m_pIpCfginfo->c10DestIPAddr));

            destAddr.sin_port = htons(PORT_NUM);
        }

        if (retVal == IPNEXT_SUCCESS)
        {
            //! Set the timeout value for the socket connection, if it fails
            int32_t sockoptResult = setsockopt(socFd,
                                            SOL_SOCKET,
                                            SO_RCVTIMEO,
                                            (const CHAR *)&timeout,
                                            sizeof(int32_t));

            if (sockoptResult == SOCKET_ERROR)
            {
                printf("sendStrmReqInfoToTarget setsockopt for SO_RCVTIMEO Failed");
                retVal = IPNEXT_ERR_UDP_RECV_TIMEOUT;
            }
        }
    }

    //! Send the num of stream to process to target
    if (retVal == IPNEXT_SUCCESS)
    {
        int32_t bytesSent = sendto(socFd,
                                   (CHAR *)m_pTxRxConfig->pActStrmToProcess,
                                   sizeof(stActiveStreamFiles),
                                   0,
                                   (sockaddr*)&destAddr,
                                   sizeof(destAddr));

        if (bytesSent == SOCKET_ERROR)
        {
            printf("sendStrmReqInfoToTarget sendto failed with ErrCode: %d\n",
                    WSAGetLastError());
            retVal = IPNEXT_ERR_UDP_SENDTO;
        }
    }

    if (retVal == IPNEXT_SUCCESS)
    {
        //! Receive data using the socket connection and store it
        int32_t bytesRecv = recvfrom(socFd,
                                    (CHAR *)&frameHdr,
                                    sizeof(stFrameHeader),
                                    0,
                                    NULL,
                                    NULL);

        if (bytesRecv == SOCKET_ERROR)
        {
            //! Check if the error is due to timeout
            if (WSAGetLastError() == WSAETIMEDOUT)
            {
                printf("sendStrmReqInfoToTarget recvfrom Timeout!! Didn't recv all the data");
                retVal = IPNEXT_ERR_UDP_RECV_TIMEOUT;
            }
            else
            {
                printf("sendStrmReqInfoToTarget recvfrom failed ErrCode: %d",
                        WSAGetLastError());
                retVal = IPNEXT_ERR_UDP_RECVFROM;
            }
        }
    }
  
    if (retVal == IPNEXT_SUCCESS)
    {
        //! Incase negative ack received
        if (!frameHdr.isFrmAckSuccess)
        {
            retVal = IPNEXT_ERR_NEG_ACK;
        }
    }
   closesocket(socFd);
    return retVal;
    
}
# Error: frametxrxmngr.cpp:500 RH.LEAK (2:Error) Analyze
Resource acquired to 'socFd' at line 385 may be lost here.
  * frametxrxmngr.cpp:385: Resource is acquired: 'socFd' in the call to 'socket'
  * frametxrxmngr.cpp:500: Resource is lost: 'socFd'
Current status 'Analyze'

Even after removing the closesocket(socFd); getting the same error.

mercredi 16 août 2023

Do we really need to ensure giving up ownership when moving a `unique_ptr`?

I'm reading Nicolai M. Josuttis's C++ Move Semantics - The Complete Guide book (which is pretty good imho) and I'm not sure I agree with the comments in one of the examples.

Quote (from 6.1.2 - Guaranteed States of Moved-From Objects):

Similar code can be useful to release memory for an object that a unique pointer uses:

draw(std::move(up));  // the unique pointer might or might not give up ownership
up.reset();           // ensure we give up ownership and release any resource

Let's assume that the up variable is indeed unique_ptr and the draw function receives the unique_ptr by value (otherwise, what's the point of moving the pointer to a "passed-by-ref" function).

I understand that it is legal to call reset on a "moved-from" object. But what I do not understand is why it is "required" in order to "ensure we give up ownership and release any resource" and how is it possible that "the unique pointer might or might not give up ownership"?

After all, unique_ptrs cannot be copied and the whole idea is that they guarantee only one ownership.

So, afaik, if my two assumptions are correct, there is no need to call the reset function to ensure the ownership was given away.

Am I missing something?

C++11 compile time calculation of constant array

I have class with variadic template parameters like this:

template <uint16_t N1, uint16_t N2, uint16_t... Ns>
class TClass
{
public:
  static constexpr std::size_t S = sizeof...(Ns) + 2;
  static constexpr std::array<uint32_t, S> N = {N1, N2, Ns...};
  static constexpr std::array<uint32_t, S> P= /* struggle */;
};

Two numeric templates parameters are mandatory and more are optional.

I need to fill the array P at compile time with the following properties:

P[0] = 1
P[i] = N[i-1] * P[i-1]

So for example when having a class like this:

TClass instance<3,5,9>;

instance::N is filled with the values {3, 5, 9}

and

instance::P should be filled with the value {1, 3, 15}

Any idea how to generate the sequence for P in C++11 code at compile time?

I tried to use some kind of variadic template parameter unpacking but couldn't find a proper solution.

mardi 15 août 2023

Local function template in cpp file: should I make it static?

// CPP file

template<typename T>
void foo()
{
}

// Use the template only in this CPP as foo<int>, foo<char>, etc.

Suppose I have CPP file and there I have a template function foo for internal usage inside this CPP file only. Do I understand right that if I don't put the template into anonymous namespace or don't make it static, its instantiations used/created in this CPP file (e.g. foo<int>{}, foo<char>{}, etc.) will have outer linkage, i.e. will be seen outside. So is it true, that I better have the template static, as shown below or have it in anonymous namespace?

// CPP file

template<typename T>
static void foo()
{
}

I'm doing a project at school by C++ and seems like it has a problem with data byte. I've created some variations with long and assigned them to each other.

But the system has reported an error: [Error] invalid conversion from 'long int*' to 'long int' [-fpermissive]

Here is the function

int main()
{
    pair <long,long> a[1001];
    long ps[1001], b[1001];
    long n,m,l,r, L, R;
    cin >> n >> m;
    ps[0]=0;
    for(long i=1; i<=n; i++)
    {
        cin >> a[i].second >> a[i].first;
        ps[i]=ps[i-1]+a[i].second;
        b[i]=a[i].first;
    }
    sort(a+1,a+n);
    while(m--)
    {
        cin >> l >> r;
        L=lower_bound(b+1,b+n+1,l);
        R=upper_bound(b+1,b+n+1, r);
        cout << ps[R]-ps[L-1];
    }
}

lundi 14 août 2023

Why gcc does not create a new variable?

I have such code:

static const char kFmt[] = "some string: - %s";
char buf[sizeof(kFmt) + 10];
snprintf(buf, sizeof(buf), kFmt, "string");

It is look like arm gcc 6.3.0 does not create addition char array kFmt in RAM and just pass the pointer to string literal (that store in flash memory in my case) to snprintf. But if I remove const and have static char kFmt[] I can see that additional array is created in RAM and then passed to snprintf. It is not a problem but I wounder if this behavior is described somewhere in C++ standard or it is compiler optimization and it might differ in different compilers?

How do atomics larger than the CPU's native support work

With current C++ compilers you can have atomic support of atomics that are larger than the actual support of your CPU. With x64 you can have atomics that are 16 bytes, but std::atomic also works with larger tuples. Look at this code:

#include <iostream>
#include <atomic>

using namespace std;

struct S { size_t a, b, c; };

atomic<S> apss;

int main()
{
    auto ref = apss.load( memory_order_relaxed );
    apss.compare_exchange_weak( ref, { 123, 456, 789 } );
    cout << sizeof ::apss << endl;
}

The cout above always prints 32 for my platform. But how do these transactions actually work without a mutex ? I don't get any clue from inspecting the disassembly.

dimanche 13 août 2023

Why does GCC C++ issue to "warning: nonnull parameter `this' compared to NULL" when I'm passing this as a parameter? [closed]

Why does GCC C++ issue

warning: nonnull parameter `this' compared to NULL

when the code being compiled is passing this as a parameter even though this is not being compared to NULL or any of its equivalents?

In the constructor of a derived C++ class I pass this as a parameter to a function which is expecting a pointer to a base class of the derived class. The constructor never compares this against anything, much less NULL or its equivalents. Yet when this code is compiled by GCC 8.5.0 with -std=c++11 on RHEL 8.6 on x86_64 I get

warning: nonnull parameter `this' compared to NULL

Note that I didn't get this warning when the same code is compiled by GCC 4.8.5 with -std=c++0x on RHEL 7.9 on x86_64.

I can work around or suppress this warning, but I wonder why I'm getting this warning even though this code isn't comparing this to NULL or any of its equivalents.