samedi 30 avril 2022

How to call a derived class function from a base abstract class?

I am trying to overload an operator in the base class but i have to use one of the functions from the derived class, for example i have a Shape abstract class and i derive 3 classes circle, rectangle and square. Now to compare which one has the biggest perimeter i want to overload an operator > to the Shape class and iterate from there in the main, but i don't know how to get the perimeter() from a derived class to the base one.

#include<iostream>
#include<cstring>
using namespace std;
class Shape{
protected:
    char name[5];
public:
    Shape(char *name = " "){
        strcpy(this->name, name);
    }
    virtual double perimeter() = 0;
    bool operator>(const Shape* other){
        ......
    }
};
class Square: public Shape{
private:
    int side;
public:
    Square(char *name = " ", int side = 0): Shape(name){
        this->side = side;
    }
    double perimeter(){
        return 4.0*side;
    }
};
class Rectangle: public Shape{
private:
    int base;
    int height;
public:
    Rectangle(char *name = " ", int base = 0, int height = 0): Shape(name){
        this->base = base;
        this->height = height;
    }
    double perimeter(){
        return 2.0*(base+height);
    }
};
class Circle: public Shape{
private:
    int radius;
public:
    Circle(char *name = " ", int radius = 0): Shape(name){
        this->radius = radius;
    }
    double perimeter(){
        return 2*radius*3.14;
    }
};

What is the problem with this code and what's the good solution?

This is a question I'll have in my programming exam in uni and I need help understanding it

#include <iostream>
#include <string>
using namespace std;
int main()
{
int *tmb;
tmb = new int[1000] = { 0 };
for (register int i = 0; i < 1000; i++)
    cout << tmb[i];
free[] tmb;
system("PAUSE");
return 0;
}

vendredi 29 avril 2022

Get name of type behind type alias in function template

I'm working with Visual Studio 2013.

When I need to know what types the compiler deduced for my template parameters, I usually trigger a compiler error like this:

template <typename U>
struct TD;

template <typename T>
void f(T) {
    TD<T> t{};
}

int main() {
    f(1);
}

And this works, as Visual Studio will tell me I tried to instanciate my undefined struct TD with an int:

error C2079: 't' uses undefined struct 'TD<T>'
        with
        [
            T=int
        ]
note: see reference to function template instantiation 'void f<int>(T)' being compiled
        with
        [
            T=int
        ]

However, the above trick becomes useless on Visual Studio if I want to know what's the type behind a type alias. E.g. the following:

template <typename T>
void f(T) {
    using unsigned_int_t = typename std::make_unsigned<T>::type;
    TD<unsigned_int_t> t{};
}

will produce:

error C2079: 't' uses undefined struct 'TD<unsigned_int_t>'
note: see reference to function template instantiation 'void f<int>(T)' being compiled
        with
        [
            T=int
        ]

Whereas GCC will tell me that unsigned_int_t is a unsigned int:

error: 'TD<unsigned int> t' has incomplete type
   10 |     TD<unsigned_int_t> t{};

So, is there a way to get the name of the type behind a type alias with Visual Studio 2013?

Note: I already had a look at Print template typename at compile time but no answer worked for me.

convert string to keyword in C++ [closed]

I want to convert a string(eg. "uint8_t") to keyword(uint8_t) without using if else or switch condition or templates ?

Latest VSCode 1.66.2 does not stop on failed assertion in C++ CMake debugging session

My VSCode:

Version: 1.66.2
Commit: dfd34e8260c270da74b5c2d86d61aee4b6d56977
Date: 2022-04-11T07:49:24.808Z
Electron: 17.2.0
Chromium: 98.0.4758.109
Node.js: 16.13.0
V8: 9.8.177.11-electron.0
OS: Linux x64 5.15.0-27-generic snap

I am using Ubuntu 22.04, gdb 12.0.90, g++ 11.2.0. assert(false) does NOT stop the VSCode debugging session at the faulting line of code but terminates the debugging session. This is what I see in the VSCode Terminal:

Aborted (core dumped)
[1] + Aborted (core dumped)      "/bin/gdb" --interpreter=mi --tty=${DbgTerm} 0<"/tmp/Microsoft-MIEngine-In-xqkekjkv.um3" 1>"/tmp/Microsoft-MIEngine-Out-pnbr5eby.w1g"

C++ google test fail for multi threads

I am having following C++ code and corresponding unit tests in google test. I am studying book on Modern C++ programming using Test Driven development. Below code is crashing in scale tests. Problem to my analysis is this part of code. If this code is removed program is running. Another observations same code is working in another test case "HandlesLargeNumbersOfUsers" with single or multiple threads. your inputs will help me in moving further.

Work work{ [&] {
           if (isDifferentUserInBounds(each, user, box))
              listener->updated(User{each.first, each.second});
        } }; 

enter image description here

class GeoServerUsersInBoxTests : public testing::Test {
public:
    GeoServer server;

    const double TenMeters{ 10 };
    const double Width{ 2000 + TenMeters };
    const double Height{ 4000 + TenMeters };
    const string aUser{ "auser" };
    const string bUser{ "buser" };
    const string cUser{ "cuser" };

    Location aUserLocation{ 38, -103 };

    shared_ptr<ThreadPool> pool;

    virtual void SetUp() override {
        server.useThreadPool(pool);

        server.track(aUser);
        server.track(bUser);
        server.track(cUser);

        server.updateLocation(aUser, aUserLocation);
    }

    string userName(unsigned int i) {
        return string{ "user" + to_string(i) };
    }

    void addUsersAt(unsigned int number, const Location& location) {
        for (unsigned int i{ 0 }; i < number; i++) {
            string user = userName(i);
            server.track(user);
            server.updateLocation(user, location);
        }
    }
};

class AGeoServer_ScaleTests : public GeoServerUsersInBoxTests {

public:

    class GeoServerCountingListener : public GeoServerListener {
    public:
        void updated(const User& user) override {
            unique_lock<std::mutex> lock(mutex_);
            Count++;
            wasExecuted_.notify_all();
        }

        void waitForCountAndFailOnTimeout(unsigned int expectedCount,
            const milliseconds& time = milliseconds(10000)) {
            unique_lock<mutex> lock(mutex_);
            ASSERT_TRUE(wasExecuted_.wait_for(lock, time, [&]
                { return expectedCount == Count; }));
        }

        condition_variable wasExecuted_;
        unsigned int Count{ 0 };
        mutex mutex_;
    };

    GeoServerCountingListener countingListener;
    shared_ptr<thread> t;

    void SetUp() override {
        pool = make_shared<ThreadPool>();
        GeoServerUsersInBoxTests::SetUp();
    }

    void TearDown() override {
        t->join();
    }
};


TEST_F(AGeoServer_ScaleTests, HandlesLargeNumbersOfUsers) {
    pool->start(4);
    const unsigned int lots{ 5000 };
    addUsersAt(lots, Location{ aUserLocation.go(TenMeters, West) });

    t = make_shared<thread>(
        [&] { server.usersInBox(aUser, Width, Height, &countingListener); });

    countingListener.waitForCountAndFailOnTimeout(lots);
}

ThreadPool.h

class ThreadPool {
public:
    virtual ~ThreadPool() {
        stop();
    }

    void stop() {
        done_ = true;
        for (auto& thread : threads_) thread.join();
    }

    void start(unsigned int numberOfThreads = 1) {
        for (unsigned int i{ 0u }; i < numberOfThreads; i++)
            threads_.push_back(std::thread(&ThreadPool::worker, this));
    }

    bool hasWork() {
        std::lock_guard<std::mutex> block(mutex_);
        return !workQueue_.empty();
    }

    virtual void add(Work work) {
        std::lock_guard<std::mutex> block(mutex_);
        workQueue_.push_front(work);
    }

    Work pullWork() {
        std::lock_guard<std::mutex> block(mutex_);

        if (workQueue_.empty()) return Work{};

        auto work = workQueue_.back();
        workQueue_.pop_back();
        return work;
    }

private:
    void worker() {
        while (!done_) {
            while (!done_ && !hasWork())
                ;
            if (done_) break;
            pullWork().execute();
        }
    }

    std::atomic<bool> done_{ false };
    std::deque<Work> workQueue_;
    std::shared_ptr<std::thread> workThread_;
    std::mutex mutex_;
    std::vector<std::thread> threads_;
};

GeoServer.cpp

void GeoServer::track(const string& user) {
    locations_[user] = Location();
}

void GeoServer::stopTracking(const string& user) {
    locations_.erase(user);
}

bool GeoServer::isTracking(const string& user) const {
    return find(user) != locations_.end();
}

void GeoServer::updateLocation(const string& user, const Location& location) {
    locations_[user] = location;
}

Location GeoServer::locationOf(const string& user) const {
    if (!isTracking(user)) return Location{}; // TODO performance cost?

    return find(user)->second;
}

std::unordered_map<std::string, Location>::const_iterator
GeoServer::find(const std::string& user) const {
    return locations_.find(user);
}

bool GeoServer::isDifferentUserInBounds(
    const pair<string, Location>& each,
    const string& user,
    const Area& box) const {
    if (each.first == user) return false;
    return box.inBounds(each.second);
}

void GeoServer::usersInBox(
    const string& user, double widthInMeters, double heightInMeters,
    GeoServerListener* listener) const {
    auto location = locations_.find(user)->second;
    Area box{ location, widthInMeters, heightInMeters };

    for (auto& each : locations_) {
        Work work{ [&] {
           if (isDifferentUserInBounds(each, user, box))
              listener->updated(User{each.first, each.second});
        } };
        pool_->add(work);
    }
}

jeudi 28 avril 2022

ambiguous call of overload template function using decltype in google client library

I'm currently tried to build google cloud client libraries on windows. On build the final library I run into function call is ambiguous. They have the below code in a header pagination_range.h. The issue google response class sometimes have both or none of the declared functions would this ever be able to run/compile with c++11 in msys or msvc

typename StreamReader<T>::result_type GetNext() {
    if (current_ == page_.end()) {
      if (last_page_) return Status{};
      request_.set_page_token(std::move(token_));
      auto response = loader_(request_);
      if (!response.ok()) return std::move(response).status();
      token_ = ExtractPageToken(*response);
      if (token_.empty()) last_page_ = true;
      page_ = extractor_(*std::move(response));
      current_ = page_.begin();
      if (current_ == page_.end()) return Status{};
    }
    return std::move(*current_++);

template <typename U>
  static constexpr auto ExtractPageToken(U& u)
      -> decltype(std::move(*u.mutable_next_page_token())) {
    return std::move(*u.mutable_next_page_token());
  }
  template <typename U>
  static constexpr auto ExtractPageToken(U& u)
      -> decltype(std::move(u.next_page_token)) {
    return std::move(u.next_page_token);
  }

using get_time to parse string, part of the format doesn't seem to register

I'm trying to parse a string of date with the format seconds:minutes:hour:dayInMonth:month:year

For example: 58:48:20:12:8:1905

The code:

        struct std::tm time{};
        std::istringstream stream(timeString);
        stream >> std::get_time(&time, "%S:%M:%H:%d:%m:%Y");

timeString value is the time values and I've checked that it is as I expect. get_time puts the values of seconds:minutes:hour:dayInMonth correctly inside the time variable but the month:year values are not parsed and remain 0 in the variable. I've tried other formats such as %mm:%YYYY but it didn't fix the issue.

Help would be appreciated.

How reduce false detection in my code and how to improve tracking accuracy?

Code is working fine but not accurate

Step: 1

  1. Read Frame from Camera
  2. Select ROI(Region of Interest)
  3. After that start KCF tracker with Sobal Features Extractor
  4. Tracking the selected object.

Step: 2

  1. Failure detect
  2. After that call template matching function called MatchingMethod()
  3. Run template matching
  4. Get x, y value from template matching
  5. After that reinitialize KCF tracker with Sobal Features Extractor.

This code is fine for still object when the object is moving the tracker false detection. I want to improve accuracy and reduce false detection.

#include <opencv2/core/utility.hpp>
#include <opencv2/tracking.hpp>
#include <opencv2/videoio.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/core/ocl.hpp>
#include <iostream>
#include <cstring>
#include <unistd.h>
#include "sample_utility.hpp"
#include <thread>
#include <opencv2/cudaimgproc.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/calib3d.hpp>
#include <opencv2/cudaarithm.hpp>
#include <iomanip>
#include <stdlib.h>
#include <unistd.h>
//////////////////////////////
    
using namespace cv;
using namespace std;
    
////////////////////////////
// Convert to string
#define SSTR( x ) static_cast< std::ostringstream & >( \
( std::ostringstream() << std::dec << x ) ).str()
/// Global Variables
struct Array {
    int arr[2];
    };
Mat img;
Mat templ;
Mat result_h;

bool flag = true;    
int match_method = 5;
int i=0;
int max_Trackbar = 5;
float fps;
int seconds = 0;
// Function Headers
void delay();
// prototype of the functino for feature extractor
void sobelExtractor(const Mat img, const Rect roi, Mat& feat);
struct Array MatchingMethod( int, void* );
int main(int argc, char **argv)
    {
    TrackerKCF::Params param;
    param.compress_feature = true;
    param.compressed_size = 2;
    param.desc_npca = 0;
    param.desc_pca = TrackerKCF::GRAY | TrackerKCF::CN;
    param.detect_thresh = 0.8;
    // create a tracker object
    Ptr<TrackerKCF> tracker = TrackerKCF::create(param);
    tracker->setFeatureExtractor(sobelExtractor);
    VideoCapture cap(0);
    // Exit if video is not opened
    if(!cap.isOpened())
        {
        //cout << "Could not read video file" << endl;
        return 1;
        }
    
    // Read first frame
    Mat frame;
    bool ok = cap.read(frame);
    // Define initial bounding box
    //Rect bbox(x, y, w, h);
    // Uncomment the line below to select a different bounding box
    Rect bbox = selectROI(frame, false);
    // Display bounding box.
    rectangle(frame, bbox, Scalar( 255, 0, 0 ), 2, 1 );
    ///////////////////////////
    int H, W, cW, cH;
    // print(f"hight {H} , Width {W}")
    H = display_height;
    W = display_width;
    // Center point of the screen
    cW = int(W / 2);
    cH = int(H / 2);
    Point p1(cW, cH);
    // get bounding box
    Mat imCrop = frame(bbox);
    imwrite("1.png", imCrop);
    //quit if ROI was not selected
    if(bbox.width==0 || bbox.height==0)
        return 0;
    //////////////////////////
    //imshow("Tracking", frame);
    tracker->init(frame, bbox);
    while(true)
        {
        Mat frame;
        cap >> frame;
        circle(frame, p1, 3, Scalar(0,255,0), -1);
        // Start timer
        if(bbox.width!=0 || bbox.height!=0){
            double timer = (double)getTickCount();
            // Update the tracking result
            /////////////////////////////////////
            bool ok = tracker->update(frame, bbox);
            //////////////////////////////////////
            //ok, bbox = tracker->update(frame);
            // Calculate Frames per second (FPS)
            fps = getTickFrequency() / ((double)getTickCount() - timer);
            if (ok)
                {
                // Tracking success : Draw the tracked object
                rectangle(frame, bbox, Scalar( 255, 0, 0 ), 2, 1 );
                ///////////////////////////////////////////////////
                int xxx, yyy, height, width;
                xxx = bbox.x;
                yyy = bbox.y;
                height = bbox.height;
                width = bbox.width;
                int diffX, diffY;
                float cxROI, cyROI;
                cxROI = int((xxx + (xxx + width)) / 2);
                cyROI = int((yyy + (yyy + height)) / 2);
                diffX = cxROI - cW;
                diffY = cH - cyROI;
                //cout<<diffX<<"\n";
                //cout<<diffY<<"\n";
                Point p(cxROI, cyROI);
                circle(frame, p, 3, Scalar(128,0,0), -1);
                putText(frame, "FPS : " + SSTR(int(fps)), Point(100,20), FONT_HERSHEY_SIMPLEX, 0.75, Scalar(50,170,50), 2);
                putText(frame, "Difference From X-Axis: "+SSTR(int(diffX)), Point(100, 50), FONT_HERSHEY_SIMPLEX, 0.6, Scalar(100, 200, 200), 2);
                putText(frame, "Difference From Y-Axis: "+SSTR(int(diffY)), Point(100, 80), FONT_HERSHEY_SIMPLEX, 0.6, Scalar(100, 200, 200), 2);
                }
                else
                {
                // Tracking failure detected.
                putText(frame, "Tracking failure detected", Point(100,110), FONT_HERSHEY_SIMPLEX, 0.75, Scalar(0,0,255),2);
                templ = imread( "1.png", 1 );
                img=frame.clone();
                struct Array a = MatchingMethod( 0, 0 );
                cout<<"X: "<<a.arr[0]<<"\n";
                cout<<"Y: "<<a.arr[1]<<"\n";
                cout<<"Width: "<<w<<"\n";
                cout<<"Height: "<<h<<"\n";
                int xx, yy, ww, hh;
                xx = a.arr[0];
                yy = a.arr[1];
                ww = w;
                hh = h;
                Rect bbox(xx, yy, ww, hh);
                tracker.release();
                tracker = TrackerKCF::create(param);
                tracker->setFeatureExtractor(sobelExtractor);
                tracker->init(frame, bbox);
                //roi.x = MatchingMethod.
                //waitKey(30);
                rectangle(frame, bbox, Scalar( 255, 0, 0 ), 2, 1 );
                ////////////////////////////////////////////////////////////////////////
                int diffX, diffY;
                float cxROI, cyROI;
                cxROI = int((xx + (xx + ww)) / 2);
                cyROI = int((yy + (yy + hh)) / 2);
                diffX = cxROI - cW;
                diffY = cH - cyROI;
                //cout<<diffX<<"\n";
                //cout<<diffY<<"\n";
                Point p(cxROI, cyROI);
                circle(frame, p, 3, Scalar(128,0,0), -1);
                ///////////////////////////////////////////////////////////////////////////
                }
        }
        else{
    
        }
                
                // Display frame.
                imshow("Tracking", frame);
                // Exit if ESC pressed.
                int k = waitKey(1);
                if(k == 27)
                   {
                    break;
                    }
        }
return 0;
}
///////////////////////
void sobelExtractor(const Mat img, const Rect roi, Mat& feat){
    Mat sobel[2];
    Mat patch;
    Rect region=roi;
    // extract patch inside the image
    if(roi.x<0){region.x=0;region.width+=roi.x;}
    if(roi.y<0){region.y=0;region.height+=roi.y;}
    if(roi.x+roi.width>img.cols)region.width=img.cols-roi.x;
    if(roi.y+roi.height>img.rows)region.height=img.rows-roi.y;
    if(region.width>img.cols)region.width=img.cols;
    if(region.height>img.rows)region.height=img.rows;
    patch=img(region).clone();
    cvtColor(patch,patch, COLOR_BGR2GRAY);
    // add some padding to compensate when the patch is outside image border
    int addTop,addBottom, addLeft, addRight;
    addTop=region.y-roi.y;
    addBottom=(roi.height+roi.y>img.rows?roi.height+roi.y-img.rows:0);
    addLeft=region.x-roi.x;
    addRight=(roi.width+roi.x>img.cols?roi.width+roi.x-img.cols:0);
             
    copyMakeBorder(patch,patch,addTop,addBottom,addLeft,addRight,BORDER_REPLICATE);
    
    Sobel(patch, sobel[0], CV_32F,1,0,1);
    Sobel(patch, sobel[1], CV_32F,0,1,1);
    
    merge(sobel,2,feat);
    
    feat=feat/255.0-0.5; // normalize to range -0.5 .. 0.5
}
////////////////////////////////////////////////////
struct Array MatchingMethod( int, void* )
    {
    /// Source image to display
    Mat frame;
    struct Array a;
    /////////
    for(int i=1; i<=4; i++){
    img.copyTo( frame );
    //  break;
    //}
    //////////////////////////
    cv::cuda::setDevice(0); // initialize CUDA  
    // convert from mat to gpumat
    cv::cuda::GpuMat image_d(img);
    cv::cuda::GpuMat templ_d(templ);
    cv::cuda::GpuMat result;
    // GPU -> NG
    cv::Ptr<cv::cuda::TemplateMatching> alg = 
    cv::cuda::createTemplateMatching(image_d.type(), cv::TM_CCOEFF_NORMED);
    alg->match(image_d, templ_d, result);  // no return.
    
    //cv::cuda::normalize(result, result, 0, 1, cv::NORM_MINMAX, -1);
    double max_value, min_value;
    cv::Point location;
    cv::cuda::minMaxLoc(result, &min_value, &max_value, 0, &location);
    /////////////////////////
    double THRESHOLD = 3e-09;  //0.3;
    
    if( min_value <= THRESHOLD) {
        //struct Array a;
        a.arr[0] = location.x;
        a.arr[1] = location.y;
        cout<<"Hi"<<endl;
    }   
 }
    if(flag==true){
    return a;
    flag = false;
        }
       
      //}
    }

*//https://github.com/opencv/opencv_contrib/blob/master/modules/tracking/samples/samples_utility.hpp
    // Opencv link 
    // https://techawarey.com/programming/install-opencv-c-c-in-ubuntu-18-04-lts-step-by-step-guide/#Summary
    // Compile command
    // g++ test.cpp -o testoutput -std=c++11 `pkg-config --cflags --libs opencv`
    // ./testoutput*

mercredi 27 avril 2022

CMake add_executable() failing to make executable and 3rd party library failing to untar

Problem Background

I am trying to incorporate UnitTest++ into my linux-based C++17 project template. I have done this on windows pretty easily, but I am running into major issues on linux for some reason.

I used Cmake 3.21 on Windows and I am using CMake 3.17.5 on Linux.

I downloaded the UnitTest++ source code from the UnitTest++ Github. and proceeded to throw the tar.gz into my 3rdParty folder in my ProjectTemplate. I have had major trouble getting it to build. So I have stripped out everything except for the one 3rd party library I added and the things that folder affects. So at this point all the main() functions are very simple. I am just expecting to see executables that do nothing.

Problem Points

  • The main executable gets made, but the unit testing executable (testExecutable) does not get made.
  • The build fully finishes with no errors even though an executable failed to be made.
  • The UnitTest++ 3rd party library fails to untar with no errors output.

I have included the actual contents of my cmake and the build output.

Why is the testExecutable not getting made? More importantly, why is my UnitTest++ failing to untar?

Directory Structure

ProjectTemplate
    +3rdParty
        -CMakeLists.txt (3rd party cmake)
        -unittest-cpp-2.0.0.tar.gz
    +build
    +src
        -ClassTemplate.cpp (just a plain class file - compiles fine)
        -ClassTemplate.hpp (just a plain class file - compiles fine)
        -main.cpp (basic int main function)
    +UnitTests
        -CMakeLists.txt (unit test cmake)
        -UnittestcppMain.cpp (basic int main function)
    -CMakeLists.txt (root cmake)
    

CMake Contents

root cmake

cmake_minimum_required(VERSION 3.12)

# ====================================================================================================
#                                           Project Settings
# ====================================================================================================
project(ProjectName  VERSION 1.0.0.0 
                    DESCRIPTION "Project Description"
                    LANGUAGES CXX)

#Compiler Flags (Language default is C++17)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O3 -Wall -std=c++17 -pedantic -U_FORTIFY_SOURCE")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O3 -Wall -ansi -pedantic -U_FORTIFY_SOURCE")

#Project Source code Definitions
set(SOURCE
    ${CMAKE_SOURCE_DIR}/src/ClassTemplate.cpp
    ${CMAKE_SOURCE_DIR}/src/ClassTemplate.hpp)

#Project Library Definitions
add_library(ExecutableLib ${SOURCE})

#Project Executable Definitions
add_executable(ExecutableName ${CMAKE_SOURCE_DIR}/src/main.cpp)

#Project Include Directory Definitions
target_include_directories(ExecutableLib PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/src/)

# ====================================================================================================
#                                      Project Links to Libraries
# ====================================================================================================
target_link_libraries(ExecutableName PRIVATE pthread )
target_link_libraries(ExecutableName PRIVATE ExecutableLib )
target_link_libraries(ExecutableName PRIVATE uuid)

# ====================================================================================================
#                                          Cmake Branch offs
# ====================================================================================================
add_subdirectory(${CMAKE_SOURCE_DIR}/3rdParty)  #Builds 3rd Party Libraries
add_subdirectory(${CMAKE_SOURCE_DIR}/UnitTests) #Builds Unit Tests

3rd party cmake

# ====================================================================================================
#                                          UnitTest++
# ====================================================================================================
set (UTCPP_PATH "${CMAKE_BINARY_DIR}/3rdParty/unittest-cpp-2.0.0")
set (UTCPP_TAR_PATH "${CMAKE_SOURCE_DIR}/3rdParty")
set (UTCPP_TARBALL_NAME "unittest-cpp-2.0.0.tar.gz")
set (UTCPP_FINAL_OBJECT "${UTCPP_PATH}/builds/libUnitTest++.a")
set (UTCPP_STAMP "UTCPP.stamp")

add_custom_target( UTCPP_untar_target ALL DEPENDS ${UTCPP_PATH}/${UTCPP_STAMP})
add_custom_target( UTCPP_build_target ALL DEPENDS ${UTCPP_FINAL_OBJECT})
add_library(UTCPP_3rdParty STATIC IMPORTED GLOBAL)

add_dependencies(UTCPP_build_target UTCPP_untar_target)

#decompresses the tar file
add_custom_command(OUTPUT ${UTCPP_PATH}/${UTCPP_STAMP}
   COMMAND ${CMAKE_COMMAND} -E remove_directory ${UTCPP_PATH}
   COMMAND ${CMAKE_COMMAND} -E tar xf ${UTCPP_TAR_PATH}/${UTCPP_TARBALL_NAME}
   COMMAND ${CMAKE_COMMAND} -E touch ${UTCPP_PATH}/${UTCPP_STAMP}
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/3rdParty/
DEPENDS ${UTCPP_TAR_PATH}/${UTCPP_TARBALL_NAME}
COMMENT "Unpacking Unittest++ ${UTCPP_TARBALL_NAME}"
VERBATIM)

#So cmake does not complain about include dir not existing
file(MAKE_DIRECTORY "${UTCPP_PATH}")

#Builds UnitTest++ (unittest++ tar has a 'builds' directory where it expects to do builds)
add_custom_command(
      OUTPUT ${UTCPP_FINAL_OBJECT}
      COMMAND ${CMAKE_COMMAND} -DCMAKE_INSTALL_PREFIX=${UTCPP_PATH}/builds ..;
      COMMAND $(MAKE);
      COMMAND $(MAKE) install;
      WORKING_DIRECTORY ${UTCPP_PATH}/builds/
      COMMENT "Building ${UTCPP_FINAL_OBJECT}")

add_dependencies(UTCPP_3rdParty UTCPP_build_target)
add_dependencies(UTCPP_3rdParty ${UTCPP_FINAL_OBJECT})
set_target_properties(UTCPP_3rdParty PROPERTIES
IMPORTED_LOCATION "${UTCPP_FINAL_OBJECT}"
INTERFACE_INCLUDE_DIRECTORIES "${UTCPP_PATH}")

unit test cmake

message("Made it to this")
add_executable(testExecutable ${CMAKE_CURRENT_SOURCE_DIR}/UnittestcppMain.cpp)
target_link_libraries(testExecutable UTCPP_3rdParty)
target_link_libraries(testExecutable pthread)
target_link_libraries(testExecutable ExecutableLib)

Build Output

Output from cmake generation / configure

[main] Configuring folder: ProjectTemplate 
[proc] Executing command: /usr/bin/cmake3 --no-warn-unused-cli -DCMAKE_EXPORT_COMPILE_COMMANDS:BOOL=TRUE -DCMAKE_BUILD_TYPE:STRING=Debug -DCMAKE_C_COMPILER:FILEPATH=/opt/rh/devtoolset-8/root/usr/bin/gcc -DCMAKE_CXX_COMPILER:FILEPATH=/opt/rh/devtoolset-8/root/usr/bin/g++ -S/path/to/ProjectTemplate -B/path/to/ProjectTemplate/build -G "Unix Makefiles"
[cmake] Not searching for unused variables given on the command line.
[cmake] -- The CXX compiler identification is GNU 8.3.1
[cmake] -- Check for working CXX compiler: /opt/rh/devtoolset-8/root/usr/bin/g++
[cmake] -- Check for working CXX compiler: /opt/rh/devtoolset-8/root/usr/bin/g++ - works
[cmake] -- Detecting CXX compiler ABI info
[cmake] -- Detecting CXX compiler ABI info - done
[cmake] -- Detecting CXX compile features
[cmake] -- Detecting CXX compile features - done
[cmake] Made it to this
[cmake] -- Configuring done
[cmake] -- Generating done
[cmake] -- Build files have been written to: /path/to/ProjectTemplate/build

output from build

[main] Building folder: ProjectTemplate 
[build] Starting build
[proc] Executing command: /usr/bin/cmake3 --build /path/to/ProjectTemplate/build --config Debug --target ExecutableName -j 18 --
[build] Scanning dependencies of target ExecutableLib
[build] [ 25%] Building CXX object CMakeFiles/ExecutableLib.dir/src/ClassTemplate.cpp.o
[build] [ 50%] Linking CXX static library libExecutableLib.a
[build] [ 50%] Built target ExecutableLib
[build] Scanning dependencies of target ExecutableName
[build] [ 75%] Building CXX object CMakeFiles/ExecutableName.dir/src/main.cpp.o
[build] [100%] Linking CXX executable ExecutableName
[build] [100%] Built target ExecutableName
[build] Build finished with exit code 0

I can't get the assignment operator = to overload in cpp [closed]

The comparison in the assignment operator works as expected, but when I try to use a temp variable and load then return that, all it returns is the defaults. Debugs show that the values are {...}, but I'm not sure what to with it to make it fill the temp variables and return them. Everything I've gone through says it should work.

main

    // Demonstrating class Polynomial's overloaded stream insertion 
// and stream extraction operators.
#include <iostream>

#include "Polynomial.h"
using namespace std;

int main() {


    Polynomial poly; // create object poly
    Polynomial poly2; // create object poly
    Polynomial poly3; // create object poly
    Polynomial poly4; // create object poly
    Polynomial poly5; // create object poly


    cout << "Enter polynomial number in the form 2x4:" << endl;
    // cin >> phone invokes operator>> by implicitly issuing
    // the non-member function call operator>>(cin, phone)
    cin >> poly;
    cout << "\nThe polynomial number entered was:\n";
    // cout << phone invokes operator<< by implicitly issuing
    // the non-member function call operator<<(cout, phone)
    cout << poly << endl;
    cout << "Enter polynomial number in the form 2x4:" << endl;
    // cin >> phone invokes operator>> by implicitly issuing
    // the non-member function call operator>>(cin, phone)
    cin >> poly2;
    cout << "\nThe polynomial number entered was:\n";
    // cout << phone invokes operator<< by implicitly issuing
    // the non-member function call operator<<(cout, phone)
    cout << "poly2 " << poly2 << endl;
    poly3 = poly + poly2;
    cout << "poly3 " << poly3 << endl;
    poly4 = poly - poly2;
    cout << "poly4 " << poly4 << endl;
    poly5 = poly;
    cout << "poly5 " << poly5 << endl;
  }

Header

#pragma once
#ifndef POLYNOMIAL_H
#define POLYNOMIAL_H

#include <iostream>
#include <string>

class Polynomial {
    friend std::ostream& operator<<(std::ostream&, const Polynomial&);
    friend std::istream& operator>>(std::istream&, Polynomial&);

public:
    // Default Constructor

    Polynomial(std::string coefficient = "1", std::string variable = "x",
        std::string exponent = "4");

    // Copy Constructor
    Polynomial(const Polynomial& copy)
        : coefficient{ copy.coefficient }, variable{ copy.variable },
        exponent{ copy.exponent } {
        std::cout << "Copy Constructor called" << std::endl;
    }

    void setPolynomial(std::string, std::string, std::string);
    Polynomial getPolynomial();
    // addition operator; Polynomial + Polynomial
    Polynomial operator+(const Polynomial&) const;
    // subtraction operator; Polynomial - Polynomial
    Polynomial operator-(const Polynomial&) const;
    // assigment operator; Polynomial - Polynomial
    Polynomial operator=(const Polynomial&) const;

private:
    std::string coefficient; // 
    std::string variable;    // 
    std::string exponent;    // 
};

#endif

Polynomial.cpp

// Overloaded stream insertion and stream extraction operators
// for class PhoneNumber.
#include "Polynomial.h"
#include <iomanip>
using namespace std;

// default constructor; conversion constructor that converts
Polynomial::Polynomial(std::string co, std::string va, std::string ex) {}
// Setters
void Polynomial::setPolynomial(std::string co, std::string va, std::string ex) {
    this->coefficient = co;
    this->variable = va;
    this->exponent = ex;
}
// Getters
Polynomial Polynomial::getPolynomial() { return *this; }
// overloaded stream insertion operator; cannot be a member function
// if we would like to invoke it with cout << somePhoneNumber;
ostream& operator<<(ostream& output, const Polynomial& number) {
    output << "Coefficient: " << number.coefficient
        << "\nVariable: " << number.variable
        << "\nExponent: " << number.exponent << "\n"
        << "" << number.coefficient << "" << number.variable << "^"
        << number.exponent << "\n";
    return output; // enables cout << a << b << c;
}

// overloaded stream extraction operator; cannot be a member function
// if we would like to invoke it with cin >> somePhoneNumber;
istream& operator>>(istream& input, Polynomial& number) {
    input >> setw(1) >> number.coefficient; // input area code
    input >> setw(1) >> number.variable;    // input exchange
    input >> setw(1) >> number.exponent;    // input line
    return input;                           // enables cin >> a >> b >> c;
}

// addition operator; Polynomial + Polynomial
// A member function takes an implicit first parameter
Polynomial Polynomial::operator+(const Polynomial& op1) const {
    Polynomial temp; // temporary result

    if (this->variable == op1.variable) {
        if (this->exponent == op1.exponent) {
            // Use stoi string to int
            int num1 = stoi(this->coefficient);
            int num2 = stoi(op1.coefficient);
            // use to_string to set coefficient
            std::string s = std::to_string(num1 + num2);
            temp.coefficient = s;
            temp.variable = this->variable;
            temp.exponent = this->exponent;
        }
        else {
            std::cout << "Exponents must match\n";
        }
    }
    else {
        std::cout << "Variables must match\n";
    }
    return temp; // return copy of temporary object
}
// substraction operator; Polynomial - Polynomial
// A member function takes an implicit first parameter
Polynomial Polynomial::operator-(const Polynomial& op1) const {
    Polynomial temp; // temporary result

    if (this->variable == op1.variable) {
        if (this->exponent == op1.exponent) {
            // Use stoi string to int
            int num1 = stoi(this->coefficient);
            int num2 = stoi(op1.coefficient);
            // use to_string to set coefficient
            std::string s = std::to_string(num1 - num2);
            temp.coefficient = s;
            temp.variable = this->variable;
            temp.exponent = this->exponent;
        }
        else {
            std::cout << "Exponents must match\n";
        }
    }
    else {
        std::cout << "Variables must match\n";
    }
    return temp; // return copy of temporary object
}

// assignment operator; Polynomial - Polynomial
// A member function takes an implicit first parameter
Polynomial Polynomial::operator=(const Polynomial& op1) const {
    // self assignment guard
    if (this == &op1) {
        return *this;//This returns as expected.
        // 
    } // This should create a new temp, assign the second's info to it and return it.
    // But all it does is return the default constructor values 1x4
    Polynomial temp;
    temp.coefficient = op1.coefficient;
    temp.variable = op1.variable;
    temp.exponent = op1.exponent;
    return temp;
}

How to get the type of the first parameter of a dependent function pointer template parameter in C++11?

Current code:

#include <utility>

template <typename T, void (*D)(T *)>
std::pair<T *, void (*)(T *)> f(T * const t)
{
    // ...
    return std::make_pair(t, D); // need `T` and `D` here
}

void d(int *t);

void g()
{
    auto something = f<int, d>(new int {5});        
}

What I'd like:

#include <utility>

template </* fill here: only `D` */>
std::pair<T *, void (*)(T *)> f(T * const t)
{
    // ...
    return std::make_pair(t, D); // need `T` and `D` here
}

void d(int *t);

void g()
{
    auto something = f<d>(new int {5});        
}

Is this possible in C++11?

Moving all Elements in a std::vector not working as expected

I'm trying to move the whole vector to another variable. The following code block does not compile. I thought that the call to std::move would force to use the Move-Constructor. Instead it seems like std::vector is using the Copy-Constructor that is deleted.

What's wrong here? How can I move all elements without copying them?

#include <vector>

class TheClass {
public:
  TheClass(const TheClass&) = delete;
  TheClass(TheClass&&) = default;
};

void fun2(const std::vector<TheClass> data) {
  std::vector<TheClass> a = std::move(data);
  a.size();
}

leads to:

clang++ -o /cplayground/cplayground /cplayground/code.cpp -I/cplayground/include -L/cplayground/lib -std=c++20 -O0 -Wall -no-pie -lm -pthread
In file included from /cplayground/code.cpp:1:
In file included from /usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/vector:66:
/usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/stl_uninitialized.h:137:7: error: static_assert failed due to requirement 'is_constructible<TheClass, const TheClass &>::value' "result type must be constructible from value type of input range"
      static_assert(is_constructible<_ValueType2, decltype(*__first)>::value,
      ^             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/stl_uninitialized.h:325:19: note: in instantiation of function template specialization 'std::uninitialized_copy<__gnu_cxx::__normal_iterator<const TheClass *, std::vector<TheClass, std::allocator<TheClass> > >, TheClass *>' requested here
    { return std::uninitialized_copy(__first, __last, __result); }
                  ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/stl_vector.h:558:9: note: in instantiation of function template specialization 'std::__uninitialized_copy_a<__gnu_cxx::__normal_iterator<const TheClass *, std::vector<TheClass, std::allocator<TheClass> > >, TheClass *, TheClass>' requested here
          std::__uninitialized_copy_a(__x.begin(), __x.end(),
               ^
/cplayground/code.cpp:10:29: note: in instantiation of member function 'std::vector<TheClass, std::allocator<TheClass> >::vector' requested here
  std::vector<TheClass> a = std::move(data);
                            ^
In file included from /cplayground/code.cpp:1:
In file included from /usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/vector:62:
In file included from /usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/stl_algo.h:62:
In file included from /usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/stl_tempbuf.h:60:
/usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/stl_construct.h:109:38: error: call to deleted constructor of 'TheClass'
    { ::new(static_cast<void*>(__p)) _Tp(std::forward<_Args>(__args)...); }
                                     ^   ~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/stl_uninitialized.h:91:8: note: in instantiation of function template specialization 'std::_Construct<TheClass, const TheClass &>' requested here
                std::_Construct(std::__addressof(*__cur), *__first);
                     ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/stl_uninitialized.h:150:2: note: in instantiation of function template specialization 'std::__uninitialized_copy<false>::__uninit_copy<__gnu_cxx::__normal_iterator<const TheClass *, std::vector<TheClass, std::allocator<TheClass> > >, TheClass *>' requested here
        __uninit_copy(__first, __last, __result);
        ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/stl_uninitialized.h:325:19: note: in instantiation of function template specialization 'std::uninitialized_copy<__gnu_cxx::__normal_iterator<const TheClass *, std::vector<TheClass, std::allocator<TheClass> > >, TheClass *>' requested here
    { return std::uninitialized_copy(__first, __last, __result); }
                  ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/stl_vector.h:558:9: note: in instantiation of function template specialization 'std::__uninitialized_copy_a<__gnu_cxx::__normal_iterator<const TheClass *, std::vector<TheClass, std::allocator<TheClass> > >, TheClass *, TheClass>' requested here
          std::__uninitialized_copy_a(__x.begin(), __x.end(),
               ^
/cplayground/code.cpp:10:29: note: in instantiation of member function 'std::vector<TheClass, std::allocator<TheClass> >::vector' requested here
  std::vector<TheClass> a = std::move(data);
                            ^
/cplayground/code.cpp:5:3: note: 'TheClass' has been explicitly marked deleted here
  TheClass(const TheClass&) = delete;
  ^
2 errors generated.

mardi 26 avril 2022

Automatic Compare Layout of 2 Structs in C++

2 structs came from different Header-Files. How can I ensure the memory layout of them are binary compatibility? In addition how can I check the naming of them are equal? The checking should be done at compile time.

As an Example:

namespace LibA {
  struct Item {
    uint32_t A;
    uint8_t B;
    uint8_t pad1,pad2,pad3;
  };
}


namespace LibB {
  struct Item {
    uint32_t A;
    uint8_t B;
    uint8_t pad1,pad2,pad3;
  };
}

Ok - in the above Example it's easy to do it the manual way with sizeof(...) and offsetof(...).

But the question is to do it in an automatic way like static_assert(issame(LibA::Item,LibB::Item),"Check")?

C++ Multithreading processes a queue, and the processed results are output to another queue in the order of the original queue

I just started learning about multithreading.I want to design multithreaded module for a problem. I have two queue,there is one thread which is putting messages in the messages queue,and there is many thread to process the messages from the message queue and put the processed messages to the output queue.And there is one thread to output from the output queue.The problem is that the order of the output queue is not same as the messages queue may because the processing threads take different time .Thanks for your help.

#include <thread>
#include <mutex>
#include<queue>
#include <string>
#include<time.h>

using namespace std;
std::mutex mut;
std::queue<int> data_queue; 
std::condition_variable data_cond;
std::queue <int> data_queue2;
std::condition_variable data_cond2;

void process(int& a)
{
    srand((unsigned)time(NULL));
    int b = 10, c = 200;
    int time= (rand() % (c - b)) + b ;
    std::this_thread::sleep_for(std::chrono::milliseconds(time));
    a=2*a;
}
void process2(int a)
{
    cout <<a << endl;

}
void data_preparation_thread()
{
    int i = 0;
    while (i<10)
    {
        int  data = i;
        std::lock_guard<std::mutex> lk(mut);
        data_queue.push(data); 
        data_cond.notify_all(); 
        i++;
    }
}
void data_processing_thread()
{
    while (true)
    {
    std::unique_lock<std::mutex> lk(mut); 
    data_cond.wait(
        lk, [] {return !data_queue.empty(); }); 
    int data = data_queue.front();
    data_queue.pop();
    lk.unlock(); 
    process(data);
    std::lock_guard<std::mutex> lk2(mut);
    data_queue2.push(data);
    data_cond2.notify_one();
    }
}
void data_processing_thread2()
{
    while (true)
    {
       
        std::unique_lock<std::mutex> lk(mut); // 4
        data_cond2.wait(
            lk, [] {return !data_queue2.empty(); }); // 5
        int data = data_queue2.front();                                                            
        data_queue2.pop();
        lk.unlock(); // 6
        process2(data);
    }
}
int main()
{
    thread first(data_preparation_thread);
    thread second(data_processing_thread);
    thread second2(data_processing_thread);
    thread second3(data_processing_thread);
    thread third(data_processing_thread2);
    first.detach();
    second.detach();
    second2.detach();
    second3.detach();
    third.detach();                                             
    while (1) 
    {
        int j = 0;
    }
    return 0;


}

c++ std::atomic concurrency printing

Hello everyone I have a code for threads to print their number and number that they are counting:

void print_num_n_times(std::uintmax_t thread_num, std::uintmax_t num_times_to_print = 100)
{
    static std::atomic_bool is_printing{ false };
    std::uintmax_t i = 0;
    while (i < num_times_to_print)
    {
        //if the thread is not acquired.
        while (is_printing.load());
        //if the thread previous value was false (maybe another thread was intterupting.
        if (!is_printing.exchange(true)) {
            std::cout << "Output from thread " << thread_num << " Value: " << i + 1 << '\n';
            is_printing.exchange(false);
            i++;
        }
    }
}

and this is the only solution I have found for multiple threads to print nicely like this (2 threads count to 5):

Output from thread 2 Value: 1
Output from thread 2 Value: 2
Output from thread 2 Value: 3
Output from thread 2 Value: 4
Output from thread 2 Value: 5
Output from thread 1 Value: 1
Output from thread 1 Value: 2
Output from thread 1 Value: 3
Output from thread 1 Value: 4
Output from thread 1 Value: 5

Is there a better solution, because it's slow and I feel like there could be a better solution. Any help would be appreciated!

How to create a functioning card class to replicate game?

I am creating a game that looks for the best positions to insert a card in a deck of cards. I am using classes for this (OOP) but I am quite confused as to how to create this. This is what I have so far:

An input example would be a deck of cards that look like: 4 8 8 8 6 5 4 5 7 I would, for example, insert 3 at the best position in this game, which in this context would be index 7 because in this context 8 8 8 < 6 5 4 3

How would I start writing my code to demonstrate this?

p.s: It would not be best to place it in the beginning because group of adjacent cards which count by ones either up or down, weigh more in the game (i.e 3456, 5678, 1234). If placed in the beginning it would be "34"888 ... which would be of count two. Why insert at index one with a count of two when it can continue at index 7 and be "6543" a count of four paired cards?

#include <iostream>
#include <vector>
#include <map>
using namespace std;

class Hand
{
    private
        vector<int>cards;
        unsigned currentCard;
      int _hand_size;
      vector<int>_cards;
      int _insert;
   public:
        Hand(int _hand_size, vector<int>cards, int insert)
      {
          _hand_size = hand_size;
          _cards = cards;
          _insert = insert;
      }
      vector<int> get_hand()
      {
         return _cards;
      }
};

//Controls execution of program.
int main()
{
   std::string num_str = "";
   std::cin >> num_str;
   size_t hand_size = 0;
   std::cin >> hand_size;
   std::string deg_str = "";
   std::cin >> deg_str;
   vector<int> cards(hand_size);
   for (size_t index = 0; index < hand_size; index++)
   {
      std::cin >> cards[index];
   }
   for (size_t index = 0; index < hand_size; index++)
   {
   }
   std::string insert_size = "";
   std::cin >> insert_size;
   size_t insert = 0;
   std::cin >> insert;
}

lundi 25 avril 2022

Issues with declaring enum

I'm getting an error when trying to declare an enum. It says the identifier is undefined, but I am including the applicable file where it was defined. (This is my first coding class so sorry in advance). Where am I going wrong? And how do I pass the enum to a constructor?

// in degree.h file

#ifndef Student_h
#define Student_h

#pragma once

enum class DegreeProgram { program1, program2, program3 };

#endif


// in student.h file

#ifndef Student_h
#define Student_h

#pragma once

#include "degree.h"

class Student {

private:
   DegreeProgram program;
};

#endif

Multiplying two big numbers represented as vectors C++ [closed]

I've created two vectors, in which we can generate as long integers as we want. I've already found a way to add and subtract them but I don't have a clue how to multiply them, for example:

vector<int>vec1{2,3,4,5,6,7,8,9,3,2,1,5}, vec2{1,2,3,4};             
vecotr<int>result{};'

I know that I should use long multiplication but I don't know how to start. The result should be: 289456780227310.

xcode : undefined symbols when including headers

I recently started a project using swift and c++. So I installed Xcode and started using it. I first encountered some bugs, but fixed theme.

However, I still got some Undefined symbols for architecture x86_64:

I searched online and I can't find the solution for my problem (otherwise I would not have asked the question).

This is the whole error :

  "parser(std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > >, Node*, int, int)", referenced from:
      utilise_file(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool, bool, bool, bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >) in main.o
  "recognize_paternes(Node*, bool)", referenced from:
      utilise_file(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool, bool, bool, bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >) in main.o
  "ast_t_rep(Node*, int)", referenced from:
      utilise_file(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool, bool, bool, bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >) in main.o
  "lex(char const*, std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > >&)", referenced from:
      utilise_file(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool, bool, bool, bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >) in main.o
  "visitor(std::__1::vector<Node*, std::__1::allocator<Node*> >, bool, bool, bool)", referenced from:
      utilise_file(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool, bool, bool, bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >) in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

But I think we can just consider :

      utilise_file(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool, bool, bool, bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >) in main.o

as this error seems to be redundant.

In my main.cpp file, I imported the header file (parser.h) where I declared Node *parser(vector<string>, Node *, int, int);.

In main.cpp>utilise_file(...), I call the function parser:

void utilise_file(){
    ...
    vector<string> code_ref = vector<string>();
    vector<string> lexeme = lex(source.c_str(), code_ref);
    Node *ast_t = new Node();
    ast_t->value = "main";
    ast_t->type = "root";
    Node *p = parser(lexeme, ast_t, 0, int(lexeme.size()));
   ...
}

So normally, I would not get this error.

It seems to me that it is a 'type' sort of problem, but I can't figure what.

I searched online for solutions, and I tried adding -Xlinker in Xcode>Linking>Other Liner Flags, but it didn't helped.

I also thought of adding the flags linking to the header in the compiling command line, but I think Xcode does that automatically. (Or not because many of my headers are not recognized in the file arborescence...)

Thank you for your help ;)

Refactoring : delegate friendship in sub-functions

I refactor a code where a class has a friend function doing a lot of stuff.

class Foo
{
  friend void do_something(Foo& foo);
};

void do_something(Foo& foo)
{
  // More than 2000 lines of ugly code
}

I would like to split the content of do_something in several small functions. Something looking like this :

void do_something(Foo& foo)
{
  if(case_1) do_1(foo);
  else if(case_2) do_2(foo);
  else if(case_3) do_3(foo);
  //...
}

Is there a design where I can transfert the friendship to the sub-fuctions do_x(Foo&) without having to declare them in the class, or something similar in order to split the code ?

Note : C++11 only

Note : I don't want to write the sub-functions as maccros

How to iterate over boost graph and hide not connected vertex?

The following figure shows bi-directional graph. I have represented following graph using boost-graph. In boost-graph every edge is also considered as vertex. So L1,L2 and L3 are also vertices.
Graph

Now I want to hide vertex v1. So all the edges connected to v1 must be hide. So L1 and L2 vertices will be hidden. Now L1 is attached to V2 and V2 does not have any further attachement so V2 must be hidden. But V3 will not be hidden as it has connection with L3.

So hidden will be V1, V2, L1 and L2

For that I have traversed through boost-graph. But I was able to hide only V1 , L1 and L2. But not V2.
How to find neighbour of L1 ?

If V2 had line L4 connected, then that must be hide.
Again if L4 had V5 connected then that also be hide. Then it will create chain of removable vertices. So how to deal with this ?

Here is my code:
(vertex -> V1) and (graph -> boost graph )

 //Finding out edges of vertex
    boost::graph_traits<BGType>::out_edge_iterator ei, ei_end;
    boost::tie(ei, ei_end) = out_edges( vertex, graph ); 
    for( boost::tie(ei, ei_end) = out_edges(vertex, graph); ei != ei_end; ++ei)
    {
        auto target = boost::target ( *ei, graph );
        graph[target]._isVisible = false;
    }

    //Finding in edges of vertex
    boost::graph_traits<BGType>::in_edge_iterator ein, ein_end;
    boost::tie(ein, ein_end) = in_edges( vertex, graph ); 
    for( boost::tie(ein, ein_end) = in_edges(vertex, graph); ein != ein_end; ++ein)
    {
        auto source = boost::source ( *ein, graph ); 
        graph[source]._isVisible = false;
    }

C++ Constructor behaving strangely in my Linkedlist program

Today I was taught Linked list in class and I wanted to implement it on my own.

Here's the part of the code that I wrote. Note that traverseLL traverses the Linked list and insertAtEnd inserts a new node at the end of the linked list.

I believe I can implement Linked list logic / methods / functions on my own. But my question is, inside insertAtEnd function when I create a newNode with the parameters - my data to be inserted, and nullptr (because inserting at the end), It inserts garbage values (or memory addresses maybe) in my node, ignoring the data passed to the constructor.

using namespace std;
#define NL '\n'

class Node {
    public:
        int data;
        Node* next;

    Node (int data, Node* nextPtr=nullptr) {
        data = data;
        next = nextPtr;
    }
};


void insertAtEnd(Node* &head, int data) {

    Node* newNode = new Node(data, nullptr);  // <---- Issue in this line
    // When I do as above, my linkedlist nodes always store garbage values and not the data being passed.

    // However, when I un-comment the below line, I get the correct output.
    // newNode->data = data;

    if (head == nullptr)
        head = newNode;
    
    else {
        Node* temp = head;

        while (temp->next != nullptr)
            temp = temp->next;

        temp->next = newNode;
    }
}


void traverseLL(Node* head) {
    if (head == nullptr)
        return;

    while (head->next) {
        cout << head->data << " -> ";
        head = head->next;
    }
    cout << head->data << NL;
}




int main() {

    Node* head = nullptr;

    insertAtEnd(head, 10);
    insertAtEnd(head, 20);
    insertAtEnd(head, 30);
    
    traverseLL(head);

    return 0;
}

For example, the output for the above code when keeping newNode->data = data line commented, is :

16259544 -> 16258392 -> 16258392

But when I un-comment that line, my output becomes, which is intended:

10 -> 20 -> 30

Why is this happening? Even though I've defined my constructor, why is it not working?

Class diagram for variable member with the type of `std::shared_ptr

class Foo{};

class Demo
{
public:
    std::shared_ptr<Foo> foo_ptr{new Foo()};;
};

What's the relationship between Foo and Demo? I think it is an aggregation. Am I right? How to draw such the relationship between them?

dimanche 24 avril 2022

using acquire memory barrier for std::atomic::exchange

There are spinlock implementations that use memory_order_acquire for std::atomic<T>::exchange. A release barrier is used for the unlock while an acquire is used for locking. Given that exchange is a read + modify + write operation, I'm trying to understand why that is valid as opposed to using memory_order_acqrel?

polling C++ atomics for thread synchronization

I would like to understand if the following way of thread sync using atomics is defined behavior, i.e. does the usage of atomic guarantee that a cached version of the atomic variable will not be used instead ? If it is defined behavior is the usage of std::memory_order::relaxed okay or does one need to use acquire/release barriers instead?

#include <thread>
#include <atomic>
#include <iostream>

std::atomic<bool> flag {false};

int main()  
{    
    std::thread t1([]() {
        while (!flag.load()) {            
        }
    }); 
    flag.store(true, std::memory_order_relaxed);
    t1.join();
    std::cout << "Done\n";
}

Cleanly exit Boost thread member of class

I have a class that has a boost::thread member variable. I have a private member function that is run in that thread (see code below).

class Human
{
  public:
    Human()
        : m_thinkThread(&Human::think, this)
    { }

    ~Human()
    {
        m_thinkThread.interrupt();
        m_thinkThread.join();
    }

  private:
    void think()
    {
        // do some thinking...
    }

    boost::thread m_thinkThread;
};
  1. Do I need the interrupt and join calls and therefore the custom destructor? Or will the default destructor take care of exiting cleanly? If the default destructor is all I need, then what does it do "under the hood" to ensure the thread is exited cleanly?
  2. If I do however, need the interrupt and join calls, then my current setup has a bug because join() can throw, which will be an uncaught exception in a destructor. How would I handle this case?

Thank you

Making a static map with pair as a key [duplicate]

Trying to solve a leetcode problem. Here's the link. In the problem I am trying to make a static map with pair as a key.

As I removed the static keyword, the code is working perfectly fine.

But in case of static keyword, Getting a weird error message like.

In file included from prog_joined.cpp:1:
In file included from ./precompiled/headers.h:34:
In file included from /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/algorithm:71:
In file included from /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/pstl/glue_algorithm_defs.h:13:
In file included from /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/functional:61:
In file included from /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/unordered_map:46:
In file included from /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/hashtable.h:35:
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/hashtable_policy.h:1382:2: error: static_assert failed due to requirement 'std::__is_invocable<const std::hash<std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>>> &, const std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>> &>{}' "hash function must be invocable with an argument of key type"
        static_assert(__is_invocable<const _H1&, const _Key&>{},
        ^             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/hashtable.h:1417:34: note: in instantiation of member function 'std::__detail::_Hash_code_base<std::pair<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char>>, std::pair<const std::pair<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char>>, std::pair<int, int>>, std::__detail::_Select1st, std::hash<std::pair<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char>>>, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_hash, true>::_M_hash_code' requested here
      __hash_code __code = this->_M_hash_code(__k);
                                 ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/unordered_map.h:921:21: note: in instantiation of member function 'std::_Hashtable<std::pair<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char>>, std::pair<const std::pair<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char>>, std::pair<int, int>>, std::allocator<std::pair<const std::pair<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char>>, std::pair<int, int>>>, std::__detail::_Select1st, std::equal_to<std::pair<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char>>>, std::hash<std::pair<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char>>>, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_hash, std::__detail::_Prime_rehash_policy, std::__detail::_Hashtable_traits<true, false, true>>::find' requested here
      { return _M_h.find(__x); }
                    ^
Line 18: Char 19: note: in instantiation of member function 'std::unordered_map<std::pair<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char>>, std::pair<int, int>, std::hash<std::pair<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char>>>, std::equal_to<std::pair<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char>>>, std::allocator<std::pair<const std::pair<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char>>, std::pair<int, int>>>>::find' requested here
        if(st_end.find({id_stat[id].first,stationName})!=st_end.end()){
                  ^

MySolution :

class UndergroundSystem {
public:
    //   checkIn   map<id,pair<stationName,time>>
    static map<int,pair<string,int>> id_stat;
    
    //   map<pair<startingSt,endingSt>,pair<totalTime,count>>
    static map<pair<string,string>,pair<int,int>> st_end;
    UndergroundSystem() {
        
    }
    
    void checkIn(int id, string stationName, int t) {
        id_stat[id] = {stationName,t};
        
    }
    
    void checkOut(int id, string stationName, int t) {
        if(st_end.find({id_stat[id].first,stationName})!=st_end.end()){
            pair<int,int> s = st_end[{id_stat[id].first,stationName}];
            st_end[{id_stat[id].first,stationName}] = {s.first+ t-id_stat[id].second,s.second+1};
        }else{
            st_end[{id_stat[id].first,stationName}] = {t-id_stat[id].second,1};
        }
        
    }
    
    double getAverageTime(string startStation, string endStation) {
        return (double)st_end[{startStation,endStation}].first/st_end[{startStation,endStation}].second;
    }
};

/**
 * Your UndergroundSystem object will be instantiated and called as such:
 * UndergroundSystem* obj = new UndergroundSystem();
 * obj->checkIn(id,stationName,t);
 * obj->checkOut(id,stationName,t);
 * double param_3 = obj->getAverageTime(startStation,endStation);
 */

Can anybody please explain what is actually going on?

Decreasing Latency of playing sound using Playsound in C++ (windows)

Currently, we are playing 5 sounds one after another using Wave output and Fetching from the TCP socket. We are now using playBuffer to play the sounds. But there is a latency of playing one sound from another sound to. I don't want any latency in between playing the 5 audio and want to be played immediately. Is there any way to do that in playsound, or can I achieve that using any other library in C++ ? I am currently using a windows system. Would really appreciate some help, Seaching for hours for a solution.

// AudioTask.cpp : Defines the entry point for the console application. // Adapted from http://www.cplusplus.com/forum/beginner/88542/

#include "stdafx.h"




#define _WIN32_WINNT 0x0500
#include <windows.h>
#include <mmsystem.h>
#include <iostream>
#include <fstream>
#include <conio.h>
#include <math.h> 
#include <stdint.h>

#define PI 3.14159265


using namespace std;

typedef struct WAV_HEADER1 {
    uint8_t RIFF[4]; // = { 'R', 'I', 'F', 'F' };
    uint32_t ChunkSize;
    uint8_t WAVE[4]; // = { 'W', 'A', 'V', 'E' };
    uint8_t fmt[4]; // = { 'f', 'm', 't', ' ' };
    uint32_t Subchunk1Size = 16;
    uint16_t AudioFormat = 1;
    uint16_t NumOfChan = 1;
    uint32_t SamplesPerSec = 16000;
    uint32_t bytesPerSec = 16000 * 2;
    uint16_t blockAlign = 2;
    uint16_t bitsPerSample = 16;
    uint8_t Subchunk2ID[4]; // = { 'd', 'a', 't', 'a' };
    uint32_t Subchunk2Size;
} wav_hdr1;




void playBuffer(short* audioSamplesData1, short* audioSamplesData2, int count)
{
    static_assert(sizeof(wav_hdr1) == 44, "");

    wav_hdr1 wav;
    wav.NumOfChan = 2;
    wav.SamplesPerSec = 44100;
    wav.bytesPerSec = 176400;
    wav.blockAlign = 4;
    wav.bitsPerSample = 16;

    // Fixed values
    wav.RIFF[0] = 'R';
    wav.RIFF[1] = 'I';
    wav.RIFF[2] = 'F';
    wav.RIFF[3] = 'F';
    wav.WAVE[0] = 'W';
    wav.WAVE[1] = 'A';
    wav.WAVE[2] = 'V';
    wav.WAVE[3] = 'E';
    wav.fmt[0] = 'f';
    wav.fmt[1] = 'm';
    wav.fmt[2] = 't';
    wav.fmt[3] = ' ';
    wav.Subchunk2ID[0] = 'd';
    wav.Subchunk2ID[1] = 'a';
    wav.Subchunk2ID[2] = 't';
    wav.Subchunk2ID[3] = 'a';


    wav.ChunkSize = (count * 2 * 2) + sizeof(wav_hdr1) - 8;
    wav.Subchunk2Size = wav.ChunkSize - 20;

    char* data = new char[44 + (count * 2 * 2)];

    memcpy(data, &wav, sizeof(wav));
    int index = sizeof(wav);

    //constexpr double max_amplitude = 32766;

    for (int i = 0; i < count; i++)
    {
        short value = audioSamplesData1 ? audioSamplesData1[i] : 0;
        memcpy(data + index, &value, sizeof(short));
        index += sizeof(short);

        value = audioSamplesData2 ? audioSamplesData2[i] : 0;
        memcpy(data + index, &value, sizeof(short));
        index += sizeof(short);
    }
    PlaySound((char*)data, GetModuleHandle(0), SND_MEMORY | SND_SYNC);
}

void performAction(short audioSamplesData1[], short audioSamplesData2[], int count)
{
    playBuffer(audioSamplesData1, audioSamplesData1, count);
    playBuffer(audioSamplesData2, audioSamplesData2, count);
    playBuffer(audioSamplesData1, NULL, count);
    playBuffer(NULL, audioSamplesData2, count);
    playBuffer(audioSamplesData1, audioSamplesData2, count);
}


class Wave {

public:
    Wave(char * filename);
    ~Wave();
    void play(bool async = true);
    bool isok();

private:
    char * buffer;
    bool ok;
    HINSTANCE HInstance;
    int numberOfAudioBytes;
};

Wave::Wave(char * filename)
{
    ok = false;
    buffer = 0;
    HInstance = GetModuleHandle(0);
    numberOfAudioBytes = 0;

    ifstream infile(filename, ios::binary);

    if (!infile)
    {
        std::cout << "Wave::file error: " << filename << std::endl;
        return;
    }

    infile.seekg(0, ios::end);   // get length of file
    int length = infile.tellg();
    buffer = new char[length];    // allocate memory
    infile.seekg(0, ios::beg);   // position to start of file
    infile.read(buffer, length);  // read entire file

    std::cout << "Number of elements in buffer : " << length << std::endl;
    numberOfAudioBytes = length;

    infile.close();
    ok = true;
}

Wave::~Wave()
{
    PlaySound(NULL, 0, 0); // STOP ANY PLAYING SOUND
    delete[] buffer;      // before deleting buffer.
}

void Wave::play(bool async)
{
    if (!ok)
        return;


    // Create two arrays of sound data to use as a test for performing the task we need to do.
    const int SAMPLE_RATE = 44100; // 44.1 kHz
    const int FILE_LENGTH_IN_SECONDS = 3;
    const int NUMBER_OF_SAMPLES = SAMPLE_RATE*FILE_LENGTH_IN_SECONDS; // Number of elements of audio data in the array, 132300 in this case.

    std::cout << "NUMBER_OF_SAMPLES : " << NUMBER_OF_SAMPLES << std::endl;

    short audioSamplesData_A[NUMBER_OF_SAMPLES];
    short audioSamplesData_B[NUMBER_OF_SAMPLES];
    float maxVolume = 32767.0; // 2^15 - 10.0
    float frequencyHz_A = 500.0;
    float frequencyHz_B = 250.0;

    for (int i = 0; i < NUMBER_OF_SAMPLES; i++)
    {
        float pcmValue_A = sin(i*frequencyHz_A / SAMPLE_RATE * PI * 2);
        float pcmValue_B = sin(i*frequencyHz_B / SAMPLE_RATE * PI * 2);

        short pcmValueShort_A = (short)(maxVolume * pcmValue_A);
        short pcmValueShort_B = (short)(maxVolume * pcmValue_B);
        //short pcmValueShort_B = (short)(0.5*maxVolume*(pcmValue_A + pcmValue_B));

        audioSamplesData_A[i] = pcmValueShort_A; // This is what you need to play.
        audioSamplesData_B[i] = pcmValueShort_B; // This is what you need to play.

        // waveData += pack('h', pcmValueShort_A) - Python code from Python equivalent program, perhaps we need something similar.
        // See enclosed "Py Mono Stereo.py" file or visit https://swharden.com/blog/2011-07-08-create-mono-and-stereo-wave-files-with-python/
    }

    // The task that needs to be done for this project:
    // The audio data is available in the form of an array of shorts (audioSamplesData_A and audioSamplesData_B created above).
    // What needs to happen is this audio data (audioSamplesData_A and audioSamplesData_B) must each be played so we can hear them.
    // When this task is over, there will be no need for any WAV file anywhere, the goal is NOT to produce a WAV file. The goal is 
    // to take the audio data in the form of audioSamplesData_A and play it from memory somehow.
    // We need to take the input data (audioSamplesData_A and audioSamplesData_B) and play the same sounds that the 5 WAV files are currently playing, but
    // in the end, we will no longer need those WAV files.

    // You do NOT need to create any new files.
    // In the end, you do not need to read any files either.
    // In the final project, all you will need is this current main.cpp file. You run main.cpp and you hear the 5 sounds.
    // The 5 sounds, are created BY C++ here in this file (see loop above). 
    
    // Display the first 100 elements for one of the audio samples array
    for (int i = 0; i < 100; i++)
    {
        //std::cout << "i = " << i << ", audioSamplesData_B[i] : " << audioSamplesData_B[i] << std::endl;
    }

    // Display the first 100 elements for the serialized buffer of WAV header data + some audio data, all coming from one of the WAV files on the disk.
    for (int i = 0; i < 100; i++) // Last 6 elements is where audio data begins. First 44 elements are WAV header data.
    {
        //std::cout << "i = " << i << ", buffer[i] : " << (int) buffer[i] << std::endl;
    }
    performAction(audioSamplesData_A, audioSamplesData_B, NUMBER_OF_SAMPLES);

    // Play the sample sound, the one obtained from the WAV file on the disk, not the one created from the audio samples created above.
    //PlaySound((char*)(&audioSamplesData_A[0]), HInstance, SND_MEMORY | SND_SYNC);
    //PlaySound((char*)audioSamplesData_B, HInstance, SND_MEMORY | SND_SYNC);
    //PlaySound((char*)audioSamplesData_AB, HInstance, SND_MEMORY | SND_SYNC);
    //PlaySound((char*)buffer, HInstance, SND_MEMORY | SND_SYNC);
}
bool Wave::isok()
{
    return ok;
}
 

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

    std::cout << "Trying to play sound ...\n";

    // Load the WAV files from them from the disk. These files are here only to help you understand what we need. In the end, we will no longer need them.
    Wave outputA("outputA.WAV"); // Audio file equivalent to audioSamplesData_A curve generated in the loop above.
    Wave outputB("outputB.WAV"); // Audio file equivalent to audioSamplesData_B curve generated in the loop above.
    Wave outputALeftOnly("outputALeftOnly.WAV"); // Audio file that plays sound A on the left only, must be able to take audioSamplesData_A and somehow make it left only.
    Wave outputBRightOnly("outputBRightOnly.WAV"); // Audio file that plays sound B on the right only, must be able to take audioSamplesData_B and somehow make it right only.
    Wave outputALeftOutputBRight("outputALeftOutputBRight.WAV"); // Must be able to take both audioSamplesData_A and audioSamplesData_B and make it play different sounds in left and right.

    // Play the WAV files from the disk, either all of them or a subset of them.
    outputA.play(0);
    //outputB.play(0);
    //outputALeftOnly.play(0);
    //outputBRightOnly.play(0);
    //outputALeftOutputBRight.play(0);

    std::cout << "press key to exit";

    while (1) {} // Loop to prevent command line terminal from closing automatically.
    return 0;
}

vendredi 22 avril 2022

VS 2019 remote debugging can't "see" my symbols (C++)

Sorry if this is a duplicate -- I've looked at this and this and others, but I can't find my problem.

A program I build debugs successfully on my local machine, but when I try to debug it remotely, I can't set breakpoints in my code. I've opened the modules window in the debugger, and under Symbol Status for my executable, it tells me "Cannot find or open the PDB file." I try to load it manually, and get the error, "A matching symbol file was not found in this folder."

I created a minimal (hello world) app, and I can debug that, so I'm able to reach the remote PC. Indeed, the app does start up and run on the remote system. So, it isn't an access issue.

Not sure what else to say about this, other than to show you my project debugging configuration: enter image description here

Any ideas are MOST welcome. Thanks...

C++ compiler versions

Sorry, I'm kind of venting here but it seems I also need to gain some knowledge on compiling versions.

So I have a c++ program (c++ version 11) that compiles normally on my working machine with the command: g++ program.cpp

However, on a different machine it does not compile without specifying the compiler version to c++ 11 using the command: g++ program.cpp -std=c++11

Why do I need to specify the compiler version on a different machine? Why does my working computer allow it to be compiled simply with g++ program.cpp and not the same elsewhere?

I'm asking because I recently turned in an assignment that received a zero because it did not compile.

I left instructions to compile as follows:

Compiler: C++11

Command to compile: g++ program.cpp

Once compiled and ran, the program will prompt you to pick which heuristic you would like to use.

Next the program will prompt you to enter each puzzle piece followed by the enter key.   

I specified the compiler version but I did not include extra -std=c++11 command to specify the version. Assuming the proffesor would be compile the program using the c++ version as stated in the first line of the instructions.

Am I in the wrong here?

Create an object of nested class in templated class

I am struggling with this, and would appreciate some help!

I have the following code:

#include <iostream>

enum Enum{A, B, C};

template<class T>
class classA
{
    public:

    template<Enum E = A>
    class innerClassA
    {
        public:
        innerClassA() {}
    };
};

template<class T>
class classB
{
    public:
    classB(){}

    template<Enum E = A>
    void foo() 
    {
        // using innerClassA= typename classA<T>::template innerClassA;
        // innerClassA <T, S> mult; // Not working
        typename classA<T>::innerClassA myInnerClassA; // Not working
    }
};

int main(int argc, char** argv)
{
    classB<int> obj2;
    obj2.foo();

   return 0;
}

I would like to create an object of innerClassA inside the function foo. But unfortunately, I am not able to do it. Can someone give me a hand?

Best wishes !

jeudi 21 avril 2022

create json object for vector

I want to convert a vector<bool> vec = {true, false,true} to json object using nlohman json lib to send through restapi.

I expect the converted json object in the form

{
  "data" : [true, false, true]
}

TimeStamp::getTimeZoneOffset returns the same offset for STD and DST?

I'm getting the time zone offset of a TIMESTAMP column using oracle::occi::Timestamp::getTimeZoneOffset method, but got the same results when retrieving a timestamp value in summer time (2020-09-30) than when retrieving other value which is in standard time (2020-03-01).

The environment is as follow:

  • Oracle XE 11G R2

  • Time Zone = Europe/Madrid (UTC offset: STD=+01:00; DST=+02:00)

  • Temp table with one row and two columns:

    CREATE TABLE TEST_TZ_OFFSET
    AS 
    SELECT TIMESTAMP '2020-09-30 00:00:00.000000' AS DST,
           TIMESTAMP '2020-03-01 00:00:00.000000' AS STD
    FROM DUAL
    
  • Oracle Instant Client for Linux x86-64 Version 12.2.0.1.0

When the column in DST is fetched it works as expected (7200 seconds = +02:00), but when STD column is fetched it has the same offset as in DST when it is suppose to be 3600 seconds (+01:00)

long getGMTOffset(oracle::occi::Connection *conn, const std::string &columnName) {
    oracle::occi::Timestamp timestamp;
    oracle::occi::Statement *stmt;
    int tzhour = 0, tzminute = 0;

    try {
        std::string query = "SELECT " + columnName + " FROM TEST_TZ_OFFSET";
        stmt = conn->createStatement();
        stmt->setSQL(query);
        oracle::occi::ResultSet *rs = stmt->executeQuery();

        if (rs->next()) {
            timestamp = rs->getTimestamp(1);
        }
        
        stmt->closeResultSet(rs);
        conn->terminateStatement(stmt);
    } catch (const std::exception &e) {
        std::cerr << e.what() << "\n";
        conn->terminateStatement(stmt);
    }

    timestamp.getTimeZoneOffset(tzhour, tzminute);
    return (tzhour * 60 + tzminute) * 60;
}

std::cout << "GMT Offset of STD column = " << getGMTOffset(connection, "STD") << "\n";
std::cout << "GMT Offset of DST column = " << getGMTOffset(connection, "DST") << "\n";

Output:

GMT Offset of STD column = 7200
GMT Offset of DST column = 7200

Is this the expected behaviour?

c++17 memory access of memory owned by c++11 library

I have a program compiled with -std=c++17 and it links against a library that uses -std=c++11. There is a class with a buffer (char *) inside the c++11 that I want to use. The c++11 library made the buffer public for whatever reason. When I look at this buffer from my class in the c++17 program, the buffer is pointing 4 bytes too far. So I am missing 4 bytes. If I step into the class from the c++11 library and I look at the buffer it looks fine. I want to know if this is a known thing between c++17 as i don't normally mix and match c++ versions.

Here is what I see in gdb when stepping through the code below.

(gdb) p &bufClass.buf
$11 = (unsigned char (*)[4194304]) 0x7fffffbf9efc
(then ill step into the print())
(gdb) p &buf
$12 = (unsigned char (*)[4194304]) 0x7fffffbf9ef8

Here is a rough idea of what it looks like:

#include "theirlib.h"
class MyClass
{
public:
void inspectbuff()
{
std::cout.write(bufClass.buf, 8); //"OYOU\0\0\0\0"
bufClass.print(std::cout); //this is a function implemeted in that lib and buf-> "HELLOYOU"
}

private:
theirlib::theirclass bufClass;
};

How to check a type has constexpr constructor

To achieve what the title says, I try this:

template<typename _t, _t = _t()>
constexpr bool f()
{
    return true;
}
template<typename _t>
constexpr bool f()
{
    return false;
}

It works well for types haven't constexpr constructor. But for other types it causes a compile error with ambiguous overloads.

so how can I check?

std::is_trivially_copyable is too strong, what shall I use instead?

I want to accept classes which are "trivially copyable", in the sense that if I mem-copy the byte representation of one variable of the type into another, it will be usable, and nothing will have been broken in any way.

Looking at std::is_trivially_copyable, I see the requirements are:

Trivially copyable classes, i.e. classes satisfying following requirements:

  • At least one copy constructor, move constructor, copy assignment operator, or move assignment operator is eligible
  • Every eligible copy constructor (if any) is trivial
  • Every eligible move constructor (if any) is trivial
  • Every eligible copy assignment operator (if any) is trivial
  • Every eligible move assignment operator (if any) is trivial
  • Has a trivial non-deleted destructor

First and last requirement - check. But the other requirements are super-strong and not what I want! I'd be willing to "compromise" on having a trivial (=defaulted) copy ctor as a requirement, and that's already quite different than what I really want.

So, what type trait can I use from the standard library, or write myself, to express the constraint I'm interested in?

I'm writing C++11 right now, so if your answer requires a later standard - write it, but mention that fact explicitly.

mercredi 20 avril 2022

How to insert to std::map which is in std::multimap?

How can I insert another map into the map?

In the code, I try to copy the map from another.

multimap<string, map<size_t, size_t>> sorted;

for (auto itr = m_Items.begin(); itr != m_Items.end(); ++itr)
    sorted.emplace(itr->first
        , make_pair(itr->second.m_Date.m_Time, itr->second.m_Cnt)
    );

Is it a data-race when several thread *read* the same memory at the same time?

cppreference.com says:

Threads and data races

When an evaluation of an expression writes to a memory location and another evaluation reads or modifies the same memory location, the expressions are said to conflict. A program that has two conflicting evaluations has a data race unless...

This speaks about the scenario of 'thread1-write thread2-read' (W-R) and about the scenario of 'thread1-write thread2-write' (W-W).

What about 'thread1-read thread2-read' (R-R)?

mardi 19 avril 2022

Can anybody provide a MISRA C++ compliant 'offsetof' macro/template/function that works with static_assert?

I'm trying to write defensive code and put static_assert<> to ensure a structure's member has a specific offset to satisfy some hardware requirements

MISRA C++ Rule 18-2-1 says "The macro offsetof shall not be used", so we've 'undef'd offsetof.

We've provided some template things, but they all fail when used in static_assert<>

I've been unable to find something that works with C++11 static_assert<> across compilers.

struct Commands
{
    uint32_t command[4];
};

struct DMA_Bundle
{
    struct header_
    {
        uint32_t num_of_elems;
        uint8_t reserved[60];
    } header;
    Commands array[16];
};

I'm trying to assure that array is 64 bytes from the beginning.

static_assert(offsetof(DMA_Bundle,array)==64,"zoinks");

Does works, but MISRA says but I can't use that. (and I can't argue with our functional safety people :/)

I've tried the following, and generally they don't work:

static_assert(offsetofarray()==64,"bar");
static_assert(myoffsetof(DMA_Bundle::array)==64,"double_zoinks");

The explicit offsetofarray() constexpr function does work under GCC 7.5.0, but it fails under later GCC and Clang (which is what our embedded processor tools use). It fails with 'non constant condition for static_assert'.

The other seems to complain of "invalid use of non-static data member 'DMA_Bundle::array'"

And, for what it's worth, I'm limited to C++11.

How to initialize a pointer to an array in a class constructor?

I have this code

template <class ItemType>
class ArrTest {
public:
    ArrTest();
private:
    ItemType* info;
};

template <class ItemType>
ArrTest<ItemType>::ArrTest()
{
    info = ItemType[50];
}

int main() {
    ArrTest<int> ar();
    return 0;
}

Right now when I try and build this I get

../src/test1.cpp:23:9: error: 'ItemType' does not refer to a value
        info = ItemType[50];

I don't understand how to initialize this into pointer. I believe its a pointer to the first item in the array. but then I should also be able to do info[3] for the 4th member of the array for instance.

while(true) condition only works for once correctly and terminates [closed]

Hi I was doing my homework and needed write while loop creating same type of object with passing different instance. Here is my code

while(true){
        ComputerSystem * compSystem = new ComputerSystem (computerNumber, &allReq, allReq.getSize(), averageTimeHolder, resultText);
        computerNumber++;
    }

in this code block code just did not do anything and terminates without any problem. On the other hand the code below worked perfectly fine.

        ComputerSystem  compSystem(3, &allReq, allReq.getSize(), averageTimeHolder, resultText);

Which I did not understand. One more interesting thing that the code block

 while(true){
    ComputerSystem  compSystem(computerNumber, &allReq, allReq.getSize(), averageTimeHolder, resultText);
}

only works for one time and terminates. I thought that it is about constructor so here is my constructor

ComputerSystem::ComputerSystem(int computerNumber, AllRequests * allRequest, int requestSize, double * averageTimeHolder, string  * result) {
    averageTime = 0;
    resultString = "";
    systemTime = 1;
    this->allRequests = allRequest;
    this->computerNumber = computerNumber;
    this->requestSize = requestSize;
    createComputers();
    reqPRQ = new RequestPRQ(requestSize);

    cout << "Start is reached" << endl;
    start();
    *averageTimeHolder = double (averageTime  / requestSize);
    *result = resultString;

}

Why the while loop either do not work or only executes for one time?

gmock template class 'const T1': actual parameter with requested alignment of 64 won't be aligned

I am trying to gmock the following template class

template <typename Type>
class Interface {
  public:
    virtual bool insert(const Type& param);

}

by using gmock as follows

template <typename Type>

class CMockInterface: public Interface<Type> {

MOCK_METHOD1_T(insert, bool(const Type&));

}

when building I get the following errors

error C2718: 'const T1': actual parameter with requested alignment of 64 won't be aligned

note: see reference to class template instantiation 'testing::internal::ImplicitlyConvertible<const T &,testing::internal::BiggestInt>' being compiled

what is this error?

lundi 18 avril 2022

fatal error: "/stdio.h: Invalid argument ,how to solve this problem?

This problem is encountered when using vscode and dev-cpp, dev-cpp can be solved by moving the code and MinGW from C disk to D disk, if I want to use vscode how to solve it

How to understand the `callable` in the right way?

As per the document, which says:

A Callable type is a type for which the INVOKE operation (used by, e.g., std::function, std::bind, and std::thread::thread) is applicable. This operation may be performed explicitly using the library function std::invoke. (since C++17)

Requirements

The type T satisfies Callable if Given f, an object of type T ArgTypes, suitable list of argument types R,

expressions must be valid:

std::declval()...) the expression is well-formed in unevaluated contextExpression Requirements INVOKE(f,suitable return type The following

Question 1:

If I understand correctly, given void foo(int) {}, std::function(foo) is not callable, whereas std::function(foo, 1) is callable. Am I right?

Question 2: What confuses me is the statement below.

As per the document, which says[emphasis mine]:

The class template std::packaged_task wraps any Callable target (function, lambda expression, bind expression, or another function object) so that it can be invoked asynchronously. Its return value or exception thrown is stored in a shared state which can be accessed through std::future objects.

As you see that the class template std::packaged_task wraps any Callable target, and std::function{foo} is not callable, but std::packged_task<void(int)> task{f}; compiles.

Why `std::thread()` and `std::packaged_task()` works different, although they both accept callable targets?

Here is a simple code snippet:

#include <thread>
#include <future>
#include <functional>

void foo(int){}

int main()
{
    std::thread(foo, 1).join();                  //works indeed
    std::packaged_task<void(int)> task{foo, 1};  //complian
    std::packaged_task<void(int)> task{std::bind(foo, 1)};
}

Both std::thread() and std::packaged_task() accept callable targets, why the code for std::packaged_task() is a little different? Why does not make the std::packged_task() works like std::thread()(i.e. accepts arguments like std::thread)?

The class template std::packaged_task wraps any Callable target (function, lambda expression, bind expression, or another function object) so that it can be invoked asynchronously. Its return value or exception thrown is stored in a shared state which can be accessed through std::future objects.

C++ - Nested for loop optimizations

Problem

I have some code that I need to optimize for work. Given two datasets, I need to compare every element in one dataset with every element in another. The elements in the datasets are string vectors. that look like this: {"AB", "BB", "AB", "AA", "AB", ...}, where there are 3 possible values: AB, BB, and AA. So for example, one dataset would be something like:

AB AA BB BB AA AB
AB AA AA AA BB AB
AA AA AB BB BB BB

while the other dataset might be

BB AB AB AA AB AB
AA AA BB BB BB BB

Note: The vector length will be the same within and between datasets. In this case, it's length 6.

So the first data set contains three vectors, and the second dataset contains two for a total of 6 comparisons

This example contained 3 vs 2 vectors. My real problem will have something like 1.3M vs 6,000

Reproducible Example

The following code will create the vectors to the datasets to the desired sizes similar to how they'll show up in my real code. The first part of the main function simply generates the datasets. This part doesn't need to be optimized because these will be read in from a file. I'm generating them here for the sake of this question. The part that needs to be optimized is the nested for loop in the latter part of the main function

#include <chrono>
#include <iostream>
#include <vector>

// Takes in a 2D string vector by reference, and fills it to the required size with AA, AB, or BB
void make_genotype_data(int numRows, int numCols, std::vector<std::vector<std::string>>& geno) {
  std::string vals[3] = {"AA", "AB", "BB"};
  for (int i = 0; i < numRows; i++) {
    std::vector<std::string> markers;
    for (int j = 0; j < numCols; j++) {
      int randIndex = rand() % 3;
      markers.push_back(vals[randIndex]);
    }
    geno.push_back(markers);
    markers.clear();
  }
}


int main(int argc, char **argv) {
  // Timing Calculation
  using timepoint = std::chrono::time_point<std::chrono::high_resolution_clock>;
  auto print_exec_time = [](timepoint start, timepoint stop) {
    auto duration_us = std::chrono::duration_cast<std::chrono::microseconds>(stop - start);
    auto duration_ms = std::chrono::duration_cast<std::chrono::milliseconds>(stop - start);
    auto duration_s = std::chrono::duration_cast<std::chrono::seconds>(stop - start);

    std::cout << duration_s.count() << " s\n";
  };




  // Create the data
  auto start = std::chrono::high_resolution_clock::now();

  int numMarkers = 100;
  std::vector<std::vector<std::string>> old_genotypes;
  std::vector<std::vector<std::string>> new_genotypes;
  make_genotype_data(50, numMarkers, old_genotypes);
  make_genotype_data(6000, numMarkers, new_genotypes);

  auto stop = std::chrono::high_resolution_clock::now();
  std::cout << "*****************" << std::endl;
  std::cout << "Total time for creating data" << std::endl;
  print_exec_time(start, stop);
  std::cout << "*****************" << std::endl;

  int nCols = old_genotypes[0].size();
  float threshold = 0.8;




  // Compare old_genotypes with new_genotypes
  start = std::chrono::high_resolution_clock::now();

  for (int i = 0; i < old_genotypes.size()-1; i++) {
    auto og = old_genotypes[i];
    for (int j = 0; j < new_genotypes.size()-1; j++) {
      auto ng = new_genotypes[j];
      int numComparisons = 0;
      int numMatches = 0;
      for (int i = 1; i < nCols; i++) {
        if (ng[i] != "--" && og[i] != "--") {
          if (ng[i] == og[i]) {
            numMatches++;
          }
          numComparisons++;
        }
      }
      float similarity = (float) numMatches / numComparisons;
      if (similarity >= threshold) {
        std::cout << i << " from old_genotypes and " << j << " from new_genotypes have high similarity: " << similarity << std::endl;
      }
    }
  }

  stop = std::chrono::high_resolution_clock::now();
  std::cout << "*****************" << std::endl;
  std::cout << "Total time for comparison" << std::endl;
  print_exec_time(start, stop);
  std::cout << "*****************" << std::endl;
}

On 6,000 vs 5,000 it takes about 4 minutes. So for 6,000 vs 1.3M, it'll take about 17 hours. It's quite slow. And I have no idea what I can do to improve the speed of the nested for loop. I'm a bit new to C++, so I don't know too many of the intricacies, but I can follow along with the jargon.

I'd really appreciate some pointers (pun intended :D) to help me optimize this. I am willing to try parallelization by breaking one of the datasets up into chunks and feeding each chunk to a core to compare against the second dataset (though don't know how to parallelize in C++). But I only want to explore parallelization after taking the serialized version as far as it can go (it'll help with the parallelized version anyway).