samedi 31 juillet 2021

Unable to print a pointer in gdb. Am i facing a stack corruption

(gdb) p dst
$9 = (ad_opg__State *) 0x2995cef0
(gdb) p *dst
$10 = <incomplete type>
(gdb) p dst->state
There is no member named state.
(gdb)
(gdb) n
ad_trf::Serialize::serializeRecording (this=this@entry=0x859e00 <<ad_trf::RecordingFactory>::GetInstance()::instance+64>, src=0x2995f110) at Serialize.cpp:379
379                     dst->status = src->m_Status;
(gdb) p dst
$21 = (ad_opg__Recording *) 0x2995cef0
(gdb) p *dst
$22 = <incomplete type>
(gdb) p dst->state
There is no member named state.
(gdb) p *(0x2995cef0)
$23 = -2109491384
(gdb) 
(gdb) p/s  *(ad_opg__Recording *) 0x2995cef0
No symbol "ad_opg__Recording" in current context.
(gdb)

I feel the incomplete type is because these classes are in a separate module which hasn't got debug symbols enabled ( and i can't do it either because of lack of space in the filesystem. This is an embedded system with aarch64)

But i am interested to know if i am facing a stack corruption. Because i can atleast explore valgrind options instead.

In the snippet above, where I get this -

(gdb) p *(0x2995cef0)
$23 = -2109491384

Is this indicating stack corruption ? I am not getting into details of ad_opg__State or ad_opg__Recording and what the relationship between them are. It would help to know if i am facing a stack corruption from this gdb trace. Any help appreciated.

Problem with C++ class instance not being recognized

This is for "homework" but this is not an algorithm question, but rather a programming issue. As part of a project for my Data Structures class, I have to write a class to act as a database. That part is done. I am not asking about the algorithm, but rather, trying to isolate what is clearly a stupid bug on my part.

PeopleDB has two constructors, the default one and one that takes as a parameter an input file and reads it into the database to initialize it.

Here is the code snippet, the problem is described below it:

#include "People.h" // People class definition
#include "PeopleDB.h" // People database class
#include "PrecondViolatedExcep.h"

using namespace std;

int main(int argc, char *argv[])
{
    // Define variables
    string infilename;
    PeopleDB mydb;

    // Get the filename of the text file to process
    infilename = argv[1];

    // Try to open import the data into a database instance
    try
    {
        cout << "Attempting to import DB entries from "<< infilename << endl;
        PeopleDB mydb(infilename);
        cout << "# A total of "<< mydb.countEntries() << " DB entries loaded." << endl;
    }
    catch(PrecondViolatedExcep e)
    {
        cout << e.what() << endl;
        cout << "Exiting program.";
        exit(1);
    }

    // Display database contents
    cout << endl;
    cout << "# A total of "<< mydb.countEntries() << " DB entries found before display." << endl;

    return 0;
}  // end main

The problem is if I don't include the PeopleDB mydb; constructor at the top of the main() loop, the compiler barfs saying it doesn't recognize the mydb.countEntries() in the second to last line of the main loop. But if I do include it, it is clear that the mydb within the try loop doesn't survive because the output of the program is:

Attempting to import DB entries from testinput.txt
# A total of 7 DB entries loaded.

# A total of 0 DB entries loaded.

I didn't want to use the same variable (mydb) twice (I actually assumed this would error out during compiling), but for some reason creating the mydb instance of PeopleDB inside the try block doesn't seem to survive to be outside the block. I am sure this is something stupid on my part, but I am not seeing it. It has been a long day, so any suggestions would be appreciated.

c++ Swap function declared with a pointer parameter can be called with a value as a parameter but not an address? [duplicate]

I'm beginning with c++, I'm writing a program to sort array with int data type, with swap function as follows:

void swap(int *a, int *b){
    int m;
    m = *a;
    *a = *b;
    *b = m;
}

I know when calling swap function we have to pass parameter to it as an address (ex: swap(&a[i], &a[j]) but if I try passing parameter as a value (ex : swap(a[i], a[j]), swap function is working properly, I'm a bit confused about this, an explanation would help me a lot, many thanks

Sorry, I edited, here is my full source code

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<conio.h>
using namespace std;

void swap(int *a, int *b){
    int m;
    m = *a;
    *a = *b;
    *b = m;
}
void bubblesort(int * a, int n){
    for (int i = 0; i < n - 1; i++){
        for (int j = i + 1; j < n; j++){
            if (a[i] <= a[j]) swap(a[i], a[j]);
        }
    }
}
int main(){
    int aray[6] = {2,4,6,1,9,7};
    bubblesort(aray, 6);

    for (int i = 0; i < 6; i++)
    {
        cout << aray[i];
    }

    _getch();
    return 0;
}

Using templates to rewrite polymorphic class to one single class (compile time polymorphism)

In my current code I use runtime polymorphism to create different subtypes of "light" from a LightBase class. The lighttypes however are already known at compile time (preprocessor picks the right variant). So I figured it is really not the right tool to do so as it is slow (vtable lookup for virtual getter functions) and could be already done at compile time. I just don't know how... could it be done with templates? I don't have too much experience in template programming so I don't know what is possible.

Essentially I want to instantiate a subclass of either type NormalLight or SpecialLight which have the same functions as LightBase but operate on a different set of constants:

class Color
{
    Color(std::string color_name) : color_name_(color_name) { }
    private:
        std::string color_name_;
}

class LightBase {
    public:
        std::unique_ptr& GetInstance() { return instance_; }

    protected:
        const resolution;
        std::array<Color, 0> = {  };
    // ..

    private:
        static std::unique_ptr<LightBase> instance_;
}

class NormalLight : public LightBase
{
    protected:
        const resolution = 9;
        std::array<Color, 3> { Color("blue"), Color("red"), Color("purple") };
    // ..
}

class SpecialLight : public LightBase
{
    protected:
        const resolution = 13;
        std::array<Color, 3> { Color("yellow"), Color("magenta"), Color("orange") };
    // ..
}

#if defined CONFIG_LIGHT_TYPE_NORMAL
std::unique_ptr<LightBase> LightBase::instance_ = std::unique_ptr<NormalLight>(new NormalLight());
#elif defined CONFIG_LIGHT_TYPE_SPECIAL
std::unique_ptr<LightBase> LightBase::instance_ = std::unique_ptr<SpecialLight>(new SpecialLight());
#endif

In a function I could conditionally check for a template parameter (I guess) but it's a class definition. Also, the thing should compile in C++11. Any ideas?

How to unit test JNI Methods

I've been trying to expose some c++ native method in Rocksdb to the Java API. I got lost when it comes to testing the JNI code. I've searched a lot on the internet but didn't find much information in this regard. I've also looked a lot in the Rocksdb source code, but didn't find anything about how the other JNI Methods are unit-tested. Posted my question to the Rocksdb team on Google Groups here and got no answer yet.

Any help will be greatly appreciated.

vendredi 30 juillet 2021

Best way to find 'quite good' numbers up to 1 million?

I am working on an assignment involving 'quite good' numbers. The task describes them as:

"A "quite good" number is an integer whose "badness" – the size of the difference between the sum of its divisors and the number itself – is not greater than a specified value. For example, if the maximum badness is set at 3, there are 12 "quite good" numbers less than 100: 2, 3, 4, 6, 8, 10, 16, 18, 20, 28, 32, and 64; Your task is to write a C++ program, quitegood, that determines numbers of a specified maximum badness that are less than a specified value. The limiting value and maximum badness are specified as command-line arguments when the program is executed."

The task asks me to write a program that prints perfect numbers with a specified badness limit up to a million. So, the command line argument of quitegood 1000000 1 should print 2 4 6 8 16 28 32 64 128 256 496 512 1024 2048 4096 8128 8192 16384 32768 65536 131072 262144 524288.

I have gotten this to work with the following code

#include

using namespace std;

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

const int limit = argc > 1 ? atoi(argv[1]) : 1000000;
const int badness = argc > 2 ? atoi(argv[2]) : 10;

for(int number = 2; number < limit; number++) {
    int sum = 1;
    for (int factor = 2; factor < number; factor++){
        if (number % factor == 0) {
            sum += factor;
        }
    }

    if (number >= (sum - badness) && number <= (sum + badness)) {
        cout << number << " ";
    }
}

return 0;

}

The only issue is that this code is far too slow finding the 'quite good' numbers up to 1 million. Is there any way of optimising this?

Thank you

OnlineGDB c++ not compiling strcpy_s

I'm going to compile a very simple code on onlinegdb.com

The code is as below.

#include <stdio.h>
#include <string.h>

int main()
{
    char s[10] = {0};
    
    strcpy_s(s, 10, "1234567890");
    
    printf("%s", s);
    
    return 0;
}

I chose option Language as C++, C++14 and C++17, but all those are not compiling strcpy_s.

It says:

main.cpp: In function ‘int main()’:
main.cpp:16:33: error: ‘strcpy_s’ was not declared in this scope
     strcpy_s(s, 10, "1234567890");
                                 ^

I googled minutes, but there was no answer.

Doesn't gdb online support c compiler above c++11 ? Help me please. Thanks.

Issue reading inserted value from BIGINT column in Microsoft SQL server database from c++ application

I am trying to get the inserted ID in a BIGINT column from a query I execute from c++ application, the target database is Microsoft SQL server, and when I try to get the output ID value all I get is a weird value (2714419332062) and when check in the database the inserted values are '1', '2'... etc.

SQLHANDLE sqlStmtHandle = ReadFromDB(L"INSERT INTO [MyTable] ([Value])
                                       OUTPUT INSERTED.[ID]
                                       VALUES('TEST')");

SQLBIGINT insertID;
SQLLEN lenInsertID = 0;
SQLRETURN returnData;

SQLBindCol(sqlStmtHandle, 1, SQL_C_LONG, &insertID, 2, &lenInsertID);
returnData = SQLFetch(sqlStmtHandle);
if (returnData == SQL_SUCCESS || returnData == SQL_SUCCESS_WITH_INFO)
    do
    {
        cout << insertID << endl;
    } while (SQLFetch(sqlStmtHandle) != SQL_NO_DATA);

SQLFreeHandle(SQL_HANDLE_STMT, sqlStmtHandle);

Schema in SQL would be:

CREATE TABLE [MyTable] (
    [ID]        BIGINT  NOT NULL IDENTITY(1,1)
    ,[Value]    VARCHAR(512) NOT NULL)
GO

As a side note this code works if column ID is INT and I use SQLINTEGER for insertID. Also, if there is any small bug in the code (this is a VERY simplified version of the original code)

Accessing member of class through shared pointer

I am facing a issue, when I try to access members of class through shared pointer. The program runs fine and gives expected output "Name: Michel". But when I comment line marked as COMMENT_THIS_LINE, it gives some junk value instead of Michel. Can anybody explain this behavior, and how can I get correct output without the marked line?

class TestShared{
public:
        TestShared(std::string name);
        std::string getName(void);
private:
        std::string m_name;
};

class Another{
public:
        const char *name;
};
TestShared::TestShared(std::string name) : m_name(name)
{
}
std::string TestShared::getName(void)
{
        return m_name;
}

std::shared_ptr<TestShared> allocate_ts()
{
        char p[] = "Michel";
        return std::make_shared<TestShared>(p);
}

Another GetAnother(std::shared_ptr<TestShared>  ts)
{
        Another an;
        std::string a = ts->getName();    //////////COMMENT_THIS_LINE
        an.name = ts->getName().c_str();
        return an;
}

int main()
{
        std::shared_ptr<TestShared>  ts = allocate_ts();
        Another an = GetAnother(ts);
        printf("Name: %s\n", an.name);
        return 0;
}

How to encode string to make it shorter

we have unique Id which is formed with three things.

  • Time Microsecond level
  • UUID generated at that transaction level Any
  • User Given value max length size

Ex: "id": "2021-Jul-29 12:14:29.793225-8d4bcf4d-dd8a-4bb0-88e9-9db2f469e770XXXXXXXXXX"

Its total length is 74Character.

As this string will be stored in persistent in DB. I want to reduce this length. Is there is

how to read a specific value from a file in C++?

I an newbie in C++ programming, I need to write a code to read a particular value from a file. for example if enter input as servername then it has to show ABCDE-1. I am trying with string function I am not able to get the results. Will anyone help in writing the logic.

I am not able to copy and paste the file data and code that I have written to read and print the data. So, I am attaching in screenshot. In that first part is file data Thank you enter image description here

Is there a better way to code enable_if with std::chrono

I'm developing a time utils library with C++11 so that my colleagues can use it.

They all have been using C-style time APIs for a long time and are not familiar with std::chrono in C++11. So I want to write some basic functions. For example, count ticks of std::chrono:

template<typename T = std::chrono::milliseconds, typename = typename std::enable_if<
                          std::is_same<std::chrono::nanoseconds, T>::value ||
                          std::is_same<std::chrono::microseconds, T>::value ||
                          std::is_same<std::chrono::milliseconds, T>::value ||
                          std::is_same<std::chrono::seconds, T>::value ||
                          std::is_same<std::chrono::minutes, T>::value ||
                          std::is_same<std::chrono::hours, T>::value>::type>
inline uint64_t getTimeTicksInMS(const T &t) {
    return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
}

This function can count the number of time ticks with milliseconds. For example, getTimeTicksInMS(std::chrono::seconds{2}) will return 2000.

Now I want to make it more flexible.

template<typename V, typename T>
inline uint64_t getTimeTicks(const T &t) {
    return std::chrono::duration_cast<V>(t).count();
}

Now, it can return the number of ticks with any kind of time.

However, as you see, I removed the std::enable_if part, because it would become very long as I have two types now: T and V.

Is there some better way to code std::enable_if in this case without very long std::enable_if?

jeudi 29 juillet 2021

Need assistance resolving read access violation within a for loop

I am writing a program that will solve sudoku puzzles given a partially solved puzzle. In a for loop that I have composed to go through each element within a row, I am receiving a read access violation exception.

Here is the code that is causing the exception to be thrown:


bool sudoku::numAlreadyInRow(int row, int num)
{
    for (int j = 0; j < 9; j++) 
    {
        cout << "Before ";
        if (grid[row][j] == num)
        {
            cout << "Iterations: " << j;
            return true;
        }
          
    }
    return false;
}

If someone could help me to resolve this issue it would be greatly appreciated.

ETA: the exception says this was was 0xCE2DC5F6

When to use std::move() for std::string?

This is a bit loaded question since after reading about std::move(), I am more confused. std::move() will cast a variable to an rvalue.

My question.

  1. Does it make any sense to use std::move for primitive data type like std::string.

Now, if yes. Here is my code

std::string val;
Mypersist store();
store.restore(val);
setAttribute(val);
//after this I don't care about val. 


int Mypersist::store(std::string &value)
{

}

void setAttribute(const std::string &value)
{

}

I am already using reference rather than value copy so I am a bit confused if std::move makes sense here or not.

I have this in my mind.

Is using std::move(val) for setAttribute will help in performance? If so why?

std::string val;
Mypersist store();
store.restore(val);
setAttribute(std::move(val));
//after this I don't care about val. 

Move constructor needed, but not used, in array initialization with elements of class with deleted copy constructor

I apologize for the wordy title, but I'm having trouble concisely expressing this question.

I have a class with a deleted copy constructor and copy assignment operator. When I attempt to initialize an array with instances of the class I get a compiler error unless I provide a move constructor. However, the provided move constructor is not actually invoked.

Here's a MWE illustrating the issue.

#include <cstdio>
#include <string>

class A
{
public:
    explicit A(std::string s) : s_(s) { puts("constructor"); }
    A() = delete;
    ~A() = default;
    A(const A &other) = delete;
    A &operator=(const A &other) = delete;
    // A(A &&other) : s_(std::move(other.s_)) { puts("move constructor"); }

    void print_s() { printf("%s\n", s_.c_str()); }

private:
    std::string s_;
};

int main()
{
    A arr[]{A{"some"}, A{"string"}};
    for (auto &a : arr) {
        a.print_s();
    }
}

With the move constructor commented out as shown, I get the error:

> g++ file.cc -g -std=c++11 -o file && ./file
file.cc: In function ‘int main()’:
file.cc:22:32: error: use of deleted function ‘A::A(const A&)’
   22 |  A arr[]{A{"some"}, A{"string"}};
      |                                ^
file.cc:10:2: note: declared here
   10 |  A(const A &other) = delete;
      |  ^
file.cc:22:32: error: use of deleted function ‘A::A(const A&)’
   22 |  A arr[]{A{"some"}, A{"string"}};
      |                                ^
file.cc:10:2: note: declared here
   10 |  A(const A &other) = delete;
      |  ^

If I uncomment the move constructor I get the output

constructor
constructor
some
string

So, the move constructor does not actually appear to be invoked.

Why is the move constructor needed? Have I made a mistake somewhere (e.g., a poorly implemented move constructor)?

How to get GDB to show the source code while debugging?

To make gdb make use of a single source file, you can store it in the same directory where gdb is run. How about a complete folder ?

E.g. I have a folder called "bootup" with multiple subfolders and files in it. It generates a binary called "bootup" which I need to debug for a crash and also to understand code flow.

If i just have the bootup folder (containing the source code) in the path it doesn't seem to be enough. When i set a breakpoint and debug it still only shows the file as follows but not the source code.

(gdb)directory /root/bootup
Source directories searched: /root/bootup:/root:$cdir:$cwd
(gdb) n
141     in RecFns.cpp
(gdb)
142     in RecFns.cpp

RecFns.cpp is under /root/bootup/dir1/dir2/dir3/RecFns.cpp

What should I do to be able to get gdb printing the source file contents as I debug along. As per http://sourceware.org/gdb/onlinedocs/gdb/Source-Path.html, directory xyz should be able to make gdb search in the directory specified. But this isn't working for me.

How to put a condition where i could check if two strings are equal from two different files?

      fileone.txt

How to apply for financial aid? (file1var)

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

      file2two.txt

How to apply for financial aid? (file2var)

By going to the financial aid office (file2var2)

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

How do I check condition if a variable(f1var) for file 1(fileone.txt) is equal to the first variable(f2var) in file 2(filetwo.txt). And if they are equal, I am trying to output the 1st variable(f2var) and 2nd variable(f2var2) of file 2(filetwo.txt) as an output.

#include <iostream>
#include <string>
#include <fstream>
#include<stdlib.h>
#include<string.h>
#include<ctime>
using namespace std;


int main()
{
    
    string f1var;
    string f2var, f2var2;
    int counter;
    ifstream y("fileone.txt");
    ifstream x("filetwo.txt");
        while((getline(y,f1var) && getline(x,f2var);getlin(x,f2var2)
        {
                if(f1var==f2var)
                {
                        counter=1;
                }
        }
        y.close();
        x.close();
        if(counter==1){
            cout<<f2var<<f2var2<<endl;
        }

    return 0;
}

How to enable C++11 on windows?

"fatal error C1189: #error: LAMMPS requires a C++11 (or later) compliant compiler. Enable C++11 compatibility or upgrade the compiler" Whenever I try to run LAMMPS on windows, this error occurs. Any solutions would be highly appreciated.

How to verify if 2 string variables are equal from 2 different files?

      file1.txt

How to apply for financial aid? (file1var)

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

      file2.txt

How to apply for financial aid? (file2var)

By going to the financial aid office (file2var2)

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

I am trying to verify if the string variable(file1var) for file 1(file1.txt) is equal to the 1st string variable(file2var) in file 2(file2.txt). And if they are equal, I am trying to ouput the first variable(file2var) and second variable(file2var2) of file 2(file2.txt) in the terminal.

#include <iostream>
#include <string>
#include <fstream>
#include<stdlib.h>
#include<string.h>
#include<ctime>
using namespace std;


int main(){
    
    string file1var, file2var, file2var2;
    int count;
    ifstream y("file1.txt");
    ifstream x("file2.txt");
        while(y>>file1var && x>>file2var>>file2var2)
        {
                if(file1var==file2var)
                {
                        count=1;
                }
        }
        y.close();
        x.close();
        if(count==1){
            cout<<file2var<<file2var2<<endl;
        }

    return 0;
}

How to identify template parameters in Container1

I have a code as below. It fails in compilation, saying Container2 is ambiguous. How can I resolve it?

#include <vector>    
using namespace std;

template<class T, template<class...> class Container2, template<class...> class Container1>    
vector<T> catenate(Container1<Container2<T>> const& tss)
{
    vector<T> res;
    for (auto& ts : tss)
        res.insert(res.end(), ts.begin(), ts.end());
    return res;
}

int main()
{
    vector<vector<int>> vv;
    catenate(vv);
}

Alternatives to normal polymorphism in embedded?

I've got a problem in my project for which polymorphism with heap allocation would be perfect. Unfortunately I'm not allowed to use any heap allocation. So I went on and implemented a way to have dynamic polymorphism on the stack. But as it turns out a simple test program which switched an led on and off used 7.1kb of flash just to create my custom vtables to copy the object correctly, this is way too much.

I've also tried out CTRP, but this wouldn't work either because I need to store the objects in a container.

What alternatives are there to normal C++ polymorphism, that don't require heap allocation and don't take up too much flash?

Poco::Dynamic::Var created empty object by operator []

I try to check the parameter is existing in Poco::Dynamic::Var. But after checking I found that source object is changed. Appeared a new parameter, which I checked.

Problem:

How to check the presence of a parameter in an Poco::Dynamic::Var without modifying the source object.

Code example:

void checkParamInConfig(Poco::Dynamic::Var &conf) {
    std::cout << "before:" << conf.toString() << std::endl;

    // new key problem
    if (conf["Configuration"]["NewParam"].isEmpty()) {
        std::cout<<"NewParam not found"<<std::endl;
    }
    
    std::cout << "after:" << conf.toString() << std::endl;
}

Output:

before:{ "Configuration" : { "Param1" : true, "Param2" : true, "Param3" : true } }
NewParam not found
after:{ "Configuration" : { "NewParam" : null, "Param1" : true, "Param2" : true, "Param3" : true } }  

Can someone tell me the output and provide explanation of the following c++ code?

cout<<"#" + 'a'<<endl;

string s = "#";
s += 'a';
cout<<s<<endl;

I am not able to figure out how the typecasting is working in the case "#" + 'a'

Pointer to member function of instance instead of class

I have the following class when I get a pointer to a member function according to some condition and then call the function.

class Test
{
public:
    bool isChar(char ch) { return (ch >= 'a' && ch <= 'z'); }
    bool isNumeric(char ch) { return (ch >= '0' && ch <= '0'); }

    enum class TestType
    {
        Undefined,
        Char,
        Numeric,
        AnotherOne,
    };

    bool TestFor(TestType type, char ch)
    {
        typedef bool (Test::*fptr)(char);
        fptr f = nullptr;
        switch(type)
        {
            case TestType::Char:
                f = &Test::isChar;
                break;
            case TestType::Numeric:
                f = &Test::isNumeric;
                break;
            default: break;
        }

        if(f != nullptr)
        {
            return (this->*f)(ch);
        }

        return false;
    }
};

But actually I don't like the syntax. Is there a way to replace

(this->*f)(ch)

with

f(ch)

?

In my real code the function a big enough and it's not so clear what (this->*f) is. I'm looking for some c++11 solution. I know about std::function and I will use it if if no solution will be found.

Update

The solution that I decided to use, if suddenly someone needs it: (thanks for @StoryTeller - Unslander Monica)

bool TestFor(TestType type, char ch)
{        
    bool(Test::* fptr)(char) = nullptr;
    switch(type)
    {
        case TestType::Char:
            fptr = &Test::isChar;
            break;
        case TestType::Numeric:
            fptr = &Test::isNumeric;
            break;
        default: break;
    }

    if(fptr != nullptr)
    {
        auto caller = std::mem_fn(fptr);
        caller(this, ch);
    }

    return false;
}

Is it possible to generate a compile-time error if some member function hasn't been called

I'm coding a class with Singleton pattern.

class GroupListDAO {
public:
    static GroupListDAO* getInstance() {
        static GroupListDAO groupListDAO;
        return &groupListDAO;
    }

    init(server::mysqldb::MysqlHelperTempalte* pHelper) {
        mysqlHT = pHelper;
    }

    bool getUserHeartNum(uint32_t owner, uint32_t& totalNum);
    bool setUserHeartNum(uint32_t owner, uint32_t totalNum, uint32_t update_time);
private:
    MysqlHelperTempalte *mysqlHT;

    GroupListDAO() = default;
    ~GroupListDAO() = default;
};

As you see, this class is used to connect to Mysql. So the member data mysqlHT must be initialized before calling any other member functions.

In a word, the class user must use this class as below:

GroupListDAO *p = GroupListDAO::getInstance();
p->init(XXX);    // init must be called before calling any other member functions
p->getUserHeartNum(...);
p->setUserHeartNum(...);

So I'm thinking if there is a way to force the class user to call the function init. Meaning that if the class user codes like this:

GroupListDAO *p = GroupListDAO::getInstance();
p->getUserHeartNum(...);
p->setUserHeartNum(...);

Some compile-time error can be generated.

Ofc, you might say that we can if (mysqlHT == nullptr) { throw exception; } in other member functions... Well, I can do this if there is no other way...

get second element of a vector pair from specific first element

how can i get the second element of a vector pair from specific first element?

I have codes below:

vector< pair <string, string> > vect;
vect.push_back(make_pair("hello","s:hihi"));
vect.push_back(make_pair("hi","s:hello"));
string check;
string first;
string last;
while(true)
{
    cout << "Create new pair.\nFirst element: ";
    //Part1
    getline(cin, first);
    cout << "Second element: ";
    //Part2
    getline(cin, last);
    if(first == "get" && last == "get") break;
    else vect.push_back(make_pair(first, last));
}
cout << "What first element to search: ";
//Part3
getline(cin, check);

I want to check if user entered hello at part3, it will cout s:hihi. By this way if user entered hi at part3, it will cout s:hello. If user entered "bye" at part 1 and entered "hey" at part 2. Then when user enter "bye" at part 3 it will print out "hey"

How can I do this?

mercredi 28 juillet 2021

Is this threadpool code attempting double execution of task?

I have copied the below threadpool implementation from https://pastebin.com/MM5kSvH6. All looks good but i can't understand the logic at Line number 32 and Line number 71. Aren't both these lines trying to execute the function? I thought in threadpool, the thread is supposed to pull task from task queue and then execute it? In that sense line 71 looks OK but i am confused by line 32. Instead of adding the task to the queue why is it trying to execute the same?

#include <condition_variable>
#include <functional>
#include <iostream>
#include <future>
#include <vector>
#include <thread>
#include <queue>
 
class ThreadPool
{
public:
    using Task = std::function<void()>;
 
    explicit ThreadPool(std::size_t numThreads)
    {
        start(numThreads);
    }
 
    ~ThreadPool()
    {
        stop();
    }
 
    template<class T>
    auto enqueue(T task)->std::future<decltype(task())>
    {
        auto wrapper = std::make_shared<std::packaged_task<decltype(task()) ()>>(std::move(task));
 
        {
            std::unique_lock<std::mutex> lock{mEventMutex};
            mTasks.emplace([=] {
                (*wrapper)();
            });
        }
 
        mEventVar.notify_one();
        return wrapper->get_future();
    }
 
private:
    std::vector<std::thread> mThreads;
 
    std::condition_variable mEventVar;
 
    std::mutex mEventMutex;
    bool mStopping = false;
 
    std::queue<Task> mTasks;
 
    void start(std::size_t numThreads)
    {
        for (auto i = 0u; i < numThreads; ++i)
        {
            mThreads.emplace_back([=] {
                while (true)
                {
                    Task task;
 
                    {
                        std::unique_lock<std::mutex> lock{mEventMutex};
 
                        mEventVar.wait(lock, [=] { return mStopping || !mTasks.empty(); });
 
                        if (mStopping && mTasks.empty())
                            break;
 
                        task = std::move(mTasks.front());
                        mTasks.pop();
                    }
 
                    task();
                }
            });
        }
    }
 
    void stop() noexcept
    {
        {
            std::unique_lock<std::mutex> lock{mEventMutex};
            mStopping = true;
        }
 
        mEventVar.notify_all();
 
        for (auto &thread : mThreads)
            thread.join();
    }
};
 
int main()
{
    {
        ThreadPool pool{36};
 
        for (auto i = 0; i < 36; ++i)
        {
            pool.enqueue([] {
                auto f = 1000000000;
                while (f > 1)
                    f /= 1.00000001;
            });
        }
    }
 
    return 0;
}

How to override the OpenMp runtime scheduling policy using OMP_SCHEDULE environment variable?

I have an openMP parallel for loop of the form

#pragma omp for schedule(dynamic)
for(std::size_t i = 0 ; i < myArray.size() ; i++)
{
  //some code here
}

In other words by default this loop uses dynamic scheduling. However if the user specifies the OMP_SCHEDULE environment variable I want to be able to override the dynamic policy with whatever policy is specified in OMP_SCHEDULE. How can this be done? In other words if OMP_SCHEDULE is not specified I want to use a dynamic schedule by default. It is my understanding that in the above code, because I have specified schedule(dynamic) it is going to ignore any policy specified in OMP_SCHEDULE, is this correct? Thanks

Why does ofstream avoids the first 4 character while storing the value of the string?

Im using ofstream to get an input type string from user and put it in a file called question.txt. It doesnt show the first 4 characters in the file..I also tried without putting cout<<question and just getline(cin, question), If i do that, it doesnt let user put input at all

string question; 
cout<<"Enter Your Question: "<<endl;
cin>>question;
getline(cin, question);
cout<<question<<endl;
ofstream g("question.txt",ios::app);
g<<question<<endl;

This code above ignores the first 4 characters of the string and then prints the rest of the code.

string question; 
cout<<"Enter Your Question: "<<endl;
getline(cin, question);
cout<<question<<endl;
ofstream g("question.txt",ios::app);
g<<question<<endl;

This code above(without cin>>question) doesnt allow the user to input at all..this code is in an if else statement...when u put the same code somewhere else it works, but it doesnt work here for some reason

whole code paste bin link: https://pastebin.com/yQrzZXxJ code starts from line 83

How to pass template type at runtime? [duplicate]

I have a ClassL<T> where I'm trying to pass a vector<T> to template ClassP<T> via the call ClassP::do_something(std::vector<T>).

// global variables
std::shared_ptr<ClassP<ObjA>> objA;
std::shared_ptr<ClassP<ObjB>> objB;
// elsewhere
objA = std::make_shared<ClassP<ObjA>>();
objB = std::make_shared<ClassP<ObjB>>();

template <typename T>
int ClassP<T>::do_something(const std::vector<T> msgs)
{   
    for (const auto& msg : msgs) {
        // print msg ...
    }

    return 0;
}

template <typename T>
void ClassL<T>::on_recv(T& records)
{
    auto data = records.get();

    std::vector<T> vecdata;

    std::copy(data.begin(), data.end(), 
        std::back_inserter(vecdata));

    if (std::is_same<T, ObjA>::value)
        objA->do_something(vecdata);

    else if (std::is_same<T, ObjB>::value) 
        objB->do_something(vecdata);
}

But doing the above will cause the following compile errors. I'm guessing my use of checking the template via is_same is not right but wasn't sure how to choose based on the type.

classl.hpp:75:27: error: cannot convert 
‘vector<ObjB,allocator<ObjB>>’ to ‘vector<ObjA,allocator<ObjA>>’
75 |   objA->do_this(vecdata);
   |                 ^~
   |                 |
   |                 vector<ObjB,allocator<ObjB>>

classl.hpp:80:39: error: cannot convert 
‘vector<ObjA,allocator<ObjA>>’ to ‘vector<ObjB,allocator<ObjB>>’
80 |   objB->do_this(vecdata);
   |                 ^~~~~~~~~
   |                 |
   |                 vector<ObjA,allocator<ObjA>>

Can anyone explain where I'm going wrong?

Maximum subarray - returning container

I am trying to implement version of Kadane's algorithm which returns subarray. Instead of just returning largest sum I would like to get container. Based on wiki pseudocode I have prepared simple implementation. However, I would like to avoid using indexes best_start and best_end. I can not find a way to fill out vector step by step using push_back.

Could you give me suggestion how should I change logic of this program?

std::vector<int> maxSubArrayWiki(const std::vector<int>& nums) {
    std::vector<int> out;
    int max_sum = INT_MIN;

    int sum = 0;
    int i = 0;
    int current_start, best_start, best_end = 0;
    for(const auto& n : nums){
        if(sum <= 0) {
            current_start = i;
            out = {};
            sum = n;
        }
        else {
            sum += n;
        }
        if(sum > max_sum) {
            max_sum = sum;
            best_start = current_start;
            out.push_back(n);
            best_end = i + 1;
        }
        i++;
    }
    // is it possible to avoid following? return std::vector<int>(&nums[best_start], &nums[best_end]);
    return out;
}

out:
4 2 1 
expected:
4 -1 2 1 

http://coliru.stacked-crooked.com/a/8d120f8f0ab923a6

Stringify parameters in macro

#define MY_ASSERT_TEST(parA, parB, parC) do {                                           \
    for (int i = 0; i < TestStruct::parB::TestData_parC_TestOptions_Len; i += 1)        \
    {                                                                                   \
        if (parA == TestStruct::parB::TestData_parC_TestOptions_i)                      \
            return;                                                                     \
    }                                                                                   \
    MY_LOG("MY_ASSERT_TEST Warning: %s", #parA);                                        \
} while(0)

It replaces parB correctly, but not parC and i.

I have tried something like TestStruct::parB::TestData_#parC_TestOptions_#i.

or TestStruct::parB::TestData_(#parC)_TestOptions_(#i)

how is it possible to create temporary files as binaries?

I'm new to c++, but I downloaded an application that reads .dat files, however these files are compressed or are in binary, when reading this file it generates a .tmp file in the %temp% folder, however this file is an executable(?) PE32, is it possible for a process to create a temporary file that is actually an executable?, if so, how is this process done more easily?

Linked List traversal by pointer in c++

In programming we have to do var = var + sum;

and we can write it as- var += sum;

So in the linked list can we write temp = temp->next;

as - temp->=next;

when to prefer lambda over packaged task with std::async? [duplicate]

I am bit confused as when do i need to pass packaged_task to std::async. Do i really need std::packaged_task when i can directly pass the function with arguments? Is there something which is possible only with packaged task and not with normal function approach?

Approach 1: std::async with lambda function

std::future<int> result= std::async(std::launch::async, [](int m, int n) { return m + n;} , 2, 4));

Approach 2: std::async with packaged_task,

        auto f = [](int m, int n) { return m + n;};
        std::packaged_task<int(int,int)> task(f);
        std::future<int> result = task.get_future();
     
        std::async(std::launch::async, std::move(task), 2, 4);
        int ans = result.get();
        

I have checked for answers but none of them gives me a proper use case. It looks like coder can just use any of these approaches BUT when does one scores over other?

Get the size of the biggest derived class from a language server

I've got the problem that I need to know the size of the biggest derived class of a base class. At the moment I'm using the -D option of the compiler to specify the size, this is the easiest option I could think of, but you always have to update the size manually.

Since this would be nearly impossible to do in c++ itself, I thought maybe could get the information from a language server and then generate a header that contains the information.

Note that I have no experience in this, but the language server should have all the information that I need right?

How difficult would it be to implement this in python? (doesn't have to be python but I would prefer it)

For the language server I could provide a CMakeLists.txt.

How to correctly copy a lambda with a reference capture?

Ok so I ran into a problem when implementing a c# property like system in c++ (see: https://stackoverflow.com/a/68557896/3339838).

Consider the following example:

struct TransformCmp
{
PropertyDelGetSet<vec3> position =
    PropertyDelGetSet<vec3>(
        [&]() -> const vec3& { return m_position; },
        [&](const vec3& val) { m_position = val; m_dirty = true; });

private:
    vec3 m_position = vec3(0);
}

If/when the instance of the TransformCmp is copied/moved (e.g. if it was stored in std::vector and resize was called), the reference capture is now invalid.

The question is how do I make sure when the copy/move happens that I also update the reference capture?

I've tried implementing a copy constructor for the Property classes but I ran into the same issue, probably because I didn't do it correctly. Any ideas?

How do I get the program to work? It is a college manangement system project made from scratch by a noob

this is a college management system program, where student can sign up, sign in. The username password and id are stored in a file. which are used later by fstream to do certain tasks like printing information. There is also another feature where the students could ask a question(line 98) and the admin will be able to answer it(line 187), and then the student will be able to view the question and answer(line 81). My program gets stuck in a loop and also need to fix the errors which i definitely made. I built this program totally from scratch myself. And also I am new to programming. Thank you!

#include <iostream>
#include <string>
#include <fstream>
#include<stdlib.h>
#include<string.h>
#include<ctime>
using namespace std;
void signIn();
void signUp();
void admin();

int main(){
    int choicE;
    cout<<"====================================================="<<endl;
    cout<<"=============College Management System==============="<<endl;
    cout<<"====================================================="<<endl;
    cout<<endl<<endl;
    cout<<"1) Student sign in"<<endl;
    cout<<"2) Student sign up"<<endl;
    cout<<"3) Admin"<<endl<<endl;
    cout<<"Enter Your Choice: "<<choicE<<endl;

    switch(choicE)
        {
                case 1:
                        signIn();
                        break;
                case 2:
                        signUp();
                        break;
                case 3:
                        admin();
                        break;
                default:
                        system("cls");
                        cout<<"Wrong choice!\nTry again!"<<endl; 
                        main();
        }


    return 0;
}
void signIn(){
        int counter,id, acount;
        string user,pass,u,p,m;
        system("cls");
        cout<<"please enter the following details"<<endl;
        cout<<"USERNAME :";
        cin>>user;
        cout<<"PASSWORD :";
        cin>>pass;
        
        ifstream f("student.txt");
        while(f>>id>>u>>m>>p)
        {
                if(u==user && p==pass)
        
                {
                        counter=1;
                        system("cls");
                }else
                {
                cout<<"Either username or password is incorrect";
                main();
                }
        }
        f.close();
        if(counter==1)
        {
            int choiCe;
            string question;
                cout<<"\nWelcome"<<user<<"!"<<endl<<endl;
                cout<<"1) Check Messages"<<endl;
                cout<<"2) Ask Question"<<endl;
                cout<<"3) Account info"<<endl;
                cout<<"Enter anything else to exit."<<endl<<endl;
                cout<<"Enter your choice: "<<choiCe;
                if(choiCe==1){
                    string q,q2,a;
                    int count;
                    ifstream y("question.txt");
                    ifstream x("answer.txt");
                        while(y>>q && x>>q2>>a)
                        {
                                if(q==q2)
                                {
                                        count=1;
                                }
                        }
                        y.close();
                        x.close();
                        if(count==1){
                            cout<<q2<<a;
                        }
                }else if(choiCe==2){
                    system("cls");
                    cout<<"Enter Your Question: "<<endl;
                    getline(cin, question);
                    ofstream g("question.txt",ios::app);
                    g<<question<<endl;
                    cout<<"Question will be answered shortly. Come back later!"<<endl;
                }else if(choiCe==3){
                    int aid;
                    cout<<"Enter your ID"<<aid;
                    ifstream h("student.txt");
                    while(h>>id>>u>>m>>p){
                        if(id==aid){
                            acount=1;
                        }
                    }
                    h.close();
                    if(acount==1){
                        int no;
                        cout<<"Major: "<<m<<endl;
                        cout<<"Username: "<<u<<endl;
                        cout<<"Password: "<<p<<endl;
                        cout<<"Press 1 to exit: "<<no;
                        if(no==1){
                            main();
                        }
                    }
                }else{
                    main();      
                }
         
                
        }
        
}
void signUp(){
    string nuser,npass, nmajor;
    string fname, lname;
        system("cls");
        cout<<"Enter First Name: ";
        cin>>fname;
        cout<<"\nEnter Last Name: ";
        cin>>lname;
        cout<<"\nCreate a Username: ";
        cin>>nuser;
        cout<<"\nEnter Major: ";
        cin>>nmajor;
        cout<<"\nEnter the password: ";
        cin>>npass;
        int id=rand();
        ofstream i("student.txt",ios::app);
        i<<id<<' '<<nuser<<' '<<nmajor<<' '<<npass<<endl;
        system("cls");
        cout<<"\nRegistration Sucessful\n";
        main();
}
void admin()
{
    int adpass, choIce;
    cout<<"Enter Password: "<<adpass<<endl;
    if(adpass==1234)
    {
        cout<<"1) View Student Info"<<endl;
        cout<<"2) Answer Questions"<<endl;
        cout<<"3) Exit"<<endl<<endl;
        cout<<"Enter your choice: "<<choIce;
        
        if(choIce==1)
        {
            int aid,acount,id;
            string u,m,p;
            cout<<"Enter student ID"<<aid;
            ifstream j("student.txt");
            while(j>>id>>u>>m>>p){
                if(id==aid){
                    acount=1;
                }
            }
            j.close();
            if(acount==1){
                int no;
                cout<<"Major: "<<m<<endl;
                cout<<"Username: "<<u<<endl;
                cout<<"Password: "<<p<<endl;
                cout<<"Press 1 to exit: "<<no;
                if(no==1){
                    main();
                }
            }
        }else if(choIce==2)
        {
            fstream l("question.txt");
            
            if(l.is_open()){
                cout<<l.rdbuf();
            }
            l.close();
            string q,a;
            cout<<"Enter the question you would like to answer:"<<endl;
            getline(cin,q);
            cout<<"Enter the answer:"<<endl;
            getline(cin,a);
            ofstream z("answer.txt",ios::app);
            z<<q<<a<<endl;
        }else{
            main();
        }
    }
}

Should we define variable with constexpr in a function

I don't know if it is meaningful to define a variable with constexpr in a function.

void func() { static const int i = 1; }
void func2() { constexpr const int i = 1; }

static const in a function would be initialized on the first function call, how about constexpr in a function? I know that constexpr specifies that the object should be available during compilation. So does it mean that the variable i in the func2 would be evaluated at compile time whereas the i in the func wouldn't?

mardi 27 juillet 2021

What is the best structure for calculating images from multiple thread?

when I tried do average to multiple panorama for blurring moving object, I got panoramas each loop in each threads, and brought by ThreadSafe_Queue. (I try to use this for making threadsafe queue : https://codetrips.com/2020/07/26/modern-c-writing-a-thread-safe-queue/)

void makePanorama_th(int thread_num, ThreadSafe_Queue* frame_q, ThreadSafe_Queue* result_q);

... and run this function asynchronously like this.

v_th_panorama.emplace_back(std::async(std::launch::async, &Pano_Worker::makePanorama_th, pano_worker, i, &this->th_frame_q, &this->th_result_q));

all thread get unique frame from shared queue. and get results from threads by threadsafe queue and do average each pixel value.

make panorama average like

     frame number for make panorama each thread
   thread 1.   2   5   8
   thread 2.    3   6   9
   thread 3.     4   7   10
  1. The average is calculated based on the length of the panorama using the frame with the smallest frame number(2~5). and other thread's remaining sections(2. 5~6/ 3. 5~7), simply sum the pixel values.

          first panorama average
    thread 1.   2   5
    thread 2.    3     
    thread 3.     4
    average     2 ~ 5
    sum             5 ~ 7 
    
  2. if shortest panorama's(2 ~ 5) length reach to longest panorama's length(2 ~ 5 -> 2 ~ 8), sum and do average about the longest section before(2 ~ 7)

second panorama average

   thread 1.   2   5   8
   thread 2.    3   6   
   thread 3.     4   7
   average     2  ~  7
   sum               7 ~ 8

But, When I tried this method, seriously slow. because return image each loop, and calculate average sequentially.

How can I create in real-time average image of multiple panoramas created in multiple threads?

What is the difference between int{10} and 10?

As the title, I have two expressions:

int&& a = const_cast<int&&>(int{10});
int&& a = const_cast<int&&>(10);

The first compiling passed, but second not. Why is this happening?

In my view, it's because 10 is a literal and int{10} is a unamed variable. Is it?

Experiments with namespace in class protected area

#include <iostream>

class A
{
public:
    int func();

protected:
    namespace B { enum { D = 0, E = 1 }; }
    namespace C { enum { D = 0, E = 1 }; }
}

int A::func()
{
    int x = A::B::D;
    int y = A::C::E;
    return x + y;
}

int main() {
    A a;
    int x = a.func();
    std::cout << x << std::endl; // 1
    
    return 0;
}

What's wrong with this code?

I am just curious and experimenting with namespace, because I'd like to have enums with same names of values.

I don't want to use enum class, because I cannot do operations with integer without overloading operators or casting.

Check if << operator is applicable in overriding template context

I have made a AnyType class which is similar to std::any in C++14. I would like to override the << operator to easily print the content of the stored variable:

std::ostream& operator<<( std::ostream& o, const AnyType& v ) {
  if( v._varPtr_ != nullptr ) v._varPtr_->writeToStream(o);
  return o;
}

And the writeToStream() is an overrided function defined in a PlaceHolder class which is holding the actual typed variable. It is defined as:

void writeToStream(std::ostream& o) const override { o << _variable_; }

My problem is when I define a AnyType object which is holding a variable type with no operator<< overrided, the compiler is throwing an (expected) error while unfolding a defined template class:

error: invalid operands to binary expression ('std::ostream' (aka 'basic_ostream<char>') and 'const TGraph')
    void writeToStream(std::ostream& o) const override { o << _variable_; }
                                                         ~ ^  ~~~~~~~~~~

Here is a minimal example:

struct PlaceHolder{
  virtual ~PlaceHolder() = default;
  virtual void writeToStream(std::ostream& o) const = 0;
};

template<typename VariableType> struct VariableHolder: public PlaceHolder{
  explicit VariableHolder(VariableType value_) : _variable_(std::move(value_)){  }
  void writeToStream(std::ostream& o) const override { o << _variable_; }

  VariableType _variable_;
};

class AnyType{
public:
  AnyType(){}
  template<typename ValueType> inline void setValue(const ValueType& value_){ 
    _varPtr_ = std::shared_ptr<VariableHolder<ValueType>>(new VariableHolder<ValueType>(value_)); 
  }
  friend std::ostream& operator<<( std::ostream& o, const AnyType& v ) {
    if( v._varPtr_ != nullptr ) v._varPtr_->writeToStream(o);
    return o;
  }

private:
  std::shared_ptr<PlaceHolder> _varPtr_{nullptr};
};

int main(){

  AnyType a;
  a.setValue(int(14));
  std::cout << a << std::endl; // this will work

  // If the following line is uncommented, the compiler will throw an error
  // a.setValue(TGraph()); // this is a CERN's ROOT class
  

}

So my question is: Is there any way to make the compiler check if it is possible to override << before having it explicilty ? This way I could let the writeToStream method to be defined as default: = 0.

May be there is another workarround. Typically this problem does not appear with std::any. Does anyone knows how it is implemented in the std library?

Cheers :)

Difference between = and {} in-class initialization

When I want t put initial values inside the class definition there are two ways it can be done: with {} and =

class A
{
public:
   int a = 1;
   bool b = false;
   someClass* obj = nullptr;
};

class B
{
public:
   int a {1};
   bool b {false};
   someClass* obj {nullptr};
};

Is there any difference between those two options? Will in class A and B be something different in a way fields where initialized?

With = it will be copy initialization, so with {} should be more efficient? Or in case of in-class initialization they are equal and just provide different syntax?

How to avoid multiple copies of the code for std::vector

I've got one shared library -- let's call it the master. It produces one or more slave shared libraries. The slave shared libraries are interacting with the master via an interface, exchanging std::string, std::vector and others. The compile time of the slave shared libraries must be minimized as this compile is done at the customer site dynamically.

As long as the exchanged object is not a STL container, everything works fine. e.g.

  • master compiles NonStlObject.cpp and NonStlObject.h and produces global text symbols (T)
  • client uses NonStlObject.h and creates undefined global text symbols (U)

As soon as an STL container is being exchanged, I end up with 1 + numberOfSlaves copies of the STL code -- and matching compile time -- they are weak symbols (W) in both master and slaves.

Is there any way to avoid this, other than wrapping every STL container?

PS. I don't care to be informed, that the version of the compiler used for building the interacting shared libraries must be the same. Of course it must!

PPS. extern template seems to be ignored by the compiler when applied to std::vector

Undefined behavior in replacement for polymorphism with out Pointers

I've recently asked about this on this question. And I've gone with this generic approach:

#define COFFEE_GEN_GENERIC_VALUE(CLASS_TYPE) using GenericValue##CLASS_TYPE = coffee::utils::GenericValue<CLASS_TYPE, COFFEE_GENERIC_VALUE_CONFIG_MAX_DERIVED_SIZE_OF_##CLASS_TYPE>

template<typename Base, size_t MaxDerivedSize>
class GenericValue
{
private:
    char buffer[MaxDerivedSize];

public:
    GenericValue() = default;

    template<typename Derived, typename... ConstructorArgs>
    static GenericValue<Base, MaxDerivedSize> create(ConstructorArgs... args)
    {
        static_assert(std::is_base_of<Base, Derived>::value, "Derived must derive from Base.");
        static_assert(sizeof(Derived) <= MaxDerivedSize, "The size specified with the macro COFFEE_GenericValueMaxSize is to small.");
        GenericValue<Base, MaxDerivedSize> result{};
        new ((Derived*) result.buffer) Derived{args...};
        return result;
    }

    template<typename Derived>            
    static GenericValue<Base, MaxDerivedSize> from(Derived* toCopy)
    {
        static_assert(std::is_base_of<Base, Derived>::value, "Derived must derive from Base.");
        static_assert(sizeof(Derived) <= sizeof(MaxDerivedSize), "The size specified with the macro COFFEE_GenericValueMaxSize is to small.");
        GenericValue<Base, MaxDerivedSize> result{};
        memcopy(result.buffer, toCopy, sizeof(Derived));
        return result;
    }
    
    GenericValue(const GenericValue<Base, MaxDerivedSize>& other)
    {
        memcopy(buffer, other.buffer, MaxDerivedSize);
    }
    
    GenericValue(GenericValue<Base, MaxDerivedSize>&& other)
    {
        memcopy(buffer, other.buffer, MaxDerivedSize);
    }

    GenericValue<Base, MaxDerivedSize>& operator=(const GenericValue<Base, MaxDerivedSize>& other)
    {
        memcopy(buffer, other.buffer, MaxDerivedSize);
        return *this;
    }
    
    GenericValue<Base, MaxDerivedSize>& operator=(GenericValue<Base, MaxDerivedSize>&& other)
    {
        coffee::utils::copy(buffer, other.buffer, MaxDerivedSize);
        return *this;
    }

    Base& operator*()
    {
        return *(Base*)buffer;
    }

    Base* operator->()
    {
        return (Base*)buffer;
    }
}

I had the idea for this form this website and its kind of the same as the awnser from @Matthias Grün on my old question. You use the COFFEE_GEN_GENERIC_VALUE macro to create a typedef for GenericValue<Base, MaxDerivedSize> the size will be passed to it with a second macro. This is so that my library can generate the appropriate GenericValue types that will be used for the specific base class. The basic idea behind it is that you store the whole instance of the derived type with it's vtable in buffer. You can than copy it just like a regular rvalue.

Unfortunately doe copying only some times works and I have no idea why, based on my knowledge this would not be a problem. If I remove the copy operators and constructor and just use the class as a wrapper for new it works great (except the objects aren't realy copied).

Does any body know what the problem could be?

I will post a specific example when I found an edge case for which I don't have to post my whole project.

Is std::bind ignoring superfluous arguments standard-conforming?

The functor returned by std::bind ignores superfluous arguments [SO1, SO2, SO3]. A simple example looks as follows.

#include <iostream>
#include <functional>

void foo(int a) {
  std::cout << "a=" << a << std::endl;
}

int main() {
  auto f = std::bind(foo, 42);
  f(3141); // a=42
}

It is clear that implementing std::bind in this way is easier [SO1a]. Is, however, this ignoring of superfluous arguments standardized or undefined behavior?

Finding the meaning of a dictionary word using QRegularExpression

I have two sentences in text file name e.g:

Abbey n. (pl. -s) 1 building(s) occupied by a community of monks or nuns. 2 the community itself. 3 building that was once an abbey.

Abbot n. Head of a community of monks. [old english from latin abbas]

I can match the word Abbey using

QRegularExpression re("Abbey", QRegularExpression::CaseInsensitiveOption); QRegularExpressionMatch match = re.match(txtFile);

What will the process to extract meaning Abbey, the meaning would be "building(s) occupied by a community of monks or nuns"?

Convert vector of vector of bools to pointer of pointers

I have a problem similar to the one mentioned in the question Convert vector of vector to pointer of pointer.

The only difference is that I have to use booleans instead of shorts.

But if I compile this code:

#include <vector>

/* C like api */
void foo(bool **psPtr, const int x, const int y);

int main()
{
  const int x = 2, y = 3;
  std::vector<std::vector<bool>> vvsVec(x, std::vector<bool>(y, 0));
  std::vector<bool *> vpsPtr(x, nullptr);

  /* point vpsPtr to the vector */
  int c = 0;
  for (auto &vsVec : vvsVec)
    vpsPtr[c++] = vsVec.data();

  /* api call */
  foo(vpsPtr.data(), x, y);

  return 0;
}

I get the following error:

./dummy/main.cpp:15: error: assigning to '__gnu_cxx::__alloc_traits<std::allocator<bool *> >::value_type' (aka 'bool *') from incompatible type 'void'

and

./dummy/main.cpp:15: error: void value not ignored as it ought to be vpsPtr[c++] = vsVec.data();

Please, can someone explain me what I'm doing wrong and how to fix this?

Thanks.

ReScroll/ReStart Scrolling from Top in wxScrollWindow - wxWidgets

Hi i am using a wxScrolledWindow to show a number of elements. Let's say I have 20 elements in the scrollwindow. Now when the user reaches the end of the list(through scrolling upwards) the scrolling should start again from the top, that is it should not stop when reaching to the end. So lets say i have 20 buttons each having labels like Button1, Button2, ...(upto), Button20. Now when the user scrolls through them and reaches Button20 then typically the scrolling stops but I want that the scrolling should continue and again Button1 should come next, then Button2, ...Button20 . And then the user can continue this process as many times as he/she wants. Similarly for scrolling in the opposite direction also. So in this case lets say the user is at the top of the scrolling list and he/she starts scrolling in the downward direction then typically there is no scrolling but what i want is that the scrolling should continue and Button20 then Button19 should be made visible and so on. Is this possible in wxWidgets? Is there any style of wxScrollWindow that allows this self wrapping kind of behavior.

Reasons for having this kind of scroll behavior:

  1. I want this in some of my widgets. This reason is for fun learning/demonstrating purposes. That is by writing such a widget I would learn/improve my wxWidgets skill.
  2. I have a huge list of elements, say a std::setstd::string of 2000. Now if i create a wxButton for each of these 2000 elements and insert that button into the wxScrollwindow then the program is taking a lot of memory. So I want to customize how scrolling works for a large number of elements. This is the design that I am thinking of:

Step 1: Out of the 2000 elements only 20 or 30 elements(wxbuttons) are inserted into the wxScrolledWindow.

Step 2: Out of these 20 or 30 elements only a fixed number say 10 are made to be actually visible on the wxScrollWindow.

Step 3: Then when the user starts scrolling downwards and then the next incoming(11th) element that just becomes visible will get the string value from the next element in the std::set. So we keep track of the element that is just made visible and which has gone out of the visible part of the scrollwindow. And then whenever the user scrolls downwards we just change the label of the next incoming widgets.

So this way the memory consumption should be reduced. Also, is there any other way to handle this situation when we have a large number of elements?

ros kinetic compile with c++11 seems not working

I make a ros package, and in it I write

typedef std::array<float,6> Tmat; 

I found this is new in c++11, and follow many instructions, I uncomment related lines in CMakelists.txt

add_compile_options(-std=c++11)
SET(CMAKE_BUILD_TYPE Debug)

in both CMakelists in package and whole project. But still I get this when catkin_make:

error: ‘array’ in namespace ‘std’ does not name a template type
 typedef std::array<float,6> Tmat;

Anyone have clue about what am I doing wrong here?

lundi 26 juillet 2021

std::string::append crashes program with "std::bad_alloc"

I have a text file which contains a list of data relating to name, position, and height. My program parses this data into a vector map, then uses this data to construct an xml file using boost::property_tree. The text file is about 3500 lines, and the program consistently crashes at line 1773 with:

terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc
Aborted (core dumped)

At first I thought maybe the size limit was being reached, but reading up on std::string shows that the target computer should be able to allocate the size required. Regardless, I decided to test with std::string::size , std::string::length, std::string::capacity, std::string::max_size which showed (respectively):

...
...
6572094845  6572094845 6626476032 9223372036854775807
6579537815  6579537815 6626476032 9223372036854775807
6586984998  6586984998 6626476032 9223372036854775807
6594436394  6594436394 6626476032 9223372036854775807
6601892003  6601892003 6626476032 9223372036854775807
6609351825  6609351825 6626476032 9223372036854775807
6616815856  6616815856 6626476032 9223372036854775807
6624284100  6624284100 6626476032 9223372036854775807

std::string::capacity was seen to increase once std::string::length == std::string::capacity.

gdb bt after compiling for debug:

(gdb) bt
#0  __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:51
#1  0x00007fd67037e921 in __GI_abort () at abort.c:79
#2  0x00007fd6709d3957 in ?? () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#3  0x00007fd6709d9ae6 in ?? () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#4  0x00007fd6709d9b21 in std::terminate() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#5  0x00007fd6709d9d54 in __cxa_throw () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#6  0x00007fd6709da2dc in operator new(unsigned long) () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#7  0x00007fd670a6bb8b in std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::_M_mutate(unsigned long, unsigned long, char const*, unsigned long) () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#8  0x00007fd670a6d133 in std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::_M_append(char const*, unsigned long) () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#9  0x000056104c176f3a in main (argc=1, argv=0x7ffc0af8b9a8) at /home/code/hello_world/createWorld.cpp:224

Example line in text file being read:

713.258 235.418 ABCD1234567     2898

Code:

int main(int argc, char **argv)
{
    CreateWorld *newWorld = new CreateWorld();
    lastModelsParser *lastModels = new lastModelsParser();

    const string filenameModel = "model.sdf";
    const string fileNameWorld = "TEMPLATE_default_world.xml";
    string lastModels = "lastmodels.txt";
    
    ptree ptWorld, ptModel, ptNewWorld, ptNewModel;

    std::ifstream ifsModel(filenameModel,std::ifstream::binary);
    std::ifstream ifsWorld(fileNameWorld,std::ifstream::binary);
    std::ofstream newWorldFile("NEW_WORLD.xml");

    std::ostringstream worldOSS, modelOSS, newWorldOSS;

    read_xml(ifsWorld, ptWorld, boost::property_tree::xml_parser::trim_whitespace);         // read xml data into ptree
    read_xml(ifsModel, ptModel, boost::property_tree::xml_parser::trim_whitespace);         // read xml data into ptree

    vector<lastModelsParser::lastModel> _lastModels;

    lastModels->ParseToXML(lastModelsFile);
    _lastModels = lastModels->getlastModels();

    uint16_t lastModelsEntry = 0;
    std::string newModelString;

    for(auto i:_lastModels){
        ptNewModel = newWorld->modelModifier(ptModel, 
            _lastModels.at(lastModelsEntry).pX,
            _lastModels.at(lastModelsEntry).pY,
            _lastModels.at(lastModelsEntry).name, 
            _lastModels.at(lastModelsEntry).height);

        boost::property_tree::xml_parser::write_xml_element(modelOSS, ptNewModel.front().first, ptNewModel.back().second, 1, xml_settings);
        
        newModelString.append(modelOSS.str());              // CRASHES HERE 
 
        lastModelsEntry++;        
    }

    // append to world.xml
    boost::property_tree::write_xml(worldOSS, ptWorld, xml_settings);           // write xml data into OSStreams
    boost::property_tree::write_xml(modelOSS, ptModel, xml_settings);           // write xml data into OSStreams   
    size_t worldPos = worldOSS.str().find("</world>");

    std::string newWorldString = worldOSS.str().insert(worldPos,newModelString+"\n\t");

    newWorldFile << newWorldString ;
    

    delete(lastModels);
    delete(newWorld);

    return EXIT_SUCCESS;
}                                                                                                                                                                                                                           

Edit. Valgrind output

  1. valgrind --tool=massif --massif-out-file=memleak.txt ./createNewWorld
heap_tree=detailed
n2: 6636657886 (heap allocation functions) malloc/new/new[], --alloc-fns, etc.
 n2: 6626476282 0x5160B89: std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::_M_mutate(unsigned long, unsigned long, char const*, unsigned long) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.25)
  n2: 6626476282 0x5162131: std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::_M_append(char const*, unsigned long) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.25)
   n0: 6626476033 0x149F38: main (in /home/code/hello_world/createNewWorld)
   n0: 249 in 2 places, all below massif's threshold (1.00%)
  n0: 0 in 2 places, all below massif's threshold (1.00%)
 n0: 10181604 in 18 places, all below massif's threshold (1.00%)
  1. valgrind --leak-check=full --show-leak-kinds=all --track-origins=yes --verbose --log-file=valgrind-out_1.txt ./createNewWorld
...
--4758-- memcheck GC: 1000 nodes, 0 survivors (0.0%)
--4758-- memcheck GC: 1000 nodes, 0 survivors (0.0%)
--4758-- memcheck GC: 1000 nodes, 0 survivors (0.0%)
--4758-- memcheck GC: 1000 nodes, 0 survivors (0.0%)
==4758== Warning: set address range perms: large range [0xee015040, 0x1b37d5041) (undefined)

Problem with cin which does not provide correct results

The following code is not mine. It's taken from Think Like a Programmer by Anton Spraul. The book pretends to use cin in a way it can get multiple inputs before the user hits Enter, with logic between them. Here's the code:

#include <iostream>
using namespace std;

main()
{
    cout << "Enter a number with as many digits as you like: ";
    char digitChar = cin.get();
    int number = (digitChar - '0');
    digitChar = cin.get();
    while(digitChar != 10){
        number = number * 10 + (digitChar = '0');
        digitChar = cin.get();
    }
    cout << "Number entered: " << number << "\n";
}

As you can see the cin.get() is used multiple times, this suggests that after the user type any digit, the code continues to run even if the user has not hit the Enter key. It doesn't make any sense to me, and it doen't work neither (for example if I enter "719" I get 1228 as a result", but my question is:

Is this code correct and the problem is due that it only work under some compileres and not under others or does it contain errors the author didn't care to check?

I noticed the same problem every time the book use cin.get() in this, apparently incorrect, way.

So to summarize: Is the code correct? Why does it produce incorrect results? If the code is correct, how does cin.get() may work this way?

Any insight will be appreciated.

Ah I almost forgot: I tried this code using GCC under Windows 10.

Can someone tell me the difference when i used

Can someone tell me the difference when i used i = a[s[j]] + 1; and i = max( i , a[s[j]] +1); Also according to me there is no use of giving max function. I GUESS

public:
    int lengthOfLongestSubstring(string s)
    {
        map<char,int> a;
        int len=0 , i = 0 , j = 0 ;
        int n = s.length();
        
        while(j<n)
        {
            if( a.find(s[j])!=a.end() )
                 i = max(i , a[s[j]] + 1);
            
            a[s[j]] = j;
            len = max(len , j - i + 1);
            j++;
        }
        
        return len;
    }
};
            if( a.find(s[j])!=a.end() )
                 i = a[s[j]] + 1;

Difference between determination & evaluation of a value of an expression

I am studying order of evaluation of expressions and I came across this paragraph,

A constant expression is an expression that consists of only constant values. It is an expression whose value is determined at the compile-time but evaluated at the run-time. It can be composed of integer, character, floating-point, and enumeration constants.

Resource of paragraph: https://www.javatpoint.com/cpp-expression

Can someone elaborate what does determining a value & evaluating a value means ? aren't these the same. . .

Also, I landed to this paragraph after reading the following definition,

**Evaluation of Expressions

Evaluation of each expression includes:

value computations: calculation of the value that is returned by the expression. This may involve determination of the identity of the object (glvalue evaluation, e.g. if the expression returns a reference to some object) or reading the value previously assigned to an object (prvalue evaluation, e.g. if the expression returns a number, or some other value)

Initiation of side effects: access (read or write) to an object designated by a volatile glvalue, modification (writing) to an object, calling a library I/O function, or calling a function that does any of those operations.**

Resource: https://en.cppreference.com/w/cpp/language/eval_order

Kindly, explain (1) what does calculation of value means. An expression could be a function returning some value so what has to be calculated about that returned value?

(2) What does identification of an object means?

How to check if object is castable?

I have following classes:

class ATemperatureDevice{};
class AHumidityDevice{};

class BluetoothLeDevice{};

class Sensor1 : BluetoothLeDevice, ATemperatureDevice, AHumidityDevice {};
class Sensor2 : BluetoothLeDevice, AHumidityDevice  {};

I have a vector<BluetoothLeDevice>, where all devices are stored.

The Classes ATemperatureDevice, AHumidityDevice and BluetoothLeDevice have virtual functions.

When I pick one, I have a BluetoothLeDevice. Now I want to check if it derives from ATemperatureDevice and/or AHumidityDevice.

I tried dynamic_cast, when its not castable, I should get null but, it says "'dynamic_cast' not permitted with -fno-rtti" although they have virtual functions.

What's the best way to check and cast?

Alternative to heapallocation when returning a uppcasted pointer in a method

The problem that I have is that I'm not allowed to use any heap allocation. And I've got a function that needs to return a pointer to an abstract class.

Example:

class Base
{
public:
    virtual Base* func() = 0;
};

class Foo : public Base
{
    Base* func() override
    {
        // return new Foo{}; // usual approach with heap allocation

        // Foo result{}; // undefined behaviour.
        // return &result;
    }
};

This example might be a little over simplified, but it shows the problem. How could I implement Foo::func without heap allocation?

Can decltype make less recompilation

I'm working on a cpp project, let's say there is such a piece of code:

// header1.h
struct Test {
    int a;
    bool func(int b) { return a < b; }
};

// header2.h
#include "header1.h"
void myfunc(int aa) {
    Test t;
    t.a = aa;
    bool res = t.func(3);
    // something else
}

// header3.h
#include "header1.h"
void myfunc(decltype(Test::a) aa) {   // CHANGED HERE
    Test t;
    t.a = aa;
    bool res = t.func(3);
    // something else
}

I was always coding like headedr2.h. But today, I got such a case, where the type of Test::a in the header1.h may change into uint8_t, int32_t etc in the future. If it changes, the header2.h should be changed too. (I don't want to make any implicit-conversion.)

That means, if header1.h changes, I have to change header2.h, as a result, all of files including header2.h have to be recompiled.

Now, I'm thinking if it is possible to use decltype just like header3.h to avoid recompilation. In other words, I'm asking if I code header3.h instead of header2.h, is it possible to avoid recompilation of the files which included header3.h after changing the type of Test::a in header1.h?

dimanche 25 juillet 2021

How to put the iterator to nth element of a custom class?

I have a custom class MyData.

class MyData
{
  private:
      int data;
  public:
      int getData() const
          {
        return data;
      }
      MyData(int val): data(val) { cout<<"Constructor invoked"<<endl; }
      MyData (const MyData &other) 
          {
         cout<<"Copy constructor invoked"<<endl;
         data = other.data;
      }
      MyData& operator =(const MyData &other)
      {
          cout<<"Assignment operator invoked"<<endl;
          data = other.data;
          return *this;
      }
      friend ostream& operator<<(ostream &os, const MyData &d)
          {
           cout<<"<< operator overloaded"<<endl;
           os<<d.data;
           return os;
      }
};

in my main function, I have

list<MyData> data2{12,21,32,113,13,131,31};

I want my iterator to 4th element let's say directly rather than doing increment++ operation each time. How can I do so?

list<MyData>::iterator it = data2.begin();
it+=4; //error since I cannot increment this???-compile time error.

I am doing like this -

it++; it++; it++; it++; 

What is the correct way so that the iterator directly points to the 4th element?

I tried using advance like advance(data2.begin(),3);. However, this throws an error saying

error: cannot bind non-const lvalue reference of type ‘std::_List_iterator<MyData>&’ to an rvalue of type ‘std::__cxx11::list<MyData>::iterator’ {aka ‘std::_List_iterator<MyData>’}
   data1.splice(it, data2,advance(data2.begin(),3),data2.end()); //splice transfer range.

Basically, I am doing this for splicing the list from another list with one element or some time range.

Out of memory C++

When I click compile and run, the program still running well. But when I click Debug, a window appears and says
"An unexpected error has occured in the application
Address: 0x003ED404
Error message:Out of memory"
instead of the debug console. This happens to all .cpp file,even a simple file "Hello World!" like this

#include<bits/stdc++.h>
using namespace std;
int main(){
  cout << "Hello,World!";
}


When I close DevC++,this window appears ClickHere
Help me I am using Embarcadero 6.3,compiler GNU C++11

Template function to FindComponentByClass in Unreal Engine

I'm trying to define a function to take UActorComponent as an argument and use FindComponentByClass to initialize based on its classType, so I used template as follow:

template<class T>
void FindActorComponent(T *aComponent){
    aComponent = GetOwner()->FindComponentByClasss<T>();
    if(aComponent) //doSomething;
    else //doOther;
}

However, I found that the passed object by pointer(aComponent) came out nullptr from function, although it's not after initializing inside it!

So, I searched for a solution for the situation and found this: Pass pointer by reference, and after trying it by changing the argument from (T *aComonent) to (T *&aComponent) I found it working!

Can anyone explain to me the concept behind this, and why it didn't affect the passed object although it's passed by pointer?

Also if I want to execute some functions based on passed class type(like if it's UInputComponent to BindAction), how should I do this? I tried to use GetClass() but I couldn't go anywhere with it!

Thanks in Advance.

What happens when std::istream_iterator

i am learning about iterators by checking/writing different examples. In one such example(given below) when i enter an invalid type say char into the input stream the next cout statement is not executed. The example is as follows:

#include <iostream>
#include <iterator>
int main()
{
   
    std::istream_iterator<int> starting_it(std::cin), ending_it;
   
    while(starting_it != ending_it)
    {
       
       *starting_it++;//lets say i entered the character f on the console and pressed enter then why is the next cout statement not executed
       std::cout<<"after"<<std::endl;//this line is not printed on the console after an invalid type is encountered
    }
    return 0;
}

Now when i execute this program and enter the values say 1 2 f and then press enter, then only two "after" are printed on the console. My question is why isn't "after" printed 3 times on the screen?

This is what i think is happening:

Step 1. Since at the beginnnig starting_it and ending_it are not equal we go inside the while loop.

Step 2. Now, starting_it is incremented and also at the same time a value is read from cin.

Step 3. Next, the old value of starting_it is returned on which we apply the * operator. This in the current iteration has value 1 which is discarded at the end of the statement. Next cout<<"after"<<std::endl; is executed and printed on the console.

Step 4. Now again since we have not encountered end of file or any input error so we go to the next iteration of the while loop.

Step 5. Step1-Step4 are repeated. The only difference this time is that at the end of Step4 when we dereference starting_it we get the value 2.

Step6 . Now again we go into the next iteration. But this time when starting_it is incremented, an invalid type of char is read and so starting_it is made equal to the end iterator.

Now my question is that in the step the statementstd::cout<<"after"<<std::endl should be executed and "after" should be printed on the console.And then the condition of while should be checked which comes out to be false. But why isn't this happening? Why do we have only two "after" printed on the console instead of 3. Is this because ostream is also in error. Effectively, it seems whenever we encounter an error or eof on input stream, we break out of the while loop. Also, is my explanation correct, if not then please correct me.

I have attached the screenshot of the output.

screenshot

what is the difference between iter++->empty() and ++iter->empty()?

Assuming that iter is a vector<string>::iterator.

  1. I have understood that ++iter->empty() is illegal, ISO C++17 does not allow incrementing expression of type bool, indicating that ++iter->empty() equals ++(iter->empty()).
  2. Based on (1), why iter++->empty() doesn't equal (iter->empty())++ or ((*iter).empty())++, but equals (*iter++).empty()? thank you very much!

samedi 24 juillet 2021

c++ slove in coolegcwa

q1/Print a program to write numbers from) 10 - 20 (when the statement become before condition? *

q2/Use (if >>>else ) to compaire between (a=10 )and (b=20),If a < b print (a) , else print( b) *؟

Simple Input validation - cin.ignore (error)

I have this problem while watching tutorials and make one for myself. I can't get a hold of this cin.ignore(). I want the user to type characters only but if he types any integer, it should continue looping until he gets the correct input.

This is my code along with the error mentioned.

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

// simple io validation
int main(){
    char name{};
    char last{};
    int birthday {};
    cout << "Pls Enter your first name: ";
    cin>>name;   // if he type "alfred123 Philip" it should error
    while (!cin.good())  // or while cin.fail()
        {
        cout<<"Please enter character only"<<endl;
        cin.clear();
        cin.ignore(INT_MAX,"/n");  //error no instance of overloaded function "std::basic_istream<_CharT, _Traits>::ignore [with _CharT=char, _Traits=std::char_traits<char>]" matches the argument list
        cout<<"Enter Name: ";   // ask again the user
        cin >> name;

        }
    cout << endl;
    cout<<"Hello "<<name<<endl;
    return 0;
}

How to unfold a template to string when the possible type be float or string?

In C++, i want to build a string only container from a template.

For example:

template<typename T>
void show(const T & t) {  // the T can be map<string, string> or <string, float> or <string, int>
  std::unordered_map<std::string, std::string> r;
  for (const auto & i : t) {
     const auto & j = i.first;
     const auto & k = i.second;  //  TODO: how to
     // make k as string, possible type of k can be 
     // int float or string???
     // put them into r
  }
  return r;
}

How can i implement this?

Dynamic loading libpython with pybind11

I'm trying to build some shared library with pybind11 from Mac OSX. I'm running into the error:

dyld: Symbol not found: _PyBaseObject_Type
  Referenced from: /Users/xxxxx/work/test_dynamic_linking/./example
  Expected in: flat namespace
 in /Users/xxxxx/work/test_dynamic_linking/./example
Abort trap: 6

What I'm trying to achieve is to turn off build time linking, but dynamic loading libpython in runtime with dlopen. Note the -Wl,-undefined,dynamic_lookup flag in the cmake file. I'm doing it this way because I want to build a wheel, and linking to libpython is not a good idea AFAIU.

Below is a minimial reproducible example. I'm confused that if you call functions like Py_DecodeLocale() or Py_InitializeEx() directly from main.cpp, it works fine. But calling pybind11::initialize_interpreter() fails with the error above. If I do

nm -gU /opt/anaconda3/envs/py38/lib/libpython3.8.dylib | grep PyBaseObject

the symbol _PyBaseObject_Type is indeed defined in the lib:

0000000000334528 D _PyBaseObject_Type

If I create a wrapper shared library which wraps the calls to pybind11 functions, and dlopen it from main.cpp, it works fine. This makes me more confused.

Cmake file:

cmake_minimum_required(VERSION 3.4)
project(example)
set (CMAKE_CXX_STANDARD 11)
set(UNDEFINED_SYMBOLS_IGNORE_FLAG "-Wl,-undefined,dynamic_lookup")
string(APPEND CMAKE_EXE_LINKER_FLAGS " ${UNDEFINED_SYMBOLS_IGNORE_FLAG}")
string(APPEND CMAKE_SHARED_LINKER_FLAGS " ${UNDEFINED_SYMBOLS_IGNORE_FLAG}")
include_directories(pybind11/include)
include_directories(/opt/anaconda3/envs/py38/include/python3.8)
add_library(pywrapper SHARED ${CMAKE_CURRENT_SOURCE_DIR}/wrapper.cpp)
add_executable(example main.cpp)

pyembed.hpp:

#pragma once

#include "pybind11/embed.h"

namespace py = pybind11;

void initialize_interpreter_func();


struct pybind_wrap_api {
    decltype(&initialize_interpreter_func) initialize_interpreter;
};

wrapper.cpp:

#include "pyembed.hpp"

#include <set>
#include <vector>
#include <iostream>

#include "pybind11/embed.h"
#include "pybind11/stl.h"

namespace py = pybind11;


void initialize_interpreter_func() {
    pybind11::initialize_interpreter();
}

pybind_wrap_api init_pybind_wrap_api() noexcept {
    return {
        &initialize_interpreter_func,
    };
}

__attribute__((visibility("default"))) pybind_wrap_api pybind_wrapper_api =
    init_pybind_wrap_api();

main.cpp:

#include <pybind11/embed.h> // everything needed for embedding                                                                                                    

#include "pyembed.hpp"

#include <stdlib.h>
#include <dlfcn.h>
#include <iostream>
#include <string>

namespace py = pybind11;
static void* pylib_handle = nullptr;
static void* pybind_wrapper_handle = nullptr;
pybind_wrap_api* wrappers = nullptr;

int main() {
    std::string path_libpython = "/opt/anaconda3/envs/py38/lib/libpython3.8.dylib";
    pylib_handle = dlopen(path_libpython.c_str(), RTLD_NOW | RTLD_GLOBAL);
    if(!pylib_handle) {
        std::cout << "load libpython failed..." << std::endl;
    } else {
        std::cout << "load libpython succeeded..." << std::endl;
    }

    std::string path_wrapper = "./libpywrapper.dylib";
    pybind_wrapper_handle = dlopen(path_wrapper.c_str(), RTLD_NOW | RTLD_GLOBAL);
    wrappers = static_cast<pybind_wrap_api*>(dlsym(pybind_wrapper_handle, "pybind_wrapper_api"));

    std::string pythonhome = "/opt/anaconda3/envs/py38";
    setenv("PYTHONHOME", pythonhome.c_str(), 1);
    std::string pythonpath = "/opt/anaconda3/envs/py38/lib/python3.8/site-packages";
    setenv("PYTHONPATH", pythonpath.c_str(), true);

    // this line will cause it to fail with the symbol not found error
    py::initialize_interpreter();
    // if comment out the previous line and do the following line, it works fine. I'm confused why is so. 
    //wrappers->initialize_interpreter();

    return 0; 
} 

Then do

cmake . && make && ./example 

C++ variadic template for validation

I have a class which initially tries to read settings from a configuration and if the values are invalid, they should be populated with a default. This is what I got (custom Optional implementation):

    template <typename T>
    struct dont_deduce { using type = T; };

    template <typename T>
    using dont_deduce_t = typename dont_deduce<T>::type;

    template<typename T>
    static bool clamped(const T& val, const Optional<T>& lower, const Optional<T>& upper){
        if(lower.has_value() && val < lower.value())
            return false;
        if(upper.has_value() && val > upper.value())
            return false;
        return true;
    }

    template <typename X, typename ... PP>
    inline void readSettingOrPopulateDefault(X& property, const QString& key, X default_val, QSettings& settings, std::function<bool(dont_deduce_t<X>, dont_deduce_t<PP> &&... pp)> validator, PP &&... pp) const{
        property = qvariant_cast<X>(settings.value( key, QVariant()));
        if (!validator(property, std::forward(pp) ...))
        {
            property = default_val;
            settings.setValue(key, QVariant(property));
        }
    }

when calling the method (default is of type uint32_t):

 readSettingOrPopulateDefault(m_query_interval_sec, KEY_QUERYINTERVAL, DEFAULT_QUERY_INTERVAL, settings, &clamped, Optional<uint32_t>(0),  Optional<uint32_t>());

this error occurs:

error: no matching member function for call to 'readSettingOrPopulateDefault'
note: candidate function [with X = unsigned int, PP = <Optional<unsigned int>, Optional<unsigned int>>] not viable: no overload of 'clamped' matching 'std::function<bool (dont_deduce_t<unsigned int>, dont_deduce_t<Optional<unsigned int>> &&, dont_deduce_t<Optional<unsigned int>> &&)>' (aka 'function<bool (unsigned int, Optional<unsigned int> &&, Optional<unsigned int> &&)>') for 5th argument

I don't get why it does not consider clamped as a viable overload.

This code allows the user to specify the file name to be created. When the file is created, it does not have a .txt extension. How do i fix this?

#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main()
  {

//Declaring file.

  ofstream f;
  string filename;

  cout << "Please enter a file name to write: ";
  getline( cin, filename );

//If you can also explain what .c_str() does here that would be awesome.

  f.open( filename.c_str() );
  f << "Hello world!\n";
  f.close();

  cout << "Good job! 'type' or 'cat' your new file to see what it says.\n";
  return 0;
  }

How does vector class takes multiple argument and create a array out of it?

vector example

vector<int> a{ 1,3,2 }; // initialize vectors directly  from elements
for (auto example : a)
{
    cout << example << " ";   // print 1 5 46 89
}
MinHeap<int> p{ 1,5,6,8 };    // i want to do the same with my custom class   

Any idea how to do accept multiple arguments in curly braces and form an array?

std::vector class uses std::allocator to allocate memory, but I do not know how to use this in a custom class. VS Code shows std::allocator

I have done the same but it does not work like that

template<typename T>
class MinHeap
{
    // ...
public:
    MinHeap(size_t size, const allocator<T>& a)
    {
        cout << a.max_size << endl;
    }
    // ...
};

noob here ....