dimanche 31 juillet 2022

Timer thread implementation

I've implemented a timer thread whose job is to call functions at a certain interval. The functions may be called multiple times if their interval > 0 millisec otherwise only one time. Even if the timer thread is running, still a new function can be registered. Could you please provide your feedback and improvement factors?

class TimerThread
{
    using ClockType = std::chrono::high_resolution_clock;

public:
    TimerThread() = default;
    TimerThread(TimerThread const &) = delete;
    TimerThread & operator=(TimerThread const &) = delete;

    ~TimerThread() noexcept
    {
        try
        {
            stop();
        }
        catch(std::exception const &ex)
        {
            std::cout << "Exception: " << ex.what() << std::endl;
        }
        catch(...)
        {
        }
    }

    void registerCallback(std::function<void()> func, uint32_t const interval=0)
    {
        std::unique_lock<std::mutex> lock{mt_};
        timers_.emplace_back(std::move(func), ClockType::now(), interval);
        cv_.notify_all();
    }

    void start(uint32_t const delay=0)
    {
        if (! start_)
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(delay));
            workerThread_ = std::thread{&TimerThread::run, this};
            start_ = true;
        }
    }

private:
    void run()
    {
        for (auto &t: timers_)
            t.prevFireTime_ = ClockType::now();

        while (startTimerFlag_.load(std::memory_order_acquire))
        {
            std::unique_lock<std::mutex> lock{mt_};
            cv_.wait(lock, [this]() -> bool {
                return ! timers_.empty();
            });

            for (auto &t: timers_)
                if (t.isReady())
                    t.func_();
        }
    }

    void stop()
    {
        startTimerFlag_.store(false, std::memory_order_release);
        cv_.notify_all();
        if (workerThread_.joinable())
            workerThread_.join();
    }

    struct TimerInfo
    {
        TimerInfo() = default;

        TimerInfo(std::function<void()> func, ClockType::time_point prevFireTime, uint32_t const interval):
            func_{std::move(func)},
            prevFireTime_{prevFireTime},
            intervalMilliSec_{interval}
        {
        }

        bool isReady()
        {
            if (!isFiredFirstTime)
            {
                isFiredFirstTime = true;
                return true;
            }
            else if (intervalMilliSec_ != 0)
            {
                auto current = ClockType::now();
                uint32_t const duration = std::chrono::duration_cast<std::chrono::milliseconds>(current - prevFireTime_).count();

                if (duration >= intervalMilliSec_)
                {
                    prevFireTime_ = current;
                    return true;
                }
            }

            return false;
        }

        std::function<void()> func_;
        ClockType::time_point prevFireTime_;
        uint32_t intervalMilliSec_;
        bool isFiredFirstTime{false};
    };

    std::vector<TimerInfo> timers_;
    std::thread workerThread_;
    std::mutex mt_;
    std::condition_variable cv_;
    std::atomic<bool> startTimerFlag_{true};
    bool start_{false};
};

int main()
{
    TimerThread timer;

    timer.registerCallback([](){
        std::cout << "Timer 1 - " << std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count() << std::endl;
    }, 1000);

    timer.registerCallback([](){
        std::cout << "Timer 2 - " << std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count() << std::endl;
    }, 2000);

    timer.registerCallback([](){
        std::cout << "Timer 3 - " << std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count() << std::endl;
    });

    timer.start();

    std::this_thread::sleep_for(std::chrono::seconds(5));

    LOG("Terminating main()...");

    return 0;
}

no type name 'typed' in class std::result_of [closed]

error: no type named ‘type’ in ‘class std::result_of<std::_Bind<void (*(std::_Placeholder<1>, std::_Placeholder<2>, int, std::_Placeholder<3>))(const int*, int, int, double&)>(int*, int, double)>’
       typedef typename result_of<_Callable(_Args...)>::type result_type;<br>
   auto cvf= bind(computeVarFactor,_1,_2,total_items,avg,_3);
    thread *t1=new thread[num_threads];
    
    for(int i=0;i<num_threads;i++)
    {
        t1[i]=thread(cvf,&data[p_indices[i]],(p_indices[i+1]-p_indices[i]),variances[i]);
    }
    
    //JOINING THE THREADS
    for(int i=0;i<num_threads;i++)
    {
        t1[i].join();
    }
void computeAvgFactor(const int* arr, int size, int divisor, double& avg) {
        avg = 0;
        for (int i = 0; i < size; i++)
            avg += arr[i];
        avg /= divisor;
    }

this is the code I'm sure is causing the problem, yet I've wrecked my brains searching over the internet about what's causing the issue?. I'm hopeful I will find some lead here. Thanks.

Are iterators still valid when the underlying elements have been moved?

If I have an iterator pointing to an element in an STL container, and I moved the element with the iterator, does the standard guarantee that the iterator is still valid? Can I use it with container's method, e.g. container::erase?

Also does it matter, if the container is a continuous one, e.g. vector, or non-continuous one, e.g. list?

std::list<std::string> l{"a", "b", "c"};
auto iter = l.begin();
auto s = std::move(*iter);
l.erase(iter);       // <----- is it valid to erase it, whose underlying element has been removed?

iterating through vector array error bs lc first question

class Solution {

public:

int search(vector& nums, int target) {

 int count=0;

for(unsigned long i=0; i<nums.size(); ++i){
    if(nums[i]==target)
    { return nums[i]; ++count; break;}
}

    


if(count==0) return -1;
}

};

samedi 30 juillet 2022

C++ Optional

can I use Optional<Parent Class pointer> Map as function parameter while passing Optional<Child Class pointer> Map as argument?

For example, I have two classes and a map

#include <iostream>
#include <string>
#include <optional>
#include <map>
#include <memory>

using namespace std;

class A {
    public:
       virtual void f() = 0;
}; //abstract class

class B : public A {
    public:
       void f() override {
           std::cout <<"override only" << std::endl;
       }
};

void testFunction(std::map<int, std::optional<std::shared_ptr<B>>>) {
    std::cout << "success!" << std::endl;
}

int main() {
    std::map<int, std::optional<std::shared_ptr<A>>> map;
    testFunction(map);
    return 0;
}

code link: When I want to pass map to testFunction, compiler throws "no conversion" error.

main.cpp:27:18: error: could not convert ‘map’ from ‘map<[...],optional>>’ to ‘map<[...],optional>>’

Is it because of the Optional or Map? (I think it's map, because map<int, Parent Class> doesn't work neither.

Is there a way to pass a map with optional of child class pointer?

Thanks!

=======

Or let's talk about a simpler version, we only have pointer in the map, is there a way to achieve below codes:

void testFunction(std::map<int, std::shared_ptr<B>>) {
    std::cout << "success!" << std::endl;
}

int main() {
    std::map<int, std::shared_ptr<A>> map;
    testFunction(map);
}

I am extremely confident my Gmail account and phone number is linked to someone's Gmail account through "family link" .Need to unlink

I believe it was set like I'm the child "under 13" so I can't regain any type of control of my account at all costs...I have seemed to try all I can to fix this snooping,E-mail highjack but I finally submit...I need help!!!

vendredi 29 juillet 2022

Use global function from library in C++ with local variables

I have created a library in C++ in which I have a function similar to the following:

originalmain.cpp

executionTimer * timer;

//This function is available to every other class through a global header file
calculateTime(){
    timer->returnTime() 
}

main(){
    foo(); // a function that eventually calls calulateTime()
    return 0;
}

foo.cpp

#include "globals.h"
void foo(){
   ....
   calculateTime();
   ...

When foo() calls calculateTime(), the global function defined in main.cpp executes.

I have created a library from those files which I'm using in another program like so:

mymain.cpp

#include "globals.h"

// trying to redefine the executionTime global object
// and the global calculateTime function to use it
executionTime * timer2; 
calculateTime(){
    timer2->returnTime()
}

main(){
   foo(); // I want foo to run normally, but now use timer2 instead of timer
   ...
   return 0;
}

From my understanding, since I'm using the library, I should have access to the functions/classes etc defined there. and indeed I have in most of them.

Things go wrong when foo() is calling 'calculateTime'. In that case I would expect calculateTime() from mymain.cpp to be executed, but instead I see the one from main.cpp.

So I have the following questions:

  1. Why is this happening?
  2. Is there a way to fix it?

Best regards

Integer sequence as a non-type template parameter

I'd like to pass several arbitrary length integer sequences as non-type parameters to a template class, so the instantiation would look something like this:

Foo<Bar, {1,2,3,4}, {5,6,7}> foo;

Is there a simple way to do this, possibly with C++11?

jeudi 28 juillet 2022

How to save vector of std::vector

new to C++

I have a question about how to save vector of ptrs.

Approach 1:

std::vector<TypeB> function(const std::vector<const TypeA*>& vector_a) {
  std::vector<const TypeB*> vector_b;

  for (const auto a : vector_a) {
    TypeB b_value = TypeB(*a);
    vector_b.emplace_back(&b_value);
  }

  return function2(vector_b);
}

Which seems only save one item.

I changed the code to: Approach 2:

std::vector<TypeB> function(const std::vector<const TypeA*>& vector_a) {
  std::vector<TypeB> vector_b;
  for (const auto& a : vector_a) {
    const TypeB value_b = EntityStateStruct(*a);
    vector_b.emplace_back(value_b);
  }

  std::vector<const TypeB*> value_b_ptr;
  for (const auto& value_b : vector_b) {
    value_b_ptr.emplace_back(&value_b);
  }

  return function2(value_b_ptr);
}

Which is working.

What I guess is in approach 1, the input const std::vector<const TypeA*>& vector_a will be destroyed when the function ends?

Need some knowledge about this part, Thank you!

How can I set class member variable correctly from vector in C++

I'm trying to set a class member variable from STL vector in C++.

But it doesn't work the way I want it to. The variable doesn't change, The variable is the same like before.

Am I programming in the wrong way?

Here's the code.

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

class Test {
private:
  std::string name;

public:
  Test();
  Test(std::string p_name);
  std::string getName();
  void setName(std::string p_name);
};

Test::Test() { name = ""; }

Test::Test(std::string p_name) : name(p_name) {}

std::string Test::getName() { return name; }

void Test::setName(std::string p_name) { name = p_name; }

int main() {
  // Initializing vector with values
  vector<Test> tests;

  for (size_t i = 0; i < 10; i++) {
    tests.push_back(Test());
  }

  for (Test test : tests) {
    cout << test.getName() << endl;
    test.setName("a");
  }

  for (Test test : tests) {
    cout << test.getName() << endl;
  }

  return 0;
}

This is the result:

> ./main




















> 

Why It doesn't work, and how to fix it?

const lvalue reference vs forwarding reference

I just cannot understand why would one want to use a forwarding reference instead of a const lvalue reference.

So why instead of this:

template<typename T>
void g(T&& x)
{
    ...
}

template<typename T>
void f(T&& x)
{
    g(std::forward<T>(x));
}

I could not use the following and get the same results performance wise (assuming I dont want to modify object x):

template<typename T>
void g(const T& x)
{
    ...
}

template<typename T>
void f(const T& x)
{
    g(x);
}

mercredi 27 juillet 2022

How to print only once from array and ignore duplicate string with same id and value [closed]

I have an array with multiple of the same id which corresponds to a given name. But I only want it to print once. How can I do so? My current codes outputs this -> Current output

What I want my output to look like -> desired output

char dummy;
istringstream iss(line); // using istringstream to read directly from line
iss >> dummy >> citya >> dummy >> cityb >> dummy >> dummy >> cityc >> dummy >> city;
cityarray[cityb][citya] = cityc;
if (cityc == 3)
{
    city = "Big_City";
    cout << "City Name  :  " << city << endl;
    cout << "City Id    :  " << cityc << endl;
}
else if (cityc == 2)
{
    city = "Mid_City";
    cout << "City Name  :  " << city << endl;
    cout << "City Id    :  " << cityc << endl;
}
else if (cityc == 1)
{
    city = "Small_City";
    cout << "City Name  :  " << city << endl;
    cout << "City Id    :  " << cityc << endl;
}

mardi 26 juillet 2022

Month auto increment using mktime and timegm functions in C++

I'd like to convert a string date (UTC) to a timestamp using C++. It works fine except for the month, which is auto incremented by one.

If the string is 20221222074648, for 2022-12-22 07:46:48, the timestamp will be 1674373608, which is the timestamp of 2023-01-22 07:46:48.

I don't understand the reason of this auto-increment, because there's no changes of the month's variable in the code below.

    cout << "date : " << receivedDate << endl;
    struct tm t;
    time_t timestamp;
    size_t year_size = 4;
    size_t other_size = 2;
    t.tm_year = stoi(receivedDate.substr(0, 4), &year_size, 10) - 1900;
    t.tm_mon = stoi(receivedDate.substr(4, 2), &other_size, 10);
    t.tm_mday = stoi(receivedDate.substr(6, 2), &other_size, 10);
    t.tm_hour = stoi(receivedDate.substr(8, 2), &other_size, 10);
    t.tm_min = stoi(receivedDate.substr(10, 2), &other_size, 10);
    t.tm_sec = stoi(receivedDate.substr(12, 2), &other_size, 10);
    t.tm_isdst = -1;
    cout << "year : " << t.tm_year + 1900 << "\nmonth : " << t.tm_mon << "\nday : " << t.tm_mday << "\nhour : " << t.tm_hour << "\nminutes : " << t.tm_min << "\nseconds : " << t.tm_sec << endl;

    timestamp = timegm(&t);

    cout << "timestamp : " << timestamp << endl;
    cout << "asctime timestamp : " << asctime(&t);

How to split a string using regex in c++?

I have a string and I need to split that string using regex.
(I have done this without using regex.)

Input: 
           str = "line (94 * SCALE, 10 * SCALE, 62 * SCALE, 10 * SCALE);"  
Output:
          firstSubPart = line
          secondSubPart = (94 * SCALE, 10 * SCALE, 62 * SCALE, 10 * SCALE);

dimanche 24 juillet 2022

Which is the correct function definition for returning an unsigned integer array from a function?

Which is the correct function definition for returning an unsigned integer array from a function in solidity..

Struct values going missing when trying to call them?

I'm having quite a bit of issue when it comes to getting my struct values to be used in another function. For some reason it keeps going missing outside of the if loop that it is in.

I saw some posts saying that this happens because it is in an if loop, and will need to do something to pass by reference, but even if I attempt to remove the higher level if statements, I'll still need the if statement to do the regex matching for the values. So I'm really not too sure how to go about doing this and would really appreciate all the help I can get! Thank you!

Some context for this portion of code - I need to store certain values from the file that's loaded in, into different variables within a struct, then call the values after in another function.

Struct & dynamic array declaration:

struct cityLocations
{
    int cityXAxis = 0;
    int cityYAxis = 0;
    int cityID = 0;
    string cityName = "";
};

cityLocations * cityLocationLines;

storeFileData() function:

void storeFileData(int fileID)
{
    string fileline; // for getline
    smatch match; // for regex matching
    ifstream inputFile; // opening stream for inputFile
    int index = 0; // index for the struct array

    // to store the file names
    cityLocationFile = configFileNames[0];

// these two below are basically the same as the citylocation one just with different values
    //cloudCoverFile = configFileNames[1];
    //pressureFile = configFileNames[2];

    
    // to check the values stored: 
    cout << "City location file name: " << cityLocationFile << endl;
    cout << "Cloud cover file name: " << cloudCoverFile << endl;
    cout << "Pressure file name: " << pressureFile << endl;
    cout << endl;
    
    // for citylocation.txt
    if (fileID == 0)
    {
        inputFile.open(cityLocationFile.c_str());
        if (inputFile.is_open())
        {
            while (getline (inputFile, fileline))
            {
                // to count the number of lines within the file so that it can be used to create an array
                if (regex_search(fileline, match, cityLocationPositionRegex))
                {
                    cityLocationCount++;
                }

                //creates an array big enough to store all the lines within the city location file
                cityLocationLines = new cityLocations[cityLocationCount];

                if (regex_search (fileline, match, cityLocationPositionRegex))
                {
                    cityLocationLines[index].cityXAxis = stoi(match[1]);
                    cityLocationLines[index].cityYAxis = stoi(match[2]);
                    cityLocationLines[index].cityID = stoi(match[3]);
                    cityLocationLines[index].cityName = (match[4])

                    index++;
                }

            }
        }
        inputFile.close();
    }

When calling the storeFileData() in another function...

displayMap() function:

void displayMap(int mapID)
{
    // some blocks of code for the border of the map
    // for citylocation.txt
    if (mapID == 0)
    {
        storeFileData(0);   
        
        // /*
        // to test
        // NTS: when this is done, returns weird numBERS
        cout << "Number of cities: " << cityLocationCount << endl;
        for (int index = 0; index<cityLocationCount; index++)
        {
            cout << "X & Y axis: " << cityLocationLines[index].cityXAxis << " & " << cityLocationLines[index].cityYAxis << endl;
            cout << "City ID: " << cityLocationLines[index].cityID << endl;
            cout << "City Name: " << cityLocationLines[index].cityName << endl;
            cout << endl;
        }
    }
}

C++11 - Keeping track of templated static storage of repeated types

I'm trying to create a flexible multi-track animation system using only C++11.

So far I have this code:

#include <vector>
#include <array>
#include <unordered_map>
#include <map>

template<typename T>
struct AnimationTrack
{
    using map_type = std::map<float, T>;
    map_type keyframes;

    AnimationTrack(std::initializer_list<typename map_type::value_type>&& keyframes) :
        keyframes(std::move(keyframes)) {}
};

template<typename T>
struct AnimationTrackView
{
    AnimationTrack<T>* track;

    AnimationTrackView() : 
        track(nullptr) {}

    AnimationTrackView(AnimationTrack<T>* track) :
        track(track) {}
};

template<typename... TrackTs>
class Animation
{
public:
    Animation(AnimationTrack<TrackTs>&... tracks)
    {
        StoreViews(tracks...);
    }

    template<std::size_t Index>
    auto& GetTrack()
    {
        return GetStorage<std::tuple_element<Index, std::tuple<TrackTs...>>::type>()[this].track;
    }

private:
    template<typename T>
    static auto& GetStorage()
    {
        static std::unordered_map<Animation*, AnimationTrackView<T>> storage;
        return storage;
    }

    template<typename T, typename... Ts>
    void StoreViews(AnimationTrack<T>& current, AnimationTrack<Ts>&... rest)
    {
        auto& storage = GetStorage<T>(); 
        storage.emplace(this, std::addressof(current));
        using expander = int[];
        (void)expander {
            0, (void(GetStorage<Ts>().emplace(this, std::addressof(rest))), 0)...
        };
    }
};


int main()
{
    AnimationTrack<float> test1(
    {
        { 0.2f, 1.0f },
        { 0.5f, 2.0f },
        { 0.9f, 3.0f }
    });

    AnimationTrack<int> test2(
    {
        { 0.2f, 1 },
        { 0.5f, 2 },
        { 0.9f, 3 }
    });

    Animation<float, int> anim(test1, test2);
    auto track0 = anim.GetTrack<0>();
    auto track1 = anim.GetTrack<1>();
}

This example works fine in this use case, but what if I wanted to keep two tracks of the same type? With my current code both tracks would grab from the same static storage when calling GetTrack, but the problem is I can't figure out a way to make it work with repeats of the same type. Any suggestions?

samedi 23 juillet 2022

braced-initialization allows creation of temporary of a *private* struct

I just read the following article from Raymond Chen's excellent 'The Old New Thing': https://devblogs.microsoft.com/oldnewthing/20210719-00/?p=105454

I have a question about this, best described in the following code snippet. Why is the initialization of 'x3' allowed at all? I don't see any semantic difference between the initialization of 'x2' and 'x3' below.

#include <memory>

class X
{
    struct PrivateTag {};   // default constructor is *NOT* explicit
public:
    X(PrivateTag) {}
    static auto Create() -> std::unique_ptr<X> 
    {
        return std::make_unique<X>(PrivateTag{});
    }
};

int main()
{
    auto x1 = X::Create();          // ok:    proper way to create this
  //auto x2 = X(X::PrivateTag{});   // error: cannot access private struct
    auto x3 = X({});                // ok:    why ?!
}

add deltaTime to movements in sfml

im working on Pacman game with c++ and sfml.as time passes, the game becomes slower. so i want to add delta time to movements. i added in one way but collision not working correctly after using delta time.i think i used the wrong method for it.

My main code

#include <SFML/Graphics.hpp>
#include <Map.hpp>

using namespace sf;

int main()
{
RenderWindow window(VideoMode(Width * CellSize, Height * CellSize), "PacMan");
window.setFramerateLimit(120);
Map map;

float dt;
Clock clock;


while (window.isOpen())
{

    Event event;
    while (window.pollEvent(event))
    {
        if (event.type == Event::Closed)
        {
            window.close();
        }
        if (event.type == Event::KeyPressed && event.key.code == Keyboard::Escape)
        {
            window.close();
        }
    }
    
    window.clear();

    dt = clock.restart().asSeconds() * 50;
    map.draw(window, dt);

    window.display();
}

}

Map class

#include <SFML/Graphics.hpp>
#include <array>
#include <iostream>
#include <Pacman.hpp>
#include <vector>

using namespace sf;

class Map
{
private:
    std::array<std::string, Height> sketch;
    Pacman pacman;
    std::vector<sf::RectangleShape> Walls;

    void initMap();

public:
    Map();
    void draw(sf::RenderWindow & window, float dt);

};

Map::Map()
{
    this->initMap();
}

void Map::initMap()
{
    sketch = {
        " ################### ",
        " #        #        # ",
        " # ## ### # ### ## # ",
        " #                 # ",
        " # ## # ##### # ## # ",
        " #    #   #   #    # ",
        " #### ### # ### #### ",
        "    # #       # #    ",
        "##### # ##### # #####",
        "        #   #        ",
        "##### # ##### # #####",
        "    # #       # #   ",
        " #### ### # ### #### ",
        " #    #   #   #    # ",
        " # ## # ##### # ## # ",
        " #                 # ",
        " # ## ### # ### ## # ",
        " #        #        # ",
        " ################### ",
        "                     ",
        "                     "
    };
}

void Map::draw(RenderWindow & window, float dt)
{
    RectangleShape Wall(Vector2f(CellSize, CellSize));
    Wall.setFillColor(Color::Blue);

    for (size_t i = 0; i < Height; i++)
    {
        for (size_t j = 0; j < Width; j++)
        {
            switch (sketch[i][j])
            {
            case '#':
                Wall.setPosition(Vector2f(j * CellSize, i * CellSize));
                Walls.push_back(Wall);
                break;
            }
        }
    }

    for(auto & a : Walls)
    {
        window.draw(a);
    }
    
    
    pacman.draw(window);
    pacman.move(Walls, dt, sketch);
}

Pacman class

    #include <SFML/Graphics.hpp>
#include <vector>
#include <info.hpp>

class Pacman
{
private:
    sf::CircleShape player;
    sf::Vector2f Pos;
    int dir;


    void initPacman();
    bool collision(float i_x, float i_y, std::array<std::string, Height> sketch);

public:
    Pacman();
    void draw(sf::RenderWindow & window);
    void move(std::vector<sf::RectangleShape> Walls, float dt, std::array<std::string, Height> sketch);
};

#include <iostream>
#include <cmath>

using namespace sf;

Pacman::Pacman()
{
    this->initPacman();
}

void Pacman::initPacman()
{
    Pos.x = 10 * CellSize;
    Pos.y = 11 * CellSize;
    player.setRadius(CellSize / 2);
    player.setFillColor(Color::Yellow);
    player.setPosition(Pos);
    dir = -1;
}

void Pacman::draw(RenderWindow & window)
{
    window.draw(player);
}

void Pacman::move(std::vector<sf::RectangleShape> Walls, float dt, std::array<std::string, Height> sketch)
{
    std::array<bool, 4> wall;

i checking collision here.i will check the next position that hits the wall or not. i think my delta time makes it work randomly. // Collision Right wall[0] = collision(player.getPosition().x + (Speed * dt), player.getPosition().y, sketch); // Collision Down wall[1] = collision(player.getPosition().x, player.getPosition().y + (Speed * dt), sketch); // Collision Left wall[2] = collision(player.getPosition().x - (Speed * dt), player.getPosition().y, sketch); // Collision Up wall[3] = collision(player.getPosition().x, player.getPosition().y - (Speed * dt), sketch);

    Vector2f position;
    position.x = 0;
    position.y = 0;

    if(Keyboard::isKeyPressed(Keyboard::Right))
    {
        if (wall[0] == 0)
        {
            dir = 0;
        }   
    } else if(Keyboard::isKeyPressed(Keyboard::Down))
    {
        if (wall[1] == 0)
        {
            dir = 1;
        }
    } else if(Keyboard::isKeyPressed(Keyboard::Left))
    {   
        if (wall[2] == 0)
        {
            dir = 2;
        }
    } else if(Keyboard::isKeyPressed(Keyboard::Up))
    {
        if (wall[3] == 0)
        {
            dir = 3;
        }
    }

    if (wall[dir] == 0)
    { 
        switch (dir)
        {
        case 0:
            position.x += Speed * dt;
            break;
        case 1:
            position.y += Speed * dt;
            break;
        case 2:
            position.x -= Speed * dt;
            break;
        case 3:
            position.y -= Speed * dt;
            break;
        }
    }
    player.move(position.x, position.y);
}

bool Pacman::collision(float px, float py, std::array<std::string, Height> sketch)
{
    
    float cell_x = px / static_cast<float>(CellSize);
    float cell_y = py / static_cast<float>(CellSize);

// std::cout << cell_x << "\n";
    for (int a = 0; a < 4; a++)
    {
        float x = 0;
        float y = 0;

        switch (a)
        {
            case 0: //Top left cell
            {
                x = static_cast<float>(floor(cell_x));
                y = static_cast<float>(floor(cell_y));

                break;
            }
            case 1: //Top right cell
            {
                x = static_cast<float>(ceil(cell_x));
                y = static_cast<float>(floor(cell_y));

                break;
            }
            case 2: //Bottom left cell
            {
                x = static_cast<float>(floor(cell_x));
                y = static_cast<float>(ceil(cell_y));

                break;
            }
            case 3: //Bottom right cell
            {
                x = static_cast<float>(ceil(cell_x));
                y = static_cast<float>(ceil(cell_y));
            }
        }

        if (0 <= x && 0 <= y && Height > y && Width > x)
        {
            //std::cout << "x : " << x << "\t y : " << y << "\n";
            if (sketch[y][x] == '#')
            {
                return 1;
            }
        }
    }
    return 0;
}

how could i have an algorithm for this?

i saw a video on tiktok of someone advertising a kind of game so i found it interstaing and wanted to do it the link for the video uploaded :

it is about 8 pages and if they are all togather they show 4*13 symbol but each one have some missing symbols

if the user chose a symbol from the all pages combined then i show him the pages each one alone if he said that his symbol in one of these pages then the page get abandoned when he finish i combine the rest which his symbol didn't appear on them and the only symbol that will be missing is what he thought about for more understanding see the video

i wrote this code as it shows the main page(the 8 pages combined)

i added some colors' functions just forget about it

#include <iostream>
#include <windows.h>
using namespace std;
HANDLE hc=GetStdHandle(STD_OUTPUT_HANDLE);

char elements[4][13]={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','#','$','!','?','=','%','+','-','*','1','2','3','4','5','6','7','8','9','0',3,2,5,'&',14,15,6};
void main_page(){
SetConsoleTextAttribute(hc,11*16);
cout<<string(65,' ')<<"\n";
for(int i=0 ;i<4;i++){
    for(int j=0 ;j<13;j++){
        cout<<" ";
        SetConsoleTextAttribute(hc,14);
        cout<<" "<<elements[i][j]<<" ";
        SetConsoleTextAttribute(hc,11*16);
        cout<<" ";
    }
    cout<<endl<<string(65,' ')<<endl;
}
SetConsoleTextAttribute(hc,7);


}

i wanted to start writing the functions for the rest pages as it will ask the user if his symbol is here or not if it is it will abandon it else it will keep it and then compare between the pages to see what is missing and show it but i didn't know how let the computer know that this symbol is missing (saying is easier than doing)

if anyone can help me and tell me what should i do and how can i compare between the missing things i would appreciate it forever

vendredi 22 juillet 2022

Does C++ provide a complete set of membars?

Acquire-release memory ordering provides a way to create a partial ordering of surrounding operations between two points in the program. This memory ordering inhibits reordering of instructions or memory operations (maybe partially) across this barrier. This essentially guarantees some synchronization across various marked points. But this is just a pairwise relationship and there is no total ordering guarantee. There are four values: relaxed, acquire, release, acq-rel.

Sequential-consistency property guarantees a total ordering of memory at various points in the program. Just plain sequential consistency property does not inhibit any kind of instruction reordering or memory reordering. It just ensures that, marked instructions or memory operations happens in a global order. But this does not give any guarantees about surrounding instructions(?). There are two values: not-cst, seq-cst.

I'm not sure if there are any other types of membars or other ways to categorize them. Wherever I see, I only see these barriers. So I intuitively listed them like above.

Now, by combining acquire-release ordering with sequential consistency property, we can create many kinds of barriers (at least on paper):

LOAD:          (C++ std::atomic_load)
relaxed                          (C++ std::memory_order_relaxed)
relaxed with seq-consist         (C++ ?)
acquire                          (C++ std::memory_order_acquire)
acquire with seq-consist         (C++ std::memory_order_seq_cst)
STORE:         (C++ std::atomic_store)
relaxed                          (C++ std::memory_order_relaxed)
relaxed with seq-consist         (C++ ?)
release                          (C++ std::memory_order_release)
release with seq-consist         (C++ std::memory_order_seq_cst)
EXCHANGE:      (C++ std::atomic_exchange)
relaxed                          (C++ std::memory_order_relaxed)
relaxed with seq-consist         (C++ ?)
acquire                          (C++ std::memory_order_acquire)
acquire with seq-consist         (C++ ?)
release                          (C++ std::memory_order_release)
release with seq-consist         (C++ ?)
acq-rel                          (C++ std::memory_order_acq_rel)
acq-rel with seq-consist         (C++ std::memory_order_seq_cst)
FENCE:         (C++ std::atomic_thread_fence)
acquire                          (C++ std::memory_order_acquire)
acquire with seq-consist         (C++ ?)
release                          (C++ std::memory_order_release)
release with seq-consist         (C++ ?)
acq-rel                          (C++ std::memory_order_acq_rel)
acq-rel with seq-consist         (C++ std::memory_order_seq_cst)

In the table, there are some missing values (relaxed_seq_cst load, stores; acquire_seq_cst and release_seq_cst fences; etc). Are they redundant? Or are they harder to use correctly / debug? Or it is left out just to reduce complexity in the library?

What is the difference between std::list and std::vector? [duplicate]

What I already know:

  • They're sequential containers; gives the programmer the control to modify the order of the elements and how they're accessed.
  • They're both templates.

What I want to know:

  • What is the difference between a std::list and std::vector? (description on their performance differences is also welcome)

Provide definition of constructor template outside a class template [duplicate]

Consider the following class template with a constructor template:

template <class T>
class C{
    public:
    T val_;
    std::string str_;
    
    template <typename S>
    C(const S& str);
    // C(const S& str) : str_(str) {}; // Valid definition of constructor within class body
    
    void print(){std::cout << str_;}
};

I'm, however, trying to define the constructor outside of the class, but I can't seem to figure out a way to account for the type S.

template <typename T, typename S> // incorrect as too many parameters
C<T>::C(const S& str) : str_(str) {};

Alternatively, I tried

template <typename T>
C<T>::C(const std::string& str) : str_(str) {};

which also does not work (and probably defeats the purpose of S)

  1. How can I correctly define this constructor outside the class.
  2. Does such a pattern (where class template parameters differ from constructor template parameters) serve any practical purpose? An example would be very helpful.

jeudi 21 juillet 2022

Vector of pointers saving a pointer to a vector of ints

just wondering if you can point to a pointer that points to a vector of ints. And save the pointer that points to a vector of ints. Here's the code I'm trying to pull off. Probably dosen't make sense but I'm trying to make it work for a while now, bare with me. But I want to pull this way somehow.

int n, q;
cin >> n >> q;
vector <int*> ar;

for (int i=0;i<n;i++){
    
    int k;
    cin >> k;

    vector< int >  *vec;

    for(int j = 0;j<k;j++){
        (*(vec+j)).push_back(cin.get());

    }
    ar.push_back(&(vec));


}

Thanks for the possible help. Haven't seen this asked in here, just things a bit different than this.

what is the exact meaning of "int c {}" in C++? [duplicate]

I tried google but got no answer. So can someone please, explain the meaning of int c {} to me.

Http status code to status messages in C++

I have written a simple program using LibCurl that does some http stuff. I was wondering if there is any library with function that can convert http status codes to status messages or LibCurl has any function to do that?

Input => 200

Output => OK

I am using C++11

Thanks

Ia a prameter for a thread object mandated to be created in the destination thead

Lool at the following code:

#if defined(_WIN32)
    #include <Windows.h>
#elif defined(__unix__)
    #include <pthread.h>
#endif
#include <iostream>
#include <thread>
#include <type_traits>

using namespace std;

struct S
{
    S( char const *str );
};

S::S( char const *str )
{
#if defined(_WIN32)
    using id_t = DWORD;
#elif defined(__unix__)
    using id_t = pthread_t;
#endif
    static_assert(is_scalar_v<id_t>, "thread id has to be scalar");
    id_t id;
#if defined(_WIN32)
    id = GetCurrentThreadId();
#elif defined(__unix__)
    id = pthread_self();
#endif
    cout << id << endl;
}

int main()
{
    S( nullptr );
    auto thrObj = []( S const &s ) { };
    thread( thrObj, nullptr ).join();
    thread( thrObj, S( nullptr ) ).join();
}

Does the standard directly or indirectly mandate that the S() in the second line is created in the destination thread ? Or is this just somehow impossible to have creation on the initiating side ?

How should I assume which iterator category an algorithm uses?

Let's say :

std::sort(beg1, beg2, pred);

This algorithm takes a range of iterators for the container and a predicate. It takes an LegacyRandomAccessIterator. I do understand the the 5 iterator categories are categorised by their operators. Albeit I'm having a hard time assuming which iterator the algorithm uses.

How to code an unlock all tool in Call of duty Warzone

Is there any chance to create an unlock-all tool for a video game named Call of Duty: Warzone?

The tool should give the player in-game the ability to access all weapons, skins, and upgrades that are normally hidden behind an XP Wall and currency Wall.

How would I go on about analyzing the code, then look for a way to access these "hidden" aspects of the game, and then write an executable for a simple in-game UI that is displayed over the "normal UI" of the game?

mercredi 20 juillet 2022

Compiler shows error, when i trying to binding handler with a socket (boost::asio)

When I trying to write this, like:

this->_io_service.post(
    std::bind(this->_connection_handler, std::move(peer))
);

and compiler well generate lot of messages that i hard to understand.

Error messages:

n file included from D:\utils\MinGW\include/boost/asio/impl/execution_context.hpp:18,
                 from D:\utils\MinGW\include/boost/asio/execution_context.hpp:409,
                 ...
D:\utils\MinGW\include/boost/asio/impl/io_context.hpp: In instantiation of 'void boost::asio::io_context::initiate_post::operator()(LegacyCompletionHandler&&, boost::asio::io_context*) const [with LegacyCompletionHandler = std::_Bind<std::function<void(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>]':
D:\utils\MinGW\include/boost/asio/async_result.hpp:476:49:   required from 'static boost::asio::detail::completion_handler_async_result<CompletionToken, Signatures>::return_type boost::asio::detail::completion_handler_async_result<CompletionToken, Signatures>::initiate(Initiation&&, RawCompletionToken&&, Args&& ...) [with Initiation = boost::asio::io_context::initiate_post; RawCompletionToken = std::_Bind<std::function<void(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>; Args = {boost::asio::io_context*}; CompletionToken = std::_Bind<std::function<void(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>; Signatures = {void()}; boost::asio::detail::completion_handler_async_result<CompletionToken, Signatures>::return_type = void]'
D:\utils\MinGW\include/boost/asio/async_result.hpp:856:29:   required from 'typename boost::asio::constraint<boost::asio::detail::async_result_has_initiate_memfn<CompletionToken, Signatures>::value, decltype (boost::asio::async_result<typename std::decay<_Tp>::type, Signatures ...>::initiate(declval<Initiation&&>(), declval<CompletionToken&&>(), (declval<Args&&>)()...))>::type boost::asio::async_initiate(Initiation&&, CompletionToken&, Args&& ...) [with CompletionToken = std::_Bind<std::function<void(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>; Signatures = {void()}; Initiation = boost::asio::io_context::initiate_post; Args = {boost::asio::io_context*}; typename boost::asio::constraint<boost::asio::detail::async_result_has_initiate_memfn<CompletionToken, Signatures>::value, decltype (boost::asio::async_result<typename std::decay<_Tp>::type, Signatures ...>::initiate(declval<Initiation&&>(), declval<CompletionToken&&>(), (declval<Args&&>)()...))>::type = void; decltype (boost::asio::async_result<typename std::decay<_Tp>::type, Signatures ...>::initiate(declval<Initiation&&>(), declval<CompletionToken&&>(), (declval<Args&&>)()...)) = void; typename std::decay<_Tp>::type = std::decay<std::_Bind<std::function<void(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)> >::type]'
D:\utils\MinGW\include/boost/asio/impl/io_context.hpp:200:58:   required from 'auto boost::asio::io_context::post(LegacyCompletionHandler&&) [with LegacyCompletionHandler = std::_Bind<std::function<void(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>]'
.\acceptor.cpp:10:27:   required from here
D:\utils\MinGW\include/boost/asio/impl/io_context.hpp:173:5: error: use of deleted function 'std::_Bind<_Functor(_Bound_args ...)>::_Bind(const std::_Bind<_Functor(_Bound_args ...)>&) [with _Functor = std::function<void(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>; _Bound_args = {boost::asio::basic_stream_socket<boost::asio::ip::tcp, boost::asio::any_io_executor>}]'
  173 |     BOOST_ASIO_LEGACY_COMPLETION_HANDLER_CHECK(
      |     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from D:\utils\MinGW\include/boost/system/detail/error_category.hpp:17,
                 from D:\utils\MinGW\include/boost/system/detail/error_code.hpp:14,
                 from D:\utils\MinGW\include/boost/system/error_code.hpp:13,
                 from D:\utils\MinGW\include/boost/asio/detail/throw_error.hpp:19,
                 from D:\utils\MinGW\include/boost/asio/detail/impl/win_tss_ptr.ipp:22,
                 from D:\utils\MinGW\include/boost/asio/detail/win_tss_ptr.hpp:76,
                 from D:\utils\MinGW\include/boost/asio/detail/tss_ptr.hpp:25,
                 from D:\utils\MinGW\include/boost/asio/detail/call_stack.hpp:20,
                 from D:\utils\MinGW\include/boost/asio/detail/thread_context.hpp:20,
                 from D:\utils\MinGW\include/boost/asio/detail/recycling_allocator.hpp:20,
                 from D:\utils\MinGW\include/boost/asio/detail/handler_alloc_helpers.hpp:21,
                 from D:\utils\MinGW\include/boost/asio/detail/executor_function.hpp:19,
                 from D:\utils\MinGW\include/boost/asio/execution/any_executor.hpp:23,
                 from D:\utils\MinGW\include/boost/asio/execution.hpp:19,
                 from D:\utils\MinGW\include/boost/asio/any_io_executor.hpp:22,
                 from D:\utils\MinGW\include/boost/asio/basic_socket_acceptor.hpp:19,
                 from D:\utils\MinGW\include/boost/asio/ip/tcp.hpp:19,
                 from .\acceptor.h:4,
                 from .\acceptor.cpp:3:
d:\utils\mingw\include\c++\11.2.0\functional:493:7: note: 'std::_Bind<_Functor(_Bound_args ...)>::_Bind(const std::_Bind<_Functor(_Bound_args ...)>&) [with _Functor = std::function<void(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>; _Bound_args = {boost::asio::basic_stream_socket<boost::asio::ip::tcp, boost::asio::any_io_executor>}]' is implicitly deleted because the default definition would be ill-formed:
  493 |       _Bind(const _Bind&) = default;
      |       ^~~~~
d:\utils\mingw\include\c++\11.2.0\functional:493:7: error: use of deleted function 'constexpr std::tuple<_Elements>::tuple(const std::tuple<_Elements>&) [with _Elements = {boost::asio::basic_stream_socket<boost::asio::ip::tcp, boost::asio::any_io_executor>}]'
In file included from d:\utils\mingw\include\c++\11.2.0\bits\unique_ptr.h:37,
                 from d:\utils\mingw\include\c++\11.2.0\memory:76,
                 from D:\utils\MinGW\include/boost/asio/detail/memory.hpp:21,
                 from D:\utils\MinGW\include/boost/asio/execution/detail/as_invocable.hpp:20,
                 from D:\utils\MinGW\include/boost/asio/execution/execute.hpp:20,
                 from D:\utils\MinGW\include/boost/asio/execution/executor.hpp:20,
                 from D:\utils\MinGW\include/boost/asio/execution/allocator.hpp:20,
                 from D:\utils\MinGW\include/boost/asio/execution.hpp:18,
                 from D:\utils\MinGW\include/boost/asio/any_io_executor.hpp:22,
                 from D:\utils\MinGW\include/boost/asio/basic_socket_acceptor.hpp:19,
                 from D:\utils\MinGW\include/boost/asio/ip/tcp.hpp:19,
                 from .\acceptor.h:4,
                 from .\acceptor.cpp:3:
d:\utils\mingw\include\c++\11.2.0\tuple:744:17: note: 'constexpr std::tuple<_Elements>::tuple(const std::tuple<_Elements>&) [with _Elements = {boost::asio::basic_stream_socket<boost::asio::ip::tcp, boost::asio::any_io_executor>}]' is implicitly deleted because the default definition would be ill-formed:
  744 |       constexpr tuple(const tuple&) = default;
      |                 ^~~~~
d:\utils\mingw\include\c++\11.2.0\tuple:744:17: error: use of deleted function 'constexpr std::_Tuple_impl<_Idx, _Head>::_Tuple_impl(const std::_Tuple_impl<_Idx, _Head>&) [with long long unsigned int _Idx = 0; _Head = boost::asio::basic_stream_socket<boost::asio::ip::tcp>]'
d:\utils\mingw\include\c++\11.2.0\tuple:435:17: note: 'constexpr std::_Tuple_impl<_Idx, _Head>::_Tuple_impl(const std::_Tuple_impl<_Idx, _Head>&) [with long long unsigned int _Idx = 0; _Head = boost::asio::basic_stream_socket<boost::asio::ip::tcp>]' is implicitly deleted because the default definition would be ill-formed:
  435 |       constexpr _Tuple_impl(const _Tuple_impl&) = default;
      |                 ^~~~~~~~~~~
d:\utils\mingw\include\c++\11.2.0\tuple:435:17: error: use of deleted function 'constexpr std::_Head_base<_Idx, _Head, false>::_Head_base(const std::_Head_base<_Idx, _Head, false>&) [with long long unsigned int _Idx = 0; _Head = boost::asio::basic_stream_socket<boost::asio::ip::tcp>]'
d:\utils\mingw\include\c++\11.2.0\tuple:185:17: note: 'constexpr std::_Head_base<_Idx, _Head, false>::_Head_base(const std::_Head_base<_Idx, _Head, false>&) [with long long unsigned int _Idx = 0; _Head = boost::asio::basic_stream_socket<boost::asio::ip::tcp>]' is implicitly deleted because the default definition would be ill-formed:
  185 |       constexpr _Head_base(const _Head_base&) = default;
      |                 ^~~~~~~~~~
d:\utils\mingw\include\c++\11.2.0\tuple:185:17: error: use of deleted function 'boost::asio::basic_stream_socket<Protocol, Executor>::basic_stream_socket(const boost::asio::basic_stream_socket<Protocol, Executor>&) [with Protocol = boost::asio::ip::tcp; Executor = boost::asio::any_io_executor]'
In file included from D:\utils\MinGW\include/boost/asio/basic_socket_streambuf.hpp:25,
                 from D:\utils\MinGW\include/boost/asio/basic_socket_iostream.hpp:24,
                 from D:\utils\MinGW\include/boost/asio/ip/tcp.hpp:20,
                 from .\acceptor.h:4,
                 from .\acceptor.cpp:3:
D:\utils\MinGW\include/boost/asio/basic_stream_socket.hpp:1045:3: note: declared here
 1045 |   basic_stream_socket(const basic_stream_socket&) BOOST_ASIO_DELETED;
      |   ^~~~~~~~~~~~~~~~~~~
In file included from D:\utils\MinGW\include/boost/asio/impl/execution_context.hpp:18,
                 ...
D:\utils\MinGW\include/boost/asio/detail/handler_type_requirements.hpp:72:39: note:   initializing argument 1 of 'char (& boost::asio::detail::zero_arg_copyable_handler_test(Handler, ...))[2] [with Handler = std::_Bind<std::function<void(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>]'
   72 | char (&zero_arg_copyable_handler_test(Handler, ...))[2];
      |                                       ^~~~~~~
D:\utils\MinGW\include/boost/asio/impl/io_context.hpp:129:5: error: use of deleted function 'std::_Bind<_Functor(_Bound_args ...)>::_Bind(const std::_Bind<_Functor(_Bound_args ...)>&) [with _Functor = std::function<void(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>; _Bound_args = {boost::asio::basic_stream_socket<boost::asio::ip::tcp, boost::asio::any_io_executor>}]'
  129 |     BOOST_ASIO_LEGACY_COMPLETION_HANDLER_CHECK(
      |     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
D:\utils\MinGW\include/boost/asio/detail/handler_type_requirements.hpp:127:35: note:   initializing argument 1 of 'char boost::asio::detail::argbyv(T) [with T = std::_Bind<std::function<void(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>]'
  127 | template <typename T> char argbyv(T);
      |                                   ^
D:\utils\MinGW\include/boost/asio/impl/io_context.hpp:129:5: error: no match for call to '(std::_Bind<std::function<void(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>) ()'
  129 |     BOOST_ASIO_LEGACY_COMPLETION_HANDLER_CHECK(
      |     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
D:\utils\MinGW\include/boost/asio/impl/io_context.hpp: In instantiation of 'void boost::asio::io_context::initiate_post::operator()(LegacyCompletionHandler&&, boost::asio::io_context*) const [with LegacyCompletionHandler = std::_Bind<std::function<void(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>]':
D:\utils\MinGW\include/boost/asio/async_result.hpp:476:49:   required from 'static boost::asio::detail::completion_handler_async_result<CompletionToken, Signatures>::return_type boost::asio::detail::completion_handler_async_result<CompletionToken, Signatures>::initiate(Initiation&&, RawCompletionToken&&, Args&& ...) [with Initiation = boost::asio::io_context::initiate_post; RawCompletionToken = std::_Bind<std::function<void(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>; Args = {boost::asio::io_context*}; CompletionToken = std::_Bind<std::function<void(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>; Signatures = {void()}; boost::asio::detail::completion_handler_async_result<CompletionToken, Signatures>::return_type = void]'
D:\utils\MinGW\include/boost/asio/async_result.hpp:856:29:   required from 'typename boost::asio::constraint<boost::asio::detail::async_result_has_initiate_memfn<CompletionToken, Signatures>::value, decltype (boost::asio::async_result<typename std::decay<_Tp>::type, Signatures ...>::initiate(declval<Initiation&&>(), declval<CompletionToken&&>(), (declval<Args&&>)()...))>::type boost::asio::async_initiate(Initiation&&, CompletionToken&, Args&& ...) [with CompletionToken = std::_Bind<std::function<void(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>; Signatures = {void()}; Initiation = boost::asio::io_context::initiate_post; Args = {boost::asio::io_context*}; typename boost::asio::constraint<boost::asio::detail::async_result_has_initiate_memfn<CompletionToken, Signatures>::value, decltype (boost::asio::async_result<typename std::decay<_Tp>::type, Signatures ...>::initiate(declval<Initiation&&>(), declval<CompletionToken&&>(), (declval<Args&&>)()...))>::type = void; decltype (boost::asio::async_result<typename std::decay<_Tp>::type, Signatures ...>::initiate(declval<Initiation&&>(), declval<CompletionToken&&>(), (declval<Args&&>)()...)) = void; typename std::decay<_Tp>::type = std::decay<std::_Bind<std::function<void(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)> >::type]'
D:\utils\MinGW\include/boost/asio/impl/io_context.hpp:200:58:   required from 'auto boost::asio::io_context::post(LegacyCompletionHandler&&) [with LegacyCompletionHandler = std::_Bind<std::function<void(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>]'
.\acceptor.cpp:10:27:   required from here
d:\utils\mingw\include\c++\11.2.0\functional:543:9: note: candidate: 'template<class ... _Args, class _Result> _Result std::_Bind<_Functor(_Bound_args ...)>::operator()(_Args&& ...) const volatile [with _Args = {_Args ...}; _Result = _Result; _Functor = std::function<void(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>; _Bound_args = {boost::asio::basic_stream_socket<boost::asio::ip::tcp, 
boost::asio::any_io_executor>}]'
  543 |         operator()(_Args&&... __args) const volatile
      |         ^~~~~~~~
d:\utils\mingw\include\c++\11.2.0\functional:543:9: note:   template argument deduction/substitution failed:
d:\utils\mingw\include\c++\11.2.0\functional: In substitution of 'template<class _Functor, class ... _Bound_args> template<class _Fn, class _CallArgs, class ... _BArgs> using _Res_type_impl = typename std::result_of<_Fn&(decltype (std::_Mu<typename std::remove_cv<_BArgs>::type, std::is_bind_expression<typename std::remove_cv<_BArgs>::type>::value, (std::is_placeholder<typename std::remove_cv<_BArgs>::type>::value > 0)>()(declval<_BArgs&>(), declval<_CallArgs&>()))&& ...)>::type [with _Fn = const volatile std::function<void(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>; _CallArgs = std::tuple<>; _BArgs = {const volatile boost::asio::basic_stream_socket<boost::asio::ip::tcp, boost::asio::any_io_executor>}; _Functor = std::function<void(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>; _Bound_args = {boost::asio::basic_stream_socket<boost::asio::ip::tcp, boost::asio::any_io_executor>}]':
d:\utils\mingw\include\c++\11.2.0\functional:475:8:   required by substitution of 'template<class _Functor, class ... _Bound_args> template<class _CallArgs, template<class _CallArgs, template<class> class __cv_quals> template<class _Functor, class ... _Bound_args> template<class> class __cv_quals> using _Res_type_cv = std::_Bind<_Functor(_Bound_args ...)>::_Res_type_impl<typename __cv_quals<typename std::enable_if<(bool)((std::tuple_size<_Tuple>::value + 1)), _Functor>::type>::type, _CallArgs, typename __cv_quals<_Bound_args>::type ...> [with _CallArgs = std::tuple<>; __cv_quals = std::add_cv; _Functor = std::function<void(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>; _Bound_args = {boost::asio::basic_stream_socket<boost::asio::ip::tcp, boost::asio::any_io_executor>}]' = {boost::asio::basic_stream_socket<boost::asio::ip::tcp, boost::asio::any_io_executor>}]'                                                                                                                                                                                                                >)>(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>]'
d:\utils\mingw\include\c++\11.2.0\functional:540:9:   required from 'void boost::asio::io_context::initiate_post::operator()(LegacyCompletionHandler&&, boost::asio::io_context*) const [with LegacyCompletionHandler = std::_Bind<std::function<void(boost::asio::basic_stream_socket<boost::asio::ip::tcpken&&, Args&& ...) [with Initiation = boost::asio::io_context::initiate_post; RawCompletionToken = std>)>(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>]'                                                                                                                                                                                                                                             c_stream_socket<boost::asio::ip::tcp>)>; Signatures = {void()}; boost::asio::detail::completion_handle
D:\utils\MinGW\include/boost/asio/async_result.hpp:476:49:   required from 'static boost::asio::detail::completion_handler_async_result<CompletionToken, Signatures>::return_type boost::asio::detail::completion_handler_async_result<CompletionToken, Signatures>::initiate(Initiation&&, RawCompletionToken&&, Args&& ...) [with Initiation = boost::asio::io_context::initiate_post; RawCompletionToken = std::_Bind<std::function<void(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>; Args = {boost::asio::io_context*}; CompletionToken = stl<Initiation&&>(), declval<CompletionToken&&>(), (declval<Args&&>)()...))>::type boost::asio::async_ind::_Bind<std::function<void(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>; Signatures = {void()}; boost::asio::detail::completion_handler_async_result<CompletionToken, Signatures>::return_type = void]'                              s = {boost::asio::io_context*}; typename boost::asio::constraint<boost::asio::detail::async_result_has
D:\utils\MinGW\include/boost/asio/async_result.hpp:856:29:   required from 'typename boost::asio::constraint<boost::asio::detail::async_result_has_initiate_memfn<CompletionToken, Signatures>::value, decltype (boost::asio::async_result<typename std::decay<_Tp>::type, Signatures ...>::initiate(declvaTp>::type, Signatures ...>::initiate(declval<Initiation&&>(), declval<CompletionToken&&>(), (declval<Al<Initiation&&>(), declval<CompletionToken&&>(), (declval<Args&&>)()...))>::type boost::asio::async_initiate(Initiation&&, CompletionToken&, Args&& ...) [with CompletionToken = std::_Bind<std::function<void(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>; Signatures = {void()}; Initiation = boost::asio::io_context::initiate_post; Args = {boost::asio::io_context*}; typename boost::asio::constraint<boost::asio::detail::async_result_has_initiate_memfn<CompletionToken, Signatures>::value, decltype (boost::asio::async_result<typena:asio::ip::tcp>)>]'me std::decay<_Tp>::type, Signatures ...>::initiate(declval<Initiation&&>(), declval<CompletionToken&&>(), (declval<Args&&>)()...))>::type = void; decltype (boost::asio::async_result<typename std::decay<_Tp>::type, Signatures ...>::initiate(declval<Initiation&&>(), declval<CompletionToken&&>(), (declval<Args&&>)()...)) = void; typename std::decay<_Tp>::type = std::decay<std::_Bind<std::function<void(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)> >::type]'
D:\utils\MinGW\include/boost/asio/impl/io_context.hpp:200:58:   required from 'auto boost::asio::io_context::post(LegacyCompletionHandler&&) [with LegacyCompletionHandler = std::_Bind<std::function<void(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>]'
.\acceptor.cpp:10:27:   required from here
d:\utils\mingw\include\c++\11.2.0\functional:464:15: error: no type named 'type' in 'struct std::result_of<const volatile std::function<void(boost::asio::basic_stream_socket<boost::asio::ip::tcp>)>&(const volatile boost::asio::basic_stream_socket<boost::asio::ip::tcp>&)>'
  464 |         using _Res_type_impl
      |               ^~~~~~~~~~~~~~

In the line 173 of "boost/asio/impl/io_context.hpp", there is a comment says:

// If you get an error on the following line it means that your handler does
// not meet the documented type requirements for a LegacyCompletionHandler.

Here is my codes:

acceptor.h

#ifndef ACCEPTOR_H
#define ACCEPTOR_H

#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/io_service.hpp>

typedef 
    std::function<void(boost::asio::ip::tcp::socket)>
        connection_handler;

class acceptor {
private:
    boost::asio::io_service &_io_service;
    boost::asio::ip::tcp::acceptor _acceptor;
    connection_handler _connection_handler;
    std::function<void (
        const boost::system::error_code&,
        boost::asio::ip::tcp::socket
    )> _accept_handler;
private:
    void accept_handler(
        const boost::system::error_code& error,
        boost::asio::ip::tcp::socket peer
    );
public:
    acceptor(
        std::string ipv4_addr,
        int port, 
        boost::asio::io_service &io_service, 
        connection_handler handler
    );
    void start_accept();
};

#endif /* ACCEPTOR_Hs */

acceptor.cpp

#include <iostream>

#include "acceptor.h"

void acceptor::accept_handler(
    const boost::system::error_code& error,
    boost::asio::ip::tcp::socket peer
){
    this->_acceptor.async_accept(this->_accept_handler);
    this->_io_service.post(
        std::bind(this->_connection_handler, std::move(peer))
    );
}

acceptor::acceptor(
    std::string ipv4_addr, 
    int port, 
    boost::asio::io_service &io_service, 
    connection_handler handler
)
:_connection_handler(handler),
_io_service(io_service),
_acceptor(
    boost::asio::ip::tcp::acceptor(
        io_service,
        boost::asio::ip::tcp::endpoint(
            boost::asio::ip::address_v4::from_string(ipv4_addr),
            port
        )
    )
),
_accept_handler(
    std::bind(
        &acceptor::accept_handler, 
        this, 
        std::placeholders::_1, 
        std::placeholders::_2
    )
){}

void acceptor::start_accept(){
    this->_acceptor.async_accept(this->_accept_handler);
}

myhttpd.cpp

#include <iostream>

#include "acceptor.h"

void handler(boost::asio::ip::tcp::socket socket) {
    std::cout << "connected" << std::endl;
}

int main(int argc, char *argv[]) {
    boost::asio::io_service _io_service;
    boost::asio::io_service::work work(_io_service);
    acceptor ac("127.0.0.1", 10000, _io_service, &handler);
    ac.start_accept();
    _io_service.run();
}

Am i doing something wrong? I'm sorry if my grammar confuses you, my English is not very good. Any help i will appreciated.

how post and pre increment works with multiplication operator?

   i am having problem postfix and prefix works with multiplication operator
              x = 5;
              y = ++x * ++x;

as it's is prefix it will change and then use it so it should be like this y =6*7=42 but that's not the case it using same value for both incremented x i.e. y =7 * 7 =49

    #include<iostream>
        
            using namespace std;
        
            int main ()
        
            {
             int x, y;
                x = 5;
              y = ++x * ++x; //y =6*7=42 but output shows y=7 * 7=49
        
              cout << x<< y<<endl;
        
                x = 5;
        
                y = x++ * ++x; // y= 5 * 7= 35 which is correct 
        
                cout << x << y;
        
                return 0;
        
            }
    
    output:749
           735

SFINAE unresolved external symbol when putting definition in src file

I have the following preprocessor class, for which I would like to have separate implementations for Real or complex data.

PreProcessor.cuh

#ifndef __PREPROCESSOR_TEST_CUH__
#define __PREPROCESSOR_TEST_CUH__

#include <cuda/std/complex>
#include <iostream>

#define DEFINITION_IN_HEADER 1 // change between definition in src or header file

typedef cuda::std::complex<float> ccfloat;
typedef cuda::std::complex<double> ccdouble;

template <template <class...> class TT, class... Args>
std::true_type is_tt_impl(TT<Args...>);
template <template <class...> class TT>
std::false_type is_tt_impl(...);

// use as is_tt<cuda::std::complex, Q>::value
template <template <class...> class TT, class T>
using is_tt = decltype(is_tt_impl<TT>(std::declval<typename std::decay<T>::type>()));

template <typename Tin, typename Tout>
class PreProcessor
{
  public:
    // specialization for complex input
    template <typename Q = Tin>
    typename std::enable_if_t<is_tt<cuda::std::complex, Q>::value, void> run();

    // specialization for real input
    template <typename Q = Tin>
    typename std::enable_if_t<!is_tt<cuda::std::complex, Q>::value, void> run();
};

#if DEFINITION_IN_HEADER
// specialization for complex input
template <typename Tin, typename Tout>
template <typename Q>
typename std::enable_if_t<is_tt<cuda::std::complex, Q>::value, void> PreProcessor<Tin, Tout>::run()
{
    std::cout << "COMPLEX template." << std::endl;
}

// specialization for real input
template <typename Tin, typename Tout>
template <typename Q>
typename std::enable_if_t<!is_tt<cuda::std::complex, Q>::value, void> PreProcessor<Tin, Tout>::run()
{
    std::cout << "REAL template." << std::endl;
}
#endif

#endif //!__PREPROCESSOR_TEST_CUH__

If I define the respective implementations in the header file, all is good. But when I define them in a source file (i.e. DEFINITION_IN_HEADER =0):

PreProcessor.cu

#include "PreProcessor.cuh"

#if !DEFINITION_IN_HEADER

// specialization for complex input
template <typename Tin, typename Tout>
template <typename Q>
typename std::enable_if_t<is_tt<cuda::std::complex, Q>::value, void> PreProcessor<Tin, Tout>::run()
{
    std::cout << "COMPLEX template." << std::endl;
}

// specialization for real input
template <typename Tin, typename Tout>
template <typename Q>
typename std::enable_if_t<!is_tt<cuda::std::complex, Q>::value, void> PreProcessor<Tin, Tout>::run()
{
    std::cout << "REAL template." << std::endl;
}

// instantiation
template class PreProcessor<ccfloat, ccfloat>;
template class PreProcessor<int, int>;

#endif

I get the following error:

[build] main.obj : error LNK2019: unresolved external symbol "public: void __cdecl PreProcessor<class cuda::std::__4::complex<float>,class cuda::std::__4::complex<float> >::run<class cuda::std::__4::complex<float> >(void)" (??$run@V?$complex@M@__4@std@cuda@@@?$PreProcessor@V?$complex@M@__4@std@cuda@@V1234@@@QEAAXXZ) referenced in function "public: void __cdecl Processor<class cuda::std::__4::complex<float>,class cuda::std::__4::complex<float> >::run(void)" (?run@?$Processor@V?$complex@M@__4@std@cuda@@V1234@@@QEAAXXZ)

Or, a bit more readable when I use Processor<int, int> Preal;. What is going on, can I not move SFINAE template speciliazations to src files?

[build] main.obj : error LNK2019: unresolved external symbol "public: void __cdecl PreProcessor<int,int>::run<int>(void)" (??$run@H@?$PreProcessor@HH@@QEAAXXZ) referenced in function "public: void __cdecl Processor<int,int>::run(void)" (?run@?$Processor@HH@@QEAAXXZ)

My main:

main.cu


#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include <cuda.h>
#include <cuda/std/complex>

#include "PreProcessor_test.cuh"

template <typename Tin, typename Tout>
class Processor
{
  public:
    PreProcessor<Tin, Tout> *Pp;
    Processor() { Pp = new PreProcessor<Tin, Tout>; }
    ~Processor() { delete Pp; }
    void run() { Pp->run(); }
};

int main()
{
    Processor<int, int> Preal;
    Preal.run();

    using ccfloat = cuda::std::complex<float>;
    Processor<ccfloat, ccfloat> Pcomplex;
    Pcomplex.run();
    return 0;
}

Execute stored procedure with Input and Output parameter with pqxx postgress edb c++

How to execute stored procedures of postgress edb using pqxx c++ library, Procedure contains both INPUT and OUTPUT parameters

Example Procedure: PROCEDURE ExampleProcedure(IN inVariable character varying, OUT outVar numeric);

mardi 19 juillet 2022

Trying to count the number of lines in a file but it returns other numbers? [closed]

I've been trying to count the number of lines within a file as such:

regex cityLocationRegex (R"(/(\[(\d+).*\s(\d+)]-(\d+)-(.+)*))");
regex cloudCoverRegex (R"(\[(\d+), (\d+)]-(\d+))");
regex pressureRegex (R"(\[(\d+), (\d+)]-(\d+))");

// to open the file & count the number of lines within the file

// citylocation.txt
ifstream inputCLFile; 
inputCLFile.open(cityLocationFile.c_str());
if (inputCLFile.is_open())
{
    while (getline (inputCLFile, fileline))
    {
        if (regex_search(fileline, match, cityLocationRegex))
        {
            cityLocationCount++;
        }
    }
    }
inputCLFile.close();

// cloudcover.txt
ifstream inputCCFile; // input file stream
inputCCFile.open(cloudCoverFile.c_str());
if (inputCCFile.is_open())
{
    while (getline (inputCCFile, fileline))
    {
        if (regex_search(fileline, match, cloudCoverRegex))
        {
            cloudCoverCount++;
        }
    }
}
inputCCFile.close();    
    
// pressure.txt
ifstream inputPressureFile; // input file stream
inputPressureFile.open(pressureFile.c_str());
if (inputPressureFile.is_open())
{
    while (getline (inputPressureFile, fileline))
    {
        if (regex_search(fileline, match, pressureRegex))
        {
            pressureCount++;        
        }
    }
}
inputPressureFile.close();



cout << "City location count: " << cityLocationCount << endl;
cout << "Cloud cover count: " << cloudCoverCount << endl;
cout << "Pressure count: " << pressureCount << endl;

Results:

City location count: 32775 // supposed to be 14
Cloud cover count: -981987855 // supposed to be 81
Pressure count: 81 //correct

Sample of lines within files:

  • citylocation.txt:

    • [3, 3]-3-Big_City
    • [3, 7]-2-Mid_City
  • cloudcover.txt:

    • [0, 4]-70
    • [0, 5]-39
  • pressure.txt:

    • [2, 1]-42
    • [2, 2]-17

I've checked the regex and it does manage to match to the files I have, so I'm not too sure why this is happening. Could someone kindly enlighten me as to what I did wrong?

C++ integration Qt

So I wrote a Qt quick application that takes user inputs and stores them in a json file. I now want to add a feature that lets me recall the data in my file and display it in a text field within my application. I can get the text in the C++ portion of my application, Im just not sure how to display it in my user interface. Here is the code to get the text from my json file.

void Jsonfile:: display(){

    //1. Open the QFile and write it to a byteArray and close the file
    QFile file;
    file.setFileName("data.json");
    if(!file.open(QIODevice::ReadOnly)){
        qDebug() << "file couldn't be opened/found";
        return;
    }

    QByteArray byteArray;
    byteArray = file.readAll();
    file.close();

    //2. Format the content of the byteArray as QJsonDocument
    //and check on parse Errors
    QJsonParseError parseError;
    QJsonDocument jsonDoc;
    jsonDoc = QJsonDocument::fromJson(byteArray, &parseError);
    if(parseError.error != QJsonParseError::NoError){
           qWarning() << "Parse error at " << parseError.offset << ":" << parseError.errorString();
           return;
       }
    QTextStream textStream(stdout);
    textStream << jsonDoc.toJson(QJsonDocument::Indented);


}

How to wrap a shared pointer of a template class function in Pybind11

I want to wrap a shared pointer of a template class function in Pybind11. My class is a template queue : MyQueue.hpp

template<typename Data>
class MyQueue {
    public:
        std::queue <Data> the_queue;
        static std::shared_ptr<MyQueue<Data>> make_data_q_ptr();
};

MyQueue.cpp

template<typename Data>
std::shared_ptr<MyQueue<Data>> MyQueue<Data>::make_data_q_ptr(){
    std::shared_ptr<MyQueue<Data>> data_q_ptr;
    data_q_ptr = std::make_shared<MyQueue<Data>>();
    return data_q_ptr;
}

The type of data in MyQueue : DataType.cpp

class DataType
{
    public:
        uint mynumber;
};

The wrapper using Pybind11 : wrap.cpp

namespace py = pybind11;

PYBIND11_MODULE(mymodule, m){
    
    py::class_<MyQueue<DataType>, std::shared_ptr<MyQueue<DataType>>>(m, "MyQueue_DataType")
            .def(py::init<>())
            .def_static("make_data_q_ptr",&MyQueue<DataType>::make_data_q_ptr);
            
    py::class_<DataType>(m, "DataType")
            .def(py::init<>())
            .def_readwrite("mynumber",&DataType::mynumber);
}

Command to compile the code

g++ -shared -fPIC `pkg-config --cflags --libs opencv` -lpthread -std=c++11 -I./pybind11/include/ `python3.7 -m pybind11 --includes` *.cpp -o mymodule.so `python3.7-config --ldflags`

The code gets compiled successfully, but when I try to import the module that I created "mymodule", I get this error: ImportError: undefined symbol: xxx

>>> import mymodule
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: /home/pi/templedpybind11/mymodule.so: undefined symbol: _ZN7MyQueueI8DataTypeE15make_data_q_ptrEv

Can you please help me out? Thank you.

Program will exit after running a specific function in C++. Unable to figure out why

I have this function that will split the string. After running it in a while loop of read file, the program will exit instead of continue the next step of functions.

vector <string> splitString (string str, string delim){
vector <string> result; 
size_t pos = 0; 
string token;

while ((pos = str.find(delim)) != std::string::npos){
    token = str.substr(0, pos);
    result.push_back(token);
    str.erase(0, pos+delim.length());
}

if (!str.empty())
    result.push_back(str);

return (result);
}

void readCityLocation(int ** cityMap){
ifstream inFile;
inFile.open(filename[0]);
string line;
while (getline(inFile, line)){
    int xCoordinate;
    int yCoordinate;

    string xValue;
    string yValue;
    
    //Get xCoordinate...
    vector <string> splitThis = splitString(line,",");

    xValue = splitThis[0];

    cout << line;

}

An function called option2(), will create a table and call void readCityLocation( )

void option2(){
cout << endl << endl;
int ** table = new int * [gridXEnd + 1];
for (int i = 0; i < gridXEnd + 1; i++) {
    table[i] = new int[gridYEnd + 1];
}

//Initialize all the array value in table to be 0
for (int i = 0; i < gridXEnd + 1; i++) {
    for (int j = 0; j < gridYEnd + 1; j++) {
        table[i][j] = 0;

        //To be remove: Error Handling
        //cout << table[i][j] <<  " Grid X: " << i << " Grid Y: " << j << endl;
    }
}

readCityLocation(table);
}

I am fairly new to all this and can't figure out whats the problem. Any assistance is appreciated. Thank you.

C++ 11 - If I initialize a variable in a class header file, is a default constructor generated?

Here is a short example of a class with a variable myInteger which is not initialized in the single constructor which has been defined.

// A.h

class A
{
    public:
        
    A(const std::string& str);

    private:

    int myInteger;
};


// A.cpp

A::A(const string& str)
{
    // I do something with str
}

A single constructor is defined, which means that the compiler will not generate a default constructor with no arguments.

  • Question: If the header file is changed so that the variable myInteger is set to a value, does the compiler generate a new default constructor?
// A.h

class A
{
    public:
        
    A(const std::string& str);

    private:

    int myInteger = 3;
};
  • Question: If the header file is changed so that the variable myInteger is set to a value, does the compiler modify the behavior of the constructor defined above to be like the following?
A::A(const string& str)
    : myInteger{3}
{
    // I do something with str
}

I checked Effective Modern C++ for an answer to this question but couldn't find it in there. It is a bit of an unusual question.

lundi 18 juillet 2022

conflicting declaration for typedef when using C header in C++ application

There is a header file say header1.h from a C library. In header1.h,

  51 enum ConnectionState {
  52     InProgress = 0,
  53     BannerWaitEol = 1,
  54     BannerDone = 2,
  55     Finished = 3,
  56 };
  57 typedef uint8_t ConnectionState;

I use it in my C++ code as

extern "C"
{
#include "header1.h"
}

But I got a compile error

header1.h:57:17: error: conflicting declaration 'typedef uint8_t ConnectionState'
 typedef uint8_t ConnectionState;
                 ^~~~~~~~~~~~~~~~~~
header1.h:51:6: note: previous declaration as 'enum ConnectionState'
 enum ConnectionState {
      ^~~~~~~~~~~~~~~~~~

I read the post: Conflicting declaration in c++. And now I understand it is the typedef difference between C and C++. But I can not change header1.h because it is from a third-party library. How do I use this header1.h in my C++ application? Thank you for your help.

Does calling a member variable of constexpr struct omits a whole constructor evaluation?

Let's say I have the following structure:

struct MyData {
    int minSteps{1};
    int maxSteps{64};
    double volume{0.25/7};
};

constexpr MyData data()
{
    return MyData();
}

Does any of expressions below make an instance of the MyData structure constructed somewhere before the value is assigned?

int steps = data().minSteps;
const int maxSteps = data().maxSteps;
constexpr double volume = data().volume;

dimanche 17 juillet 2022

Using "override" specifier

ALL,

In my program I'm using a library which uses macros.

One of the macros is using virtual function.

Now every time I'm making a child of the class I'm getting an error about missing override, since I'm building in C++11+.

Is there an easy way to fix such a warning without changing the library code significantly?

Or I'm out of luck and have to bite the bullet and replace all macro instances with the full implementation?

Thank you.

Calculation of large numbers C++11

I'm trying to find the point where 2 lines intersect. I am using this example on geeks for geeks.

This works well for small numbers. I am using "accurate" latitude and longitude points which are scaled by 10000000. So a latitude of 40.4381311 would be 404381311 in my program. I can't use double as I will lose accuracy and the whole point of getting the points scaled like this is for accuracy.

So in the geeks for geeks example I changed everywhere they use double to use int64_t. But unfortunately this is still not enough.

By the time you get to:

double determinant = a1*b2 - a2*b1;

or:

double x = (b2*c1 - b1*c2)/determinant;
double y = (a1*c2 - a2*c1)/determinant;

The number will be too big for int64_t. What is my best way around this issue while still keeping accuracy.

I am writing this code for an ESP32 and it doesn't seem to have __int128/__int128_t.

Thanks!

How to create map of a map as a key in C++ like in Java

In java, I can create a Map of a Map as following:

Map<Map<String, Integer>, List<String>> m = new HashMap<>();

Can I and if yes, How can I do similar in C++?

I tried doing

   unordered_map<unordered_map<char, int>, vector<string>> m;

and I am getting compilation error as:

Line 4: Char 65: error: call to implicitly-deleted default constructor of 'unordered_map<unordered_map<char, int>, vector<std::string>>' (aka 'unordered_map<unordered_map<char, int>, vector<basic_string<char>>>')
        unordered_map<unordered_map<char, int>, vector<string>> m;
                                                                ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/unordered_map.h:141:7: note: explicitly defaulted function was implicitly deleted here
      unordered_map() = default;
      ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/unordered_map.h:105:18: note: default constructor of 'unordered_map<std::unordered_map<char, int, std::hash<char>, std::equal_to<char>, std::allocator<std::pair<const char, int>>>, std::vector<std::__cxx11::basic_string<char>, std::allocator<std::__cxx11::basic_string<char>>>, std::hash<std::unordered_map<char, int, std::hash<char>, std::equal_to<char>, std::allocator<std::pair<const char, int>>>>, std::equal_to<std::unordered_map<char, int, std::hash<char>, std::equal_to<char>, std::allocator<std::pair<const char, int>>>>, std::allocator<std::pair<const std::unordered_map<char, int, std::hash<char>, std::equal_to<char>, std::allocator<std::pair<const char, int>>>, std::vector<std::__cxx11::basic_string<char>, std::allocator<std::__cxx11::basic_string<char>>>>>>' is implicitly deleted because field '_M_h' has a deleted default constructor
      _Hashtable _M_h;
                 ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/hashtable.h:414:7: note: explicitly defaulted function was implicitly deleted here
      _Hashtable() = default;
      ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/hashtable.h:174:7: note: default constructor of '_Hashtable<std::unordered_map<char, int, std::hash<char>, std::equal_to<char>, std::allocator<std::pair<const char, int>>>, std::pair<const std::unordered_map<char, int, std::hash<char>, std::equal_to<char>, std::allocator<std::pair<const char, int>>>, std::vector<std::__cxx11::basic_string<char>, std::allocator<std::__cxx11::basic_string<char>>>>, std::allocator<std::pair<const std::unordered_map<char, int, std::hash<char>, std::equal_to<char>, std::allocator<std::pair<const char, int>>>, std::vector<std::__cxx11::basic_string<char>, std::allocator<std::__cxx11::basic_string<char>>>>>, std::__detail::_Select1st, std::equal_to<std::unordered_map<char, int, std::hash<char>, std::equal_to<char>, std::allocator<std::pair<const char, int>>>>, std::hash<std::unordered_map<char, int, std::hash<char>, std::equal_to<char>, std::allocator<std::pair<const char, int>>>>, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_hash, std::__detail::_Prime_rehash_policy, std::__detail::_Hashtable_traits<true, false, true>>' is implicitly deleted because base class '__detail::_Hashtable_base<unordered_map<char, int, hash<char>, equal_to<char>, allocator<pair<const char, int>>>, pair<const unordered_map<char, int, hash<char>, equal_to<char>, allocator<pair<const char, int>>>, vector<basic_string<char>, allocator<basic_string<char>>>>, _Select1st, equal_to<unordered_map<char, int, hash<char>, equal_to<char>, allocator<pair<const char, int>>>>, hash<unordered_map<char, int, hash<char>, equal_to<char>, allocator<pair<const char, int>>>>, _Mod_range_hashing, _Default_ranged_hash, _Hashtable_traits<true, false, true>>' has a deleted default constructor
    : public __detail::_Hashtable_base<_Key, _Value, _ExtractKey, _Equal,
      ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/hashtable_policy.h:1822:5: note: explicitly defaulted function was implicitly deleted here
    _Hashtable_base() = default;
    ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/hashtable_policy.h:1771:5: note: default constructor of '_Hashtable_base<std::unordered_map<char, int, std::hash<char>, std::equal_to<char>, std::allocator<std::pair<const char, int>>>, std::pair<const std::unordered_map<char, int, std::hash<char>, std::equal_to<char>, std::allocator<std::pair<const char, int>>>, std::vector<std::__cxx11::basic_string<char>, std::allocator<std::__cxx11::basic_string<char>>>>, std::__detail::_Select1st, std::equal_to<std::unordered_map<char, int, std::hash<char>, std::equal_to<char>, std::allocator<std::pair<const char, int>>>>, std::hash<std::unordered_map<char, int, std::hash<char>, std::equal_to<char>, std::allocator<std::pair<const char, int>>>>, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_hash, std::__detail::_Hashtable_traits<true, false, true>>' is implicitly deleted because base class '_Hash_code_base<std::unordered_map<char, int, std::hash<char>, std::equal_to<char>, std::allocator<std::pair<const char, int>>>, std::pair<const std::unordered_map<char, int, std::hash<char>, std::equal_to<char>, std::allocator<std::pair<const char, int>>>, std::vector<std::__cxx11::basic_string<char>, std::allocator<std::__cxx11::basic_string<char>>>>, std::__detail::_Select1st, std::hash<std::unordered_map<char, int, std::hash<char>, std::equal_to<char>, std::allocator<std::pair<const char, int>>>>, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_hash, _Hashtable_traits<true, false, true>::__hash_cached::value>' has a deleted default constructor
  : public _Hash_code_base<_Key, _Value, _ExtractKey, _H1, _H2, _Hash,
    ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/hashtable_policy.h:1373:7: note: explicitly defaulted function was implicitly deleted here
      _Hash_code_base() = default;
      ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/hashtable_policy.h:1349:7: note: default constructor of '_Hash_code_base<std::unordered_map<char, int, std::hash<char>, std::equal_to<char>, std::allocator<std::pair<const char, int>>>, std::pair<const std::unordered_map<char, int, std::hash<char>, std::equal_to<char>, std::allocator<std::pair<const char, int>>>, std::vector<std::__cxx11::basic_string<char>, std::allocator<std::__cxx11::basic_string<char>>>>, std::__detail::_Select1st, std::hash<std::unordered_map<char, int, std::hash<char>, std::equal_to<char>, std::allocator<std::pair<const char, int>>>>, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_hash, true>' is implicitly deleted because base class '_Hashtable_ebo_helper<1, std::hash<std::unordered_map<char, int, std::hash<char>, std::equal_to<char>, std::allocator<std::pair<const char, int>>>>>' has a deleted default constructor
      private _Hashtable_ebo_helper<1, _H1>,
      ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/hashtable_policy.h:1096:7: note: explicitly defaulted function was implicitly deleted here
      _Hashtable_ebo_helper() = default;
      ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/hashtable_policy.h:1094:7: note: default constructor of '_Hashtable_ebo_helper<1, std::hash<std::unordered_map<char, int, std::hash<char>, std::equal_to<char>, std::allocator<std::pair<const char, int>>>>, true>' is implicitly deleted because base class 'std::hash<std::unordered_map<char, int, std::hash<char>, std::equal_to<char>, std::allocator<std::pair<const char, int>>>>' has a deleted default constructor
    : private _Tp
      ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/functional_hash.h:101:19: note: default constructor of 'hash<std::unordered_map<char, int, std::hash<char>, std::equal_to<char>, std::allocator<std::pair<const char, int>>>>' is implicitly deleted because base class '__hash_enum<std::unordered_map<char, int, std::hash<char>, std::equal_to<char>, std::allocator<std::pair<const char, int>>>>' has no default constructor
    struct hash : __hash_enum<_Tp>
                  ^

Making a template class for a State manager

i am trying to make a statemanager class to manage my program.

I have the current code:

CPP

#include "StateManager.hpp"

template <class T>
StateManager<T>::StateManager() {}

template <class T>
StateManager<T>::~StateManager() {}

template <class T>
void StateManager<T>::setState(T state)
{
    _current_state = state;
}

/*
 * Get States
 * Returns the current state of the device
 */
template <class T>
T StateManager<T>::getCurrentState()
{
    return _current_state;
}

HPP

#ifndef STATEMANAGER_HPP
#define STATEMANAGER_HPP
#include <Arduino.h>

/*
 * StateManager
 * All Project States are managed here
 */
class ProgramStates
{
public:
    struct DeviceStates
    {
        enum State_e
        {
            Starting,
            Started,
            Stopping,
            Stopped,
            Error

        };

        enum WiFiState_e
        {
            WiFiState_None,
            WiFiState_Connecting,
            WiFiState_Connected,
            WiFiState_Disconnected,
            WiFiState_Disconnecting,
            WiFiState_Error
        };

        enum WebServerState_e
        {
            WebServerState_None,
            WebServerState_Starting,
            WebServerState_Started,
            WebServerState_Stopping,
            WebServerState_Stopped,
            WebServerState_Error
        };

        enum MDNSState_e
        {
            MDNSState_None,
            MDNSState_Starting,
            MDNSState_Started,
            MDNSState_Stopping,
            MDNSState_Stopped,
            MDNSState_Error
        };

        enum CameraState_e
        {
            Camera_Success,
            Camera_Connected,
            Camera_Disconnected,
            Camera_Error
        };

        enum ButtonState_e
        {
            Buttons_OFF,
            Buttons_ON,
            Buttons_PLUS,
            Buttons_MINUS,
            Buttons_Error
        };

        enum StreamState_e
        {
            Stream_OFF,
            Stream_ON,
            Stream_Error
        };
    };
};

/*
 * EventManager
 * All Project Events are managed here
 */
template <class T>
class StateManager
{
public:
    StateManager();
    virtual ~StateManager();

    void setState(T state);

    T getCurrentState();

private:
    static T _current_state;
};

#endif // STATEMANAGER_HPP

Everything compiles, but does not link. I get undefined references when trying to use the statemanager methods.

Ex usage

StateManager<ProgramStates::DeviceStates::MDNSState_e> mdns_stateManager;
StateManager<ProgramStates::DeviceStates::WiFiState_e> wifi_stateManager;

WiFiHandler::setupWifi(ssid, password, &wifi_stateManager);
MDNSHandler::setupMDNS(MDSNTrackerName, &mdns_stateManager);

These two methods accept an argument of a class object, allowing me to pass a reference to it. However, i get undefiend on the class instationation and on calling the methods inside of the receiving classes. My intellisense shows no errors and the code compiles but does not link. I am still new to c++, and am learning - so it's probably an obvious mistake.

Ignore false positives on std::future in valgrind (DRD)

I am writing some library code using std::future used to "beam" execution context of a lambda (or std::function /TBP) to another thread in order to avoid data races (because that std::function's operation would almost entirely be related to data managed by the other thread). This is basically the reference example usage of std::promise/std::future along with explicit exception passing, see below for the code structure.

However, when testing with DRD (from Valgrind tools), I see strange data races reported. According to https://en.cppreference.com/w/cpp/thread/promise/set_value and https://en.cppreference.com/w/cpp/thread/promise/get_future all this is supposed to be fine and not require any additional synchronization. For testing purposes, I have even added a std::mutex and lock_guard around promise/future access and the results were even more confusing, then my own mutex was reported as cause of the conflicting operations. I tried with GCC 12 and Clang 13, same picture.

So why does valgrind mark std::promise/std::future operations as unsafe and how can I work around that? Is there a way to whitelist/justify/hide that?

(This is Debian OS btw, libstdc++6 12.1.0-5)


==45452== Thread 2:
==45452== Conflicting load by thread 2 at 0x05c64800 size 4
==45452==    at 0x4928B55: load (atomic_base.h:488)
==45452==    by 0x4928B55: _M_load (atomic_futex.h:86)
==45452==    by 0x4928B55: std::__atomic_futex_unsigned<2147483648u>::_M_load_and_test_until(unsigned int, unsigned int, bool, std::memory_order, bool, std::chrono::duration<long, std::ratio<1l, 1l> >, std::chrono::duration<long, std::ratio<1l, 1000000000l> >) (atomic_futex.h:113)
==45452==    by 0x49287FC: std::__atomic_futex_unsigned<2147483648u>::_M_load_and_test(unsigned int, unsigned int, bool, std::memory_order) (atomic_futex.h:158)
==45452==    by 0x4928697: _M_load_when_equal (atomic_futex.h:212)
==45452==    by 0x4928697: std::__future_base::_State_baseV2::wait() (future:337)
==45452==    by 0x4959849: std::__basic_future<unsigned long>::_M_get_result() const (future:720)
==45452==    by 0x4955E55: std::future<unsigned long>::get() (future:806)
==45452==    by 0x4954AD5: RunOnIoThread(std::function<unsigned long ()>, unsigned long) (schedlib.cc:335)
...
==45452== Address 0x5c64800 is at offset 32 from 0x5c647e0. Allocation context:
==45452==    at 0x484514F: operator new(unsigned long) (in /usr/libexec/valgrind/vgpreload_drd-amd64-linux.so)
==45452==    by 0x4925A4C: std::__new_allocator<std::_Sp_counted_ptr_inplace<std::__future_base::_State_baseV2, std::allocator<void>, (__gnu_cxx::_Lock_policy)2> >::allocate(unsigned long, void const*) (new_allocator.h:137)
==45452==    by 0x49259A0: allocate (allocator.h:183)
==45452==    by 0x49259A0: std::allocator_traits<std::allocator<std::_Sp_counted_ptr_inplace<std::__future_base::_State_baseV2, std::allocator<void>, (__gnu_cxx::_Lock_policy)2> > >::allocate(std::allocator<std::_Sp_counted_ptr_inplace<std::__future_base::_State_baseV2, std::allocator<void>, (__gnu_cxx::_Lock_policy)2> >&, unsigned long) (alloc_traits.h:464)
==45452==    by 0x4925840: std::__allocated_ptr<std::allocator<std::_Sp_counted_ptr_inplace<std::__future_base::_State_baseV2, std::allocator<void>, (__gnu_cxx::_Lock_policy)2> > > std::__allocate_guarded<std::allocator<std::_Sp_counted_ptr_inplace<std::__future_base::_State_baseV2, std::allocator<void>, (__gnu_cxx::_Lock_policy)2> > >(std::allocator<std::_Sp_counted_ptr_inplace<std::__future_base::_State_baseV2, std::allocator<void>, (__gnu_cxx::_Lock_policy)2> >&) (allocated_ptr.h:98)
==45452==    by 0x4925750: std::__shared_count<(__gnu_cxx::_Lock_policy)2>::__shared_count<std::__future_base::_State_baseV2, std::allocator<void>>(std::__future_base::_State_baseV2*&, std::_Sp_alloc_shared_tag<std::allocator<void> >) (shared_ptr_base.h:969)
==45452==    by 0x49256F6: std::__shared_ptr<std::__future_base::_State_baseV2, (__gnu_cxx::_Lock_policy)2>::__shared_ptr<std::allocator<void>>(std::_Sp_alloc_shared_tag<std::allocator<void> >) (shared_ptr_base.h:1712)
==45452==    by 0x49256B4: std::shared_ptr<std::__future_base::_State_baseV2>::shared_ptr<std::allocator<void>>(std::_Sp_alloc_shared_tag<std::allocator<void> >) (shared_ptr.h:464)
==45452==    by 0x49255F6: std::shared_ptr<std::__future_base::_State_baseV2> std::make_shared<std::__future_base::_State_baseV2>() (shared_ptr.h:1009)
==45452==    by 0x4955D08: std::promise<unsigned long>::promise() (future:1080)
==45452==    by 0x49549EB: RunOnIoThread(std::function<unsigned long ()>, unsigned long) (schedlib.cc:307)
...
==45452== Other segment start (thread 1)
==45452==    at 0x4854114: pthread_mutex_unlock (in /usr/libexec/valgrind/vgpreload_drd-amd64-linux.so)
==45452==    by 0x4914602: __gthread_mutex_unlock(pthread_mutex_t*) (gthr-default.h:779)
==45452==    by 0x4916D44: std::mutex::unlock() (std_mutex.h:118)
==45452==    by 0x4914807: std::lock_guard<std::mutex>::~lock_guard() (std_mutex.h:235)
==45452==    by 0x49546FA: PeekNewJobs(int, short, void*) (schedlib.cc:237)
... // this is basically the job processing on IO thread, taking scheduled tasks and running them
MyValues RunOnIoThread(std::function<MyValues()> act, MyValues onRejection = MyValues::INVOCATION_ERROR)
{
    if (!act) MyValues::BAD_ARGUMENT;
    // if called from IO thread, stay there
    if(ThisIsIoThread()) return act();

    std::promise<MyValues> pro;
    try {
        ScheduleOnIoThread([&]() {
            try {
                auto res = act();
                pro.set_value(res);
            }
            catch (...) { pro.set_exception(std::current_exception()); }
        });
    }
    catch (...) { return onRejection; }
    return pro.get_future().get(); // rethrows exception if stored there
}