vendredi 30 avril 2021

std::bind arguments not matching function parameters?

I'm trying to pass a socket along a connection handshake, and use std::bind to do so. The compile issue I'm getting (in one continuous block, which I've added spaces to for readability) is:

'std::_Bind<_Functor(_Bound_args ...)>::_Bind(_Functor&&, _Args&& ...) 

[with _Args = {socket_state**, std::function<void(socket_state*)>&, boost::asio::basic_socket_acceptor<boost::asio::ip::tcp, boost::asio::executor>&, boost::asio::io_context&}; 

_Functor = void (*)(socket_state*, std::function<void(socket_state*)>&, boost::asio::basic_socket_acceptor<boost::asio::ip::tcp>&, boost::asio::io_context&); 

_Bound_args = {socket_state**, std::function<void(socket_state*)>, boost::asio::basic_socket_acceptor<boost::asio::ip::tcp, boost::asio::executor>, boost::asio::io_context}]':

My code is below, with the error appearing to nag at the std::bind arguments given to boost::asio::acceptor.async_accept(socket, ...) and the parameters for the accept_new_client method

    void start_server(std::function<void(socket_state*)>& func, tcp::acceptor& acceptor, boost::asio::io_context& context)
    {
        acceptor.listen();
        // Start client connection loop
        networking::wait_for_client(func, acceptor, context);
    }

    void wait_for_client(std::function<void(socket_state*)>& func, tcp::acceptor& acceptor, boost::asio::io_context& context)
    {
        boost::asio::ip::tcp::socket socket(context);

        // socket_state is its own class which links a particular socket with an ID and buffer data
        // it also holds a function to indicate which part of the connection handshake it needs to go to next
        socket_state* state = new socket_state(func, &socket);
        acceptor.async_accept(socket, std::bind(&networking::accept_new_client, state, func, acceptor, context));
    }

    void accept_new_client(socket_state* state, std::function<void(socket_state*)>& func, tcp::acceptor& acceptor, boost::asio::io_context& context)
    {
            state->on_network_action(state);
            wait_for_client(func, acceptor, context);
    }

It seems like they would match, but you can see the error state my std::bind arguments are socket_state** instead of socket_state*, and boost::asio::basic_socket_acceptor<boost::asio::ip::tcp, boost::asio::executor>& instead of boost::asio::basic_socket_acceptor<boost::asio::ip::tcp>&.

I have no idea what the "with _Args" vs. "_Bound_args" is either.

Where is the memory location of list of objects (list

class InnerObj{
// implementation
};

class OuterObj{
public:
   void innerObjFactory() { my_innerObjs.pushback( ########## <Q2> ########## )}; // line Q2

private:
   list<InnerObj> my_innerObjs;
};

int main(int argc, char *argv[])
{
 ########## <Q1> ##########; // line Q1
}

So my question is considering the 4 combinations:

line Q1 line Q2
created in the stack (ex: OuterObj aa;) created in the stack (ex: InnerObj(); )
created in the stack (ex: OuterObj aa;) created in the free store/heap (ex: new InnerObj(); )
created in the free store/heap (ex: OuterObj *aa = new OuterObj();) created in the stack (ex: InnerObj(); )
created in the free store/heap (ex: OuterObj *aa = new OuterObj();) created in the free store/heap new InnerObj();

Where in memory (free store or stack) is the objects at line Q2 are created?

c++ error in my thread constructor passing the function

I'm trying to make a thread every time a call a function from a class, but i can't pass the function correctly:

file.h

#include <thread>

class Class
{
public:
    Class(int a);
    void ThreadBase(void (*func));
    int CreateThread(void (*func));
};

file.cpp

#include <thread>
Class::Class(int a)
{
    /**
     *  ...
     */
}

void Class:ThreadBase(void (*func))
{
    while(1)
    {
        /**
         *  ...
         */
    }
}

int Class:CreateThread(void (*func))
{
    std::thread th(Class::ThreadBase, func);
}

Error:

error: reference to non-static member function must be called

implementation of swap in c++ [duplicate]

Started to learn some C++ for competitive programming (already know some other languages) However got in a thinking for swap function of C++. Looked several resources including this one and this one also (Although the later one was a bit jargon for me(exhaling)). Most of them just tell what swap() do... ok, now I know what it do but I'm wondering How it's different form other common swap methods?

For example, If I have two numbers a and b than, a ^= b ^= a ^= b will also swap a and b

Infact, in general any object(same type as a and b) can be swapped with:

object temp = a;
a = b;
b = temp;

Obviously this will have overhead of creating extra object. But it's very simple to write... than why a specially dedicated inbuilt swap() is there? Does it have better performance and if so, how it's implemented without using third variable (thinking emoji) ? Or it's just for sake of completion?

Multithreading implementation in threads

I am in process of implementing messages passing from one thread to another

Thread 1: Callback functions are registered with libraries, on callback, functions are invoked and needs to be send to another thread for processing as it takes time.

Thread 2: Thread to check if any messages are available(preferrednas in queue) and process the same.

Is condition_variable usage with mutex a correct approach to start considering thread 2 processing takes time in which multiple other messages can be added by thread 1?

determine if function argument is a sequence in C++?

On my way to write a simple traversal through auto generated data structures I was wondering why type_traits do not provide sth. like std::is_sequence.

I am using this make_array :

template <typename... T>
  constexpr auto make_array(T&&... values) 
  -> std::array< typename std::decay< typename std::common_type<T...>::type>::type, sizeof...(T)> {
    return {std::forward<T>(values)...};
  }

to create structures like this:

auto z = make_array(
    make_array('h','e','l','l','o'),
    make_array('w','o','r','l','d')
 );

The elements could be of different types and dimensions as well. Later I'd like to support more complex uses such as func(1,2,MyClass(3),4.0,make_array(5,6,7),std::make_tuple(8.0,"9.1011",12)) ,or func({13,14,15}), but that I consider as a 2nd step ... ;)

(Whether or not such ideas will ever make it into my project I don't yet know. I am just curious ...)

My approach is to write two overloaded, templated functions func:

template<typename T>
typename std::enable_if<!is_sequence<T>::value, void>::type
func(T& t) {
  std::cout << "\n\tfunc(t) => " << t << ' ';
}


template<typename SeqT> 
typename std::enable_if<is_sequence<SeqT>::value, void>::type
func(SeqT&  s) {
  std::cout << "\nfunc(SeqT& s)...";
  for(auto iter=std::begin(s);iter!=std::end(s);++iter) func(*iter);
  std::cout << "\n...func(SeqT& s)...";
}

And with the help of

template <typename T>
class is_sequence {
private:
    typedef char YesType[1];
    typedef char NoType[2];

    template <typename C> static YesType& test(decltype(std::begin(C{})));
    template <typename C> static NoType& test(...);

public:
    enum { value = sizeof(test<T>(0)) == sizeof(YesType) };
};

(idea stolen from https://www.bfilipek.com/2016/02/notes-on-c-sfinae.html)

it seams to work:

func(z);

prints

func(SeqT& s)...
func(SeqT& s)...
        func(t) => h 
        func(t) => e 
        func(t) => l 
        func(t) => l 
        func(t) => o 
...func(SeqT& s)
func(SeqT& s)...
        func(t) => w 
        func(t) => o 
        func(t) => r 
        func(t) => l 
        func(t) => d 
...func(SeqT& s)
...func(SeqT& s)

Here come my questions:

(1) I don't think my need and general approach is soo special. But the wise C++ guys obviously did not see the need to put sth. like ```is_sequence''' into the standard. What am I missing then ?

(2) What other suggestions do you have for me ?

When does instantiation happens for explicit instantiation of a function template

Hi i am trying to learn about explicit instantiation. And so reading different examples but in one example have some doubts. The example is given below and i have 2 doubts in this particular example.

File Application.cc contains:

extern template int compare(const int&, const int&);
int i = compare(a1[0], a2[0]);// instantiation will appear elsewhere

File templateBuild.cc contains:

template int compare(const int&, const int&);

Also note that the function template compare is:

template<typename T, typename F = less<T>>
int compare(const T &v1, const T &v2, F f = F())
{
  if (f(v1,v2)) return -1;
  if (f(v2,v1)) return 1;
  return 0;
}

My questions are as follows:

  1. As you can see in the Application.cc file in the 2nd line it is written(as a comment) that instantiation will appear elsewhere. But here we are using the template function as int i = compare(a1[0], a2[0]); and we know that whenever we use a template function the compiler will instantiate it. So why is that comment written there? Also in the explanation it is written that

When the compiler sees an instantiation definition (as opposed to a declaration), it generates code. Thus, the file templateBuild.o will contain the definitions for compare instantiated with int.

So my question is if the compiler generates code whenever it sees an instantiation definition and so templateBuild.o will contain the definition of compare instantiated with int then how can we use compare() in the Application.cc file using compare(a1[0], a2[0]);? I mean the compare() template is not yet instantiated so how can we use it before it is instantiated?

  1. My 2nd question is that where should i write(put) the content of the compare() template. For example in a header file or in the Application.cc file? By the content of the compare() template i mean the 3rd block of code that i have given in the example.

jeudi 29 avril 2021

How does the C++ algorithm library check the range of the output and not create segfaults when it is smaller than the range of the input?

I was just curious how some of the C++ algorithms check the range of the result/output container when you only provide the range of the input? For example, for the following code

#include <iostream>
#include <algorithm>

int main()
{
  std::vector<int> a = {4, 2, 1, 7};
  std::vector<int> b = {1, 2};
  
  std::copy(a.begin(), a.end(), b.begin());
  for(auto val : b)
    std::cout << val << std::endl;
}

with the output:

4
2

I don't understand how the algorithm knows that the capacity of the output container b is 2. I would have expected it assumes just the same range as the input container and therefore generates some kind of segmentation fault.

C++, how to open and close files properly?

I want to open some file, redirect the output their and go back to previous situation, so I wrote:

int fd = open("test.txt", O_WRONLY | O_CREAT, 0666);
dup(1);
dup2(3, 1);
close(3);
//call my func() to print in std::cout which will write to test.txt
dup2(4, 1);//Close file

I know that default input channel is in index 0, output channel (screen) in index 1 and stderr in index 2 so fd will get 3, dup 1 will create another pointer to output channel in index 4, then I replace screen with my file and close that isn't needed.

  1. My code is correct, but did I forget anything else or can it be made shorter/ more clear?

  2. Most importantly, in case one line fails I want to return false but this will be a lot of checks and in every advance step we need to close more... how can I solve this problem? what if I wanted in case of failure to make everything go back to its default situation?

Please Note, I only know and want to use open,close,dup,dup2

How to insert spaces to string

I had multiple tries but failed all of them.

I am trying to write a function that sets space before first occurrence of > and another one after last occurrence of > how can I do that in C++11?

let's suppose my function is:

void add_space(string &e_cmd_line)
{
int f_ocu=e_cmd_line.find_first_of(">");
e_cmd_line.insert(f_ocu," ");
int l_ocu=e_cmd_line.find_last_of(">");
e_cmd_line.insert(l_ocu+1," ");

}

The main problem is that sometimes it returns bad signals, in case no > found and in e_cmd_line.insert(l_ocu+1," "); I can't know for sure there is l_ocu+1...

Getting passing ‘const std::map

Here is a basic code snippet for which I'm getting an error:

error: passing ‘const std::map<int, bool>’ as ‘this’ argument discards qualifiers [-fpermissive]`

struct Point {
    float x;
    float y;
    int id;
    Point(float x, float y, float id) : x(x), y(y), id(id) {}
};

void removePoints(std::vector<Point> &points_vec) {
    std::map<int, bool> my_map;
    for (const auto& pt : points_vec) {
        if(pt.id < 0) 
            my_map[pt.id] = true;
        else
            my_map[pt.id] = false;
    }

    points_vec.erase(std::remove_if(points_vec.begin(), points_vec.end(), [map_lambda = my_map] (const Point pt) -> bool {
        return map_lambda[pt.id];
    }), points_vec.end());
}

int main(int argc, char const *argv[]) {
    std::vector<Point> points_vec;
    points_vec.push_back(Point(1, 2, 0));
    points_vec.push_back(Point(1, 5, -1));
    points_vec.push_back(Point(3, 3, -1));
    points_vec.push_back(Point(4, 9, 2));
    points_vec.push_back(Point(0, 1, 3));
    points_vec.push_back(Point(-1, 7, -2));

    std::cout << points_vec.size() << std::endl;
    removePoints(points_vec);
    std::cout << points_vec.size() << std::endl;
    
    return 0;
}

Note: I know I can remove points without using std::map, but the above code snippet is just an example of a bigger problem.

I checked some questions on a similar error:

  1. error: passing ‘const std::map<int, int>’ as ‘this’ argument discards qualifiers [-fpermissive]
  2. C++ "error: passing 'const std::map<int, std::basic_string<char> >' as 'this' argument of ..."

But in both of them, it was because of the fact that std::map has been declared as const. On the other hand, the map I'm trying to use/access has not been declared as const, and my error is also related to a lambda. As you can see, I'm creating a copy of the original my_map in the lambda capture list as map_lambda = my_map. So, why am I'm getting this -fpermissive error? Or, when we capture something in a lambda, does it automatically get converted to const?

Detailed error message:

main.cpp: In lambda function:
main.cpp:26:32: error: passing ‘const std::map<int, bool>’ as ‘this’ argument discards qualifiers [-fpermissive]
         return map_lambda[pt.id];
                                ^
In file included from /usr/include/c++/7/map:61:0,
                 from main.cpp:2:
/usr/include/c++/7/bits/stl_map.h:484:7: note:   in call to ‘std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const key_type&) [with _Key = int; _Tp = bool; _Compare = std::less<int>; _Alloc = std::allocator<std::pair<const int, bool> >; std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type = bool; std::map<_Key, _Tp, _Compare, _Alloc>::key_type = int]’
       operator[](const key_type& __k)
       ^~~~~~~~

On a side note, I know the operator[] returns the value if the key already exists, otherwise it creates a new key and inserts the value (and returns it). But why does const for std::map::operator[] give a compilation error? Shouldn't it be more of like a runtime error instead?

Use std::move when receiving function output

I have seen lots of discussions about using std::move on a function return value (like this), and I know it's unnecessary for these cases. But what if I want to use the std::move semantic when receiving a function output like the codes below:

std::vector<double> funcA()
{
    std::vector<double> out(10000, 0.0);
    return out;
}

int main()
{
    auto out = std::move(funcA());
    return 0;
}

Is this a good use case for std::move? My understanding is move here can avoid a copy of the returned vector, especially when the vector size is very large. Please correct me if I'm wrong. Thanks so much!

Visual Studio 2019 - "C++ Language Standard" [duplicate]

How to add C++/11 or 98 support to Visual Studio 2019?

enter image description here

How to set up a Shiboken2 environment from start to finish?

I'm trying to wrap a simple Qt widget of mine with Shiboken2, but I'm having no luck and the official documentation is not that helpful.

Every guide and tutorial I've found so far covers extensively the code part, but explains very little about the environment.

I'm running Windows 10 and compiling with MinGW 8.10 64 bit, the one installed by Qt. I've installed libclang and correctly set the necessary environmental variables. I've installed PySide2 from pip and also installed the generator wheel from qt page, but I can't get it to work. Do I have to build PySide2 from source?

I'd like to set up Shiboken in a virtual environment, but right now I can't even make the easiest "hello world" binding...

C++ accepting command line argument with "-" symbol

I am new to c++ and trying to read command line arguments specified as below.

./helloworld -i input_file -o outputfile -s flag3 -t flag4

I tried hardcoding the flags by index as below

int main(int argc, char *argv[]) {
 // argv[1] corresponds to -i
 // argv[2] corresponds to input_file
 // argv[3] corresponds to -o
 // argv[4] corresponds to outputfile
 // argv[5] corresponds to -s
 // argv[6] corresponds to flag3
 // argv[7] corresponds to -t
 // argv[8] corresponds to flag4

}

Then i realized the order can be changed so I can't use hardcoded index, I used a unordered_map<string, string> to put the -i, -o, -s, -t as keys and inputfile, outputfile, flag3, flag4 as values.

This is working fine, but I was wondering is there any better way to do the same.

Why is move_iterator::operator-> deprecated in C++20?

As far as I know the reason it was removed.The expression (*i).m, where i is an iterator, and the expression i->m have the same semantics.Input iterators are required to support the -> operator, and move_iterator is an input iterator, so move_iterator’s arrow operator must satisfy that requirement.But I guess not like that.For a move_iterator, *i is an xvalue, so (*i).m is also an xvalue. i->m, however, is an lvalue.Consequently, (*i).m and i->m can produce observably different behaviors as subexpressions.Is this exactly why it is deprecated in C ++ 20 ? Are there any other concepts and disadvantages that should not be used ?whats the best practice about this ?

Passing smart pointer to function through non smart pointer argument

Consider the following function:

void example(void **ptr){
    std::cout << *ptr << "\n";                   // pointer value
    std::cout << ptr << "\n";                    // pointer address
    std::cout << **reinterpret_cast<int**>(ptr); // value
}

The function signature cannot be changed.

Is the following code valid, or should I use raw pointers?

int main() 
{
    std::unique_ptr<int> x = std::make_unique<int>(20);
    std::cout << x.get() << "\n";                 // pointer value
    std::cout << &x << "\n";                      // pointer address
    example(reinterpret_cast<void**>(&x));
}

Live sample

Memory leak after moving a std::string with placement new

I have a structure that contains a string and that structure is used in a vector. When the vector grows, all of the elements are moved to the new allocation. Unfortunately, this move also results in std::string leaking memory.

Here are a few minimum reproducible cases. This first example will illustrate where a memory leak occurs but sense can be made of it. The second example will cover the memory leak that has stumped me. The third will take it a step further.

int main(void)
{
  char* allocation = new char[sizeof(std::string)];
  std::string start("start");
  std::string* move = (std::string*)allocation;
  new (move) std::string(std::move(start));
  delete[] allocation;
}

Unsurprisingly, this results in a memory leak. The start string is constructed and memory should be allocated for the data. That string is then moved into move and remains there for the rest of the program. Because it has been moved, the destructor for move will not be called and this will result in a memory leak like the one below. The reason I am creating a character array is to avoid the constructor and destructor calls for the move string.

Detected memory leaks!
Dumping objects ->
{207} normal block at 0x00000278D16848C0, 16 bytes long.
 Data: <  g x           > D0 D7 67 D1 78 02 00 00 00 00 00 00 00 00 00 00
Object dump complete.

An interesting thing to note here is that the data < g x > does not contain the string used to initialize start, which probably indicates that this leak is not coming from the string`s buffer.

Now we'll add one line to the previous example in an attempt to remove the memory leak.

int main(void)
{
  char* allocation = new char[sizeof(std::string)];
  std::string start("start");
  std::string* move = (std::string*)allocation;
  new (move) std::string(std::move(start));
  start = std::move(*move); // The new line.
  delete[] allocation;
}

Now, instead of that string remaining in move until the end of the program, it is moved back into start and since start's destructor should be called, the string's allocation should be freed. However, when I run this, I still experience a similar memory leak.

Detected memory leaks!
Dumping objects ->
{207} normal block at 0x000001AE813FECC0, 16 bytes long.
 Data: <  @             > 80 15 40 81 AE 01 00 00 00 00 00 00 00 00 00 00
Object dump complete.

I also attempted this test with a single string allocation rather than allocating a character array and I still experience a similar memory leak with the code below.

int main(void)
{
  std::string start("start");
  std::string* move = new std::string;
  new (move) std::string(std::move(start));
  start = std::move(*move);
  delete move;
}

Why would this memory leak happen? Is there something about std::string that I am missing here or is my use of placement new somehow the culprit?

Additional Notes: Memory leak in placement new of standard library string - This question only covers my first example. It does not explain or cover the last two.

mercredi 28 avril 2021

assigning an object to C++ array

I am examining the following code in C++:


#include <iostream>

using namespace std;

class Person{
    int age;
    Person(int age){
        this->age = age;
    }
};

int main()
{
    Person a = Person(2);
    Person temp[] = {a};
    temp[0].age = 5;
    cout << temp[0].age;
    return 0;
}

So my guess is when one assigns an object to a slot of an array in C++, that is equivalent to copying that object into the array. Thus when we change that element in the array, it will not affect the original object. Is that correct?

C++ how to skip getline()?

I wrote the following simple C++11 program:

#include <iostream>
#include <signal.h>

void ctrlZHandler(int sig_num) {
    //SIGTSTP-18
    std::cout << "smash: got ctrl-Z" << std::endl;
}

int main(int argc, char *argv[]) {
    if (signal(SIGTSTP, ctrlZHandler) == SIG_ERR) {
        perror("smash error: failed to set ctrl-Z handler");
    }

    while (true) {
        std::cout << "my_bash> ";
        std::string cmd_line;
        std::getline(std::cin, cmd_line);
    }
    return 0;
}

it runs perfect when the user types something and presses enter, but when my program is waiting for input like this:

my_bash>

and then he presses ctrl+z I get:

my_bash> ^Zsmash: got ctrl-Z     
//Empty line here

How can I fix this?

I want something like normal terminal which is the following output:

my_bash> ^Zsmash: got ctrl-Z     
my_bash> 

In other words how can I tell getline to not-wait and go for next iteration?

Using declval with a reference type

I see some code examples where the type used to instantiate the std::declval template function is specified as a reference type rather than just a type, as in:

std::declval<T &>()

as opposed to:

std::declval<T>()

where T is some type. I am missing the subtlety why the reference notation might be chosen overe the plain type. Would someone please explain this to me ?

I know that std::declval expands to typename std::add_rvalue_reference<T>::type but I am still missing the reason why one would instantiate the latter with a reference to a type rather than the plain type itself.

List push_back triggers a segmentation fault error [closed]

I have a class which has a private list. I've declared it in my .hh file like this:

   class Course{

   private:

      int id;
      list<string> sessions;

   public:


   Course(int c);

   ~Course();

   void read_course();

and then again in my constructor on the .cc file (i don't know if i have to do this again). I want to have it so that the constructor initialises it as an empty list:

#include "Course.hh"
#include <list>
#include <iostream>
using namespace std;

Course::Course(int c){
    id = c;
    list<string> sessions;

}

Course::~Course(){}

void Course::read_course(){
  int s;
  string nom;
  cin >> s;
  for(int i = 0; i < s; ++i){
      cin >> nom;
      sessions.push_back(nom);
  }
}

The read_course() method, when called, has to store s strings to the list, and i do this with a for loop and .push_back():

My problem is that when i execute it it gives me a segmentation fault (core dumped) error. I have tried initialising the list as

sessions = new list<string>;

and other stuff that I've found online, but the examples were mostly for vectors and I couldn't figure out why this happens or how to solve it. Any help will be appreciated!

How to access type's index in the template type parameter pack?

I would like to access type's index when expanding a type parameter pack into an std::tuple<...>.

For example, given a type pack of <int, double, float> I would like to build an std::tuple<...> that looks as follows:

std::tuple<std::array<int,0>, std::array<double,1>, std::array<float, 2>>
//                     ^  ^                ^    ^                ^    ^
//                     T  I                T    I                T    I

Here is an implementation that does almost exactly what I want, but it works only for type packs of size 3 (see the comment next to the hack). How do I fix this to work independently of TT...s size?

#include <tuple>
#include <utility>
#include <array>
#include <iostream>

template <typename... TT>
struct Foo {
    template <std::size_t... Indices>
    struct Baz {
       std::tuple<std::array<TT,Indices>...> baz;
    };
    Baz<0,1,2> bar; // <<<=== Here is the hack: I make a fixed-size pack; I want it to match TT...
};

int main() {
    Foo<int,double,float> foo;
    std::cout << std::get<0>(foo.bar.baz).size() << std::endl;
    std::cout << std::get<1>(foo.bar.baz).size() << std::endl;
    std::cout << std::get<2>(foo.bar.baz).size() << std::endl;
    return 0;
}

Live demo.

specializing operator new and operator delete of some class

In order to selectively trace the allocations of particular types, I have created the following construct:

struct my_alloc {
    static void* operator new(size_t sz) { /*...*/ ; return calloc(1,sz); }
    static void operator delete(void *ptr) { /*...*/ ; return free(ptr); }
};

and whenever I wanted to follow the internal allocations of a particular type, say struct A, I could simply inherit from my_alloc:

struct A : my_alloc  
{  
    AImpl* p_impl;
    A() {
        p_impl = new AImpl; // will call my_alloc::operator new
    }
    ~A() {
        delete p_impl;
    }
};

A x();  // x.p_impl has been allocated via my_alloc

This was also useful to trace allocations in std containers:

using Vector = std::vector<some_class, my_alloc>;

Vector v; 
v.reserve(10);   // v.data has been allocated using my_alloc

However, sometimes I need to trace the allocations and I sometimes I don't. To allow that, I tried passing the allocator as a template parameter

template <class ALLOC>
struct A : ALLOC  {   /*...*/   }; 

but it doesn't always do the trick:

using A_alloced = A<my_alloc>;       // works fine
using A_non_alloced = A;             // does not does not compile

I also considered providing a default parameter:

template <class ALLOC = std::allocator>
struct A : ALLOC  {   /*...*/   }; 

but I am missing std::allocator's parameter.

  • Should I change the way I parameterize struct A (perhaps not inherit from my_alloc) ? , or
  • should I change the definition ofmy_alloc in order to achieve both the current functionality and the ability to customize struct A ?

PS: I am looking for a formulation that would also work for the following type-erased class! Note the new Model<B>() call, where Model<T> is not visible outside the class...

class MyType {
    struct Concept {
         virtual ~Concept() = default;
         virtual Concept* clone() const = 0;
    };

    template <class T>
    struct Model {
         T data;

         virtual Concept* clone() const { return new Model(*this); }

         template <class B> 
         Model(B value) : data(value) {}
    };

    Concept *self;
public:
    template <class B>
    MyType(B value) : self(new Model<B>(value)) {}
   
    MyType(const MyType &rhs) : self(rhs.self->clone()) { }
    
};

How to change the center of origin point on QCylinderMesh using Qt3D

usually the center of origin point for any shape is at the centre.

I want to change this to be at the bottom of the shape/cylinder.

How do I do this? I'm using At C++ and Qt 3D

How to copy a dynamically allocated object (with having one const member of a class)

I'm trying to make a function, where user can add an entry in the data, so the array dynamically increases it's size by 1 and allows the user to enter the data.

Logic:

  1. pass the current size and array pointer by reference to a function
  2. make a new pointer array (dynamically allocated) in the function, and increase it size by 1 .
  3. copy all the data from the passed array to newly made array
  4. delete the memory allocated to parameter pointer
  5. point the parameter pointer to new pointer array.

Problem: I have a const int member in the class,following the algorithm above, when I try to copy contents to new pointer,it's obvious that id would'nt be copied to const member. I have a hunch that I can use copy constructor here with a initialization list, and initialize the new array of the function with the help of copy constructor.

I need to know how to copy a dynamically allocated object array using copy constructor and moreover, if the object have some const member.

Thanks in advance.

CLASS HEADER:

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

class ramish
{
private:
    const int id;
public:
    void print()
    {
        cout << "ID = " << id;
    }
    ramish():id(rand()%100+1)
    {
    }
    //ramish(ramish *& object)
    //{
    //}
};

FUNCTION AND DRIVER:

int main()
{
   int size = 4;
   ramish* object = new ramish[size];
   copypointer(object, size);
}

void copypointer(ramish*& object, int size)
{
   ramish *newobject = new ramish[size + 1];
   for (int i = 0; i < size; i++)
   {
       newobject[i]=object[i];
   }
   delete[]object;
   //take inps from user for newobject[size]
   object = newobject;
   newobject = NULL;
}

std::_String_alloc destructor linker error

I am trying to link a third party static library with a DLL (say DLL A). But during linking, there is an error related to std::_String_alloc destructor. The error is as follows:

Error LNK2005 "public: __cdecl std::_String_alloc<struct std::_String_base_types<wchar_t,class std::allocator<wchar_t> > >::~_String_alloc<struct std::_String_base_types<wchar_t,class std::allocator<wchar_t> > >(void)" (??1?$_String_alloc@U?$_String_base_types@_WV?$allocator@_W@std@@@std@@@std@@QEAA@XZ) already defined in abc.lib(abc.dll)

The abc.dll also links with DLL A. The abc.dll explicitly instantiates the std::basic_string template and inherits the std::basic_string.

In order to solve above linker error (which clearly states that there are multiple symbols for std::_String_alloc destructor), I tried to declare the explicit instantiation (extern template) as follows:

extern template  std::_String_alloc< std::_String_base_types<wchar_t, class std::allocator<wchar_t> >>::~_String_alloc(void);

But the linker error persisted and there is new error thrown which is as follows:

compiler generated function "std::_String_alloc<_Alloc_types>::~_String_alloc [with _Alloc_types=std::_String_base_types<wchar_t, std::allocator<wchar_t>>]" cannot be explicitly instantiated.

My questions are as follows:

  1. Can and how the std::_String_alloc destructor be declared explicitly so that its implicit instantiation(and Symbols) can be suppressed.

  2. As per new generated error, if std::_String_alloc explicit instantiation is not possible then how the linker error can be resolved. I can not make any changes in abc.dll. (The error is thrown as the symbol is already defined in abc.dll)

It would be great if someone can shed some light on the template std::_String_alloc (It is base class for std::basic_string and there is not much information present on the internet.)and the new error thrown for it (compiler generated functions cannot be explicitly instantiated.)

There were linker errors for other std::basic_string member functions including the std::basic_string constructor, destructor and move constructors. I resolved those by explicitly declaring those member functions in static lib (extern template).

About QSGGeometryNode and WebAssembly in QT

I'm trying to deploy my project on the Web with WebAssembly and encountered some problems.

The project made a custom rendering with QSGRenderNode and ran on the web.

And I'm getting error "INVALID OPERATION insufficient buffer size".

Here's my code bellow.

openglerenderer.h

#ifndef OPENGLRENDERER_H
#define OPENGLRENDERER_H

#include <qsgrendernode.h>
#include <QQuickItem>
#include "webaccess/render/baserender.h"

#if QT_CONFIG(opengl)


class OpenGLRenderNode : public QSGRenderNode
{
public:
    ~OpenGLRenderNode();

    void render(const RenderState *state) override;
    void releaseResources() override;
    StateFlags changedStates() const override;
    RenderingFlags flags() const override;
    QRectF rect() const override;

    void sync(QQuickItem *item);

private:
    void init();
    int m_width = 0;
    int m_height = 0;
    bool beInit = false;
    BaseRender* m_render = nullptr;
};

#endif

#endif // OPENGLRENDERER_H

openglerenderer.cpp

#include "openglrenderer.h"
#include <QQuickItem>

#if QT_CONFIG(opengl)

#include <QOpenGLFunctions>
#include <QOpenGLExtraFunctions>
#include <QQuickWindow>

#include "webaccess/render/tutorial/les1.h"
#include "webaccess/render/tutorial/les2.h"
#include "webaccess/render/tutorial/les3.h"
#include "webaccess/render/tutorial/les4.h"

OpenGLRenderNode::~OpenGLRenderNode()
{
    releaseResources();
}

void OpenGLRenderNode::releaseResources()
{
    if (m_render) {
        m_render->releaseResources();
    }
}

void OpenGLRenderNode::init()
{
    if (m_render) {
        m_render->init();
        beInit = true;
    }
}

void OpenGLRenderNode::render(const RenderState *state)
{
    if (!beInit)
        init();
    if (m_render) {
        m_render->render(state);
    }
}

QSGRenderNode::StateFlags OpenGLRenderNode::changedStates() const
{
    return BlendState | ScissorState | StencilState;
}

QSGRenderNode::RenderingFlags OpenGLRenderNode::flags() const
{
    return BoundedRectRendering | DepthAwareRendering;
}

QRectF OpenGLRenderNode::rect() const
{
    return QRect(0, 0, m_width, m_height);
}

void OpenGLRenderNode::sync(QQuickItem *item)
{
    m_width = static_cast<int>(item->width());
    m_height = static_cast<int>(item->height());
    if (!m_render) {
        m_render = static_cast<BaseRender*>(new les4{});
        if (m_render) {
            QObject::connect(item->window(), &QQuickWindow::beforeRendering, m_render, [&]() { m_render->beforeRender(); }, Qt::DirectConnection);
        }
    }
    if (m_render) {
        m_render->sync(item);
        m_render->setViewportSize(item->size().toSize() * item->window()->devicePixelRatio());
        m_render->setPosition(item->position().toPoint());
        m_render->setWindow(item->window());
    }
}

#endif

les4.h

#ifndef LES4_H
#define LES4_H

#include "../baserender.h"

class QOpenGLTexture;
class QOpenGLShaderProgram;
class QOpenGLBuffer;
class QOpenGLVertexArrayObject;

class les4 : public BaseRender
{
public:
    les4();

    ~les4() override;
    virtual void init() override;
    virtual void render(const QSGRenderNode::RenderState *state) override;
    virtual void sync(QQuickItem *item) override;
    virtual void releaseResources() override;

    virtual void setViewportSize(QSize size) override { m_viewportSize = size; }
    virtual void setPosition(QPoint point) override { m_position = point; }
    virtual void setWindow(QQuickWindow* window) override { m_window = window; }
    virtual void beforeRender() override;

private:
    QSize m_viewportSize{};
    QPoint m_position{};
    QQuickWindow* m_window{};

    QOpenGLShaderProgram *m_program = nullptr;
    QOpenGLVertexArrayObject *m_vao = nullptr;
    QOpenGLBuffer *m_vbo = nullptr;
    QOpenGLBuffer *m_ibo = nullptr;

    int m_width = 0;
    int m_height = 0;
};

#endif // LES4_H

les4.cpp

#include "les4.h"
#include <QQuickWindow>
#include <QOpenGLContext>
#include <QOpenGLTexture>
#include <QOpenGLShaderProgram>
#include <QOpenGLBuffer>
#include <QOpenGLVertexArrayObject>
#include <QOpenGLFunctions>
#include <QGuiApplication>

static const char *vertexShaderSource =
        "#version 100\n"
        "attribute vec3 aPos;\n"
        "attribute vec3 aColor;\n"
        "varying vec3 ourColor;\n"
        "void main() {\n"
        "   gl_Position = vec4(aPos.xyz, 1.0);\n"
        "   ourColor = aColor;\n"
        "}";

static const char *fragmentShaderSource =
        "#version 100\n"
#if defined(Q_OS_HTML5) or defined(Q_OS_WASM) or defined(__EMSCRIPTEN__)
        "precision mediump float;\n"
#endif
        "varying vec3 ourColor;\n"
        "void main() {\n"
        "   gl_FragColor = vec4(ourColor, 1.0);\n"
        "}";

static float vertices[] {
    // 位置              // 顏色
     0.5f, -0.5f, 0.0f,  1.0f, 0.0f, 0.0f,   // 右下
    -0.5f, -0.5f, 0.0f,  0.0f, 1.0f, 0.0f,   // 左下
     0.0f,  0.5f, 0.0f,  0.0f, 0.0f, 1.0f    // 頂部
};

static unsigned int indices[] {
    0, 1, 2
};

les4::les4()
{

}

les4::~les4()
{

}

void les4::init() {
    QSurfaceFormat fmt;
    fmt.setVersion(2, 0);
    fmt.setRenderableType(QSurfaceFormat::OpenGLES);
    fmt.setMajorVersion(2);
    fmt.setMinorVersion(0);
    fmt.setRedBufferSize(5);
    fmt.setGreenBufferSize(6);
    fmt.setBlueBufferSize(5);
    fmt.setAlphaBufferSize(0);
    fmt.setDepthBufferSize(0);

    QSurfaceFormat::setDefaultFormat(fmt);

    QOpenGLContext *ctx = QOpenGLContext::currentContext();
    ctx->setFormat(fmt);
}

void les4::releaseResources() {
    delete m_program;
    m_program = nullptr;

    delete m_vbo;
    m_vbo = nullptr;

    delete m_ibo;
    m_ibo = nullptr;

    delete m_vao;
    m_vao = nullptr;
}

void les4::beforeRender() {

}

void les4::render(const QSGRenderNode::RenderState*) {

    QOpenGLContext *ctx = QOpenGLContext::currentContext();

#if defined(Q_OS_HTML5) or defined(Q_OS_WASM) or defined(__EMSCRIPTEN__)
const bool isCoreProfile  = false;
#else
const bool isCoreProfile  = ctx->format().profile() == QSurfaceFormat::CoreProfile;
#endif

    QOpenGLFunctions *f = ctx->functions();

    int y = (m_window->size()* m_window->devicePixelRatio()).height() - m_viewportSize.height() - m_position.y();
    f->glViewport(m_position.x(), y, m_viewportSize.width(), m_viewportSize.height());
    f->glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
    f->glClear(GL_COLOR_BUFFER_BIT);

    auto setupVertAttrs = [this, f] {
        m_vbo->bind();
        f->glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6*sizeof(float), (void*)0);
        f->glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6*sizeof(float), (void*)(3*sizeof(float)));
        f->glEnableVertexAttribArray(0);
        f->glEnableVertexAttribArray(1);
    };

    if (!m_program) {
        m_program = new QOpenGLShaderProgram;
        m_program->addCacheableShaderFromSourceCode(QOpenGLShader::Vertex, vertexShaderSource);
        m_program->addCacheableShaderFromSourceCode(QOpenGLShader::Fragment, fragmentShaderSource);
        m_program->bindAttributeLocation("aPos", 0);
        m_program->bindAttributeLocation("aColor", 1);
        m_program->link();

        m_vao = new QOpenGLVertexArrayObject;
        m_vao->create();

        m_vbo = new QOpenGLBuffer;
        m_vbo->create();

        m_ibo = new QOpenGLBuffer(QOpenGLBuffer::IndexBuffer);
        m_ibo->create();
    }

    // non-premultiplied alpha
    f->glEnable(GL_BLEND);
    f->glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    // no backface culling
    f->glDisable(GL_CULL_FACE);
    // still need depth test to test against the items rendered in the opaque pass
    f->glEnable(GL_DEPTH_TEST);
    // but no need to write out anything to the depth buffer
    f->glDepthMask(GL_FALSE);
    // do not write out alpha
    f->glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE);
    // will always scissor
    f->glEnable(GL_SCISSOR_TEST);

    if (m_vao->isCreated())
        m_vao->bind();

    m_program->bind();

    m_vbo->bind();
    m_vbo->allocate(vertices, sizeof(vertices));
    m_ibo->bind();
    m_ibo->allocate(indices, sizeof(indices));

    setupVertAttrs();

    //scissor...
    //texture...
    f->glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr);
    f->glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
}

void les4::sync(QQuickItem *item) {
  //  qDebug() << "w:" << item->width() << " h:" << item->height();
    m_width = static_cast<int>(item->width());
    m_height = static_cast<int>(item->height());
}

Please help me. I'm stuck here for a long time.

mardi 27 avril 2021

Understanding GDB back trace with error access outside bounds of object referenced via synthetic pointer

I have 2 classes using CRTP. Class A parses a json file. Class B gets the Json data by calling get() method of Class A. Class A in turn calls set() of Class B after parsing the Json.

template <class T>
class A
  {
    private:
     nlohmann::json doc;
     using jptr = nlohmann::json::json_pointer;
     jptr addl_fld_ptr;
     public:
     parse_nf_event(std::string event)
     {
             try
             {
             doc = nlohmann::json::parse(event);
             }
             catch(const nlohmann::json::exception& e)
             {
                 std::cout<<"MVRP: Cannot create Json from string\n";
                 throw "parse_nf_event: json string invalid";
             }

         
         addl_fld_ptr="/event/path/to/msuid/"_json_pointer;
      }
      inline void get_msuid()
     {   
         //return "NULL" if field not present
         static_cast<T&>(*this).set_msuid(doc.value(addl_fld_ptr/"msuid","NULL"));
     }
};

class B:public A<B>
 {
   private:

      something *ptr;

   public:
      B(std::string str):A(str)//str is json string
      {
      }
      inline void set_msuid(std::string val)
      {
          ptr->msu_id.assign(val);
      }
      void* get_payload()
      {
        ptr = new something();
        get_msuid();
        return ptr;
      }
};

Above code is trimmed version

User calls get_payload.

Sometimes I am getting a core

(gdb) bt
#0  0x00007fc2a27cc38d in std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::_M_assign(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6

#1  0x00000000006be6ff in std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::assign (__str="",
    this=<optimized out>) at /usr/local/include/c++/5.4.0/bits/basic_string.h:1095
#2  B::set_msuid (this=0x7fc298ff6b20,
    val=<error reading variable: access outside bounds of object referenced via synthetic pointer>)
    
#3  A<B>::get_msuid (this=0x7fc298ff6b20)
    
#4  B::get_payload (this=0x7fc298ff6b20)
    

This is the first time I am using CRTP, and not sure if I did it right. I am not able to understand the reason from back trace. From the Json I can see msuid="" so nlohmann parser returns empty string.

C++ determining at compile time whether a particular operation on one or more types is valid

In C++, for C++11 on up, I want to be able to determine whether a particular operation on one or more types is valid at compile time, with a boolean value of 'true' indicating that the operation is valid and a value of 'false' indicating that the operation is not valid.

In the Boost.TypeTraits library there are operations as part of the library, called "Operator Type Traits", which can determine this for me for a very large range of operators. I am not questioning the value of this code, for it is excellent. It was written to work at the C++03 level, but does have a few limitations. Does some C++, from C++11 on up, have compile time support for such a determination as part of the C++ enhancements to that particular level of C++ ? As an example, given type T and type U, I want to create a compile time question of whether A + B is a valid operation. I can not say decltype(T() + U()) because if this is not valid I will get a compile time error. Instead I want to write code which basically says "if decltype(T() + U())" is valid do this, else do that. Is this possible ?

C++ feed cin enter?

I am the owner of: C++ Signal Handlers output doesn't appear? but lost access to my account (used temp email which is my fault).

Regarding the same question, in case ctrl+z was pressed how can I feed Enter to cin to make my bash behave as expected instead of waiting for the user to press enter.

For reference I have:

if (signal(SIGTSTP, ctrlZHandler) == SIG_ERR) {
    perror("smash error: failed to set ctrl-Z handler");
}

SmallShell &smash = SmallShell::getInstance();
while (keep_running) {
    std::cout << "smash> ";
    std::string cmd_line;
    std::getline(std::cin, cmd_line);
    smash.executeCommand(cmd_line.c_str());
}


void ctrlZHandler(int sig_num) {
    //SIGTSTP-18
    cout << "smash: got ctrl-Z" << endl;
    SmallShell::route_signal(sig_num);
}

Is there a way I can keep something at a constant speed in C++ game?

I currently have a game where there is a player, enemies, and projectiles. The user can spawn projectiles to damage enemies. However, the problem that I am having, is that the enemies speed up the more projectiles the user spawns in a row. I tried to use a game clock to keep everything constant and my game loop is below.

while (window.isOpen())
{
    std::chrono::high_resolution_clock::time_point begin = std::chrono::high_resolution_clock::now();
    for (int i = 0; i < enemies.size(); i++)
    {
        enemies[i].move(begin, HEIGHT, WIDTH, player);
    }
    for (size_t i = 0; i < player.projectiles.size();)
    {
        if (player.projectiles[i].move(begin, WIDTH))
        {
            player.projectiles.erase(player.projectiles.begin() + i);
        }
        else
        {
            i++;
        }
    }
    for (int i = 0; i < enemies.size();)
    {
        for (int j = 0; j < player.projectiles.size();)
        {
            if (enemies[i].hit(player.projectiles[j]))
            {
                player.projectiles.erase(player.projectiles.begin() + j);
            }
            else
            {
                j++;
            }
        }
        if (enemies[i].hp <= 0)
        {
            enemies.erase(enemies.begin() + i);
        }
        else
        {
            i++;
        }
    }
    sf::Event event;
    while (window.pollEvent(event))
    {
        if (event.type == sf::Event::Closed)
        {
            window.close();
            break;
        }
        if (sf::Mouse::isButtonPressed(sf::Mouse::Right))
        {
            enemies.push_back(Enemy(100.0, 1.0, Mouse::getPosition().x, Mouse::getPosition().y, Color::White));
        }
        if (event.type == Event::KeyPressed)
        {
            if (event.key.code == player.up)
            {
                player.moving_up = true;
            }
            else if (event.key.code == player.down)
            {
                player.moving_down = true;
            }
            else if (event.key.code == player.right)
            {
                player.moving_right = true;
            }
            else if (event.key.code == player.left)
            {
                player.moving_left = true;
            }
            else if (event.key.code == player.shoot)
            {
                player.shooting = true;
            }
            if (event.key.code == player.exit)
            {
                window.close();
            }
        }
        if (event.type == Event::KeyReleased)
        {
            if (event.key.code == player.up)
            {
                player.moving_up = false;
            }
            else if (event.key.code == player.down)
            {
                player.moving_down = false;
            }
            else if (event.key.code == player.right)
            {
                player.moving_right = false;
            }
            else if (event.key.code == player.left)
            {
                player.moving_left = false;
            }
            else if (event.key.code == player.shoot)
            {
                player.shooting = false;
            }
        }
        player.input(begin, HEIGHT, WIDTH);
        for (int i = 0; i < enemies.size();)
        {
            for (int j = 0; j < player.projectiles.size();)
            {
                if (enemies[i].hit(player.projectiles[j]))
                {
                    player.projectiles.erase(player.projectiles.begin() + j);
                }
                else
                {
                    j++;
                }
            }
            if (enemies[i].hp <= 0)
            {
                enemies.erase(enemies.begin() + i);
            }
            else
            {
                i++;
            }
        }
    }
    window.clear();
    player.draw(window);
    for (int i = 0; i < enemies.size(); i++)
    {
        enemies[i].draw(window);
    }
    window.display();
}

The enemy.move function looks like this, where speed is set to 1.0:

void Enemy::move(std::chrono::high_resolution_clock::time_point begin, float height, float width, Player player)
{
    std::chrono::high_resolution_clock::time_point end = std::chrono::high_resolution_clock::now();
    if (player.x < this->x)
    {
        if (this->x - (enemy_speed * (std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count()) / 1000.0) < 0)
        {
            this->x = 0;
        }
        else
        {
            this->x = this->x - (enemy_speed * (std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count()) / 1000.0);
        }
        if (player.y < this->y)
        {
            if (this->y - (enemy_speed * (std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count()) / 1000.0) < 0)
            {
                this->y = 0;
            }
            else
            {
                this->y = this->y - (enemy_speed * (std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count()) / 1000.0);
            }
        }
        else
        {
            if (this->y + (enemy_speed * (std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count()) / 1000.0) > (height - double(this->sprite.getSize().y)))
            {
                this->y = height - double(this->sprite.getSize().y);
            }
            else
            {
                this->y = this->y + (enemy_speed * (std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count()) / 1000.0);
            }
        }
    }
    else
    {
        if (this->x + (enemy_speed * (std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count()) / 1000.0) > (width - double(this->sprite.getSize().x)))
        {
            this->x = width - double(this->sprite.getSize().x);
        }
        else
        {
            this->x = this->x + (enemy_speed * (std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count()) / 1000.0);
        }
        if (player.y < this->y)
        {
            if (this->y - (enemy_speed * (std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count()) / 1000.0) < 0)
            {
                this->y = 0;
            }
            else
            {
                this->y = this->y - (enemy_speed * (std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count()) / 1000.0);
            }
        }
        else
        {
            if (this->y + (enemy_speed * (std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count()) / 1000.0) > (height - double(this->sprite.getSize().y)))
            {
                this->y = height - double(this->sprite.getSize().y);
            }
            else
            {
                this->y = this->y + (enemy_speed * (std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count()) / 1000.0);
            }
        }
    }
    this->sprite.setPosition(this->x, this->y);
}

I apologize for the long segments of code but these are the relative parts and I don't know specifically what pieces of code you may need. Any help is greatly appreciated.

Inverse of a square matrix using CUBLAS in C++ [duplicate]

Can anybody tell me a way to find the inverse of a square matrix using CUBLAS in C++?It would be very helpful is you could provide a simple example code with a 2x2 matrix.

is it possible to record the audio and save as .wav file [closed]

i have searched everywhere and i couldnt find any proper code to record the audio when a button is pressed and save it as .wav file when the button is released.

C++ overload resolution with template

I want to have a function that takes a std::string and another that takes anything that is not a std::string.

So I have:

#include <iostream>
#include <string>

void foo(const std::string& str) {
  std::cout << "string version called" << std::endl;
}

template<class T>
void foo(T&& str) {
  std::cout << "template version called" << std::endl;
}

int main() {
    foo(std::string{"hello"});
    return 0;
}

The problem is that the templated version is called instead of the std::string version.

So how can I have a foo function that either takes anything or specifically a std::string?

Dynamic programing with C++ problem in Hackerrank task

Recently I have been solving some hackerranks tasks.In advance I want to tell that I know basics of c++ (I read and made tasks from book "Programming: Principles and Practice Using C++") .. Unfortunately in one of these problem I got stuck and from few hours i can't move forward. When I tried to fix it, I experienced a bunch of runtime or segmentation errors. I know that errors are produced by my int** arrwhen program tries to modify it , but I can't figure out by what are caused. Also I aware that program can have more bugs which now i can't spot due to this first bad part of program. I know that further i program are more mistakes but now I focus on the first issue. I could write this program by using list or array but i want to challenge myself and do it with more low programing tools.

There is link to problem and below is my whole code

#include <vector>
#include <list>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <stack>
#include <algorithm>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <limits>
#include <cstring>
#include <string>
#include <cassert>

using namespace std;
int N ,q;
int main()
{
   int lastAnswer=0;
   cin>>N>>q;
   int** arr = new int*[N];
   for(int i=0;i<N;i++)
   {
       arr[i]=nullptr;
   }
   for(int i=0; i<q;i++)
   {
       cout<<"it :"<<i<<", ";
       int a,b,c;
       cin>>a>>b>>c;
       cout<<"C:"<<c<<" ";
       int ind= (b^lastAnswer)%2;
       if(a==1){
          
               cout<<"{1: ";
               int* poi =arr[ind];
               cout<<"$arr[ind] ad:"<<arr[ind]<<" $";              
               int size =0;
               while(poi){poi++;size++;}
               cout<<" Size at beg:"<<size<<" $";
               int* n =new int[size+1];
               if(size!=0)
               {
                   for(int i=0; i<size;i++)
                       n[i]=poi[i];
                   for(int i=0; i<size+1;i++ )cout<<"i"<<i<<" "<<*poi<<" ";
                   delete[] poi;    
               }
               n[size]=c;
               cout<<" Elem n[size]:"<<c<<"  $";
               arr[ind] =n;
           cout<<"E:"<<*arr[ind]<<" for index:"<<ind<<" address:"<<arr[ind]<<'\n';
       }    
       else if(a==2)
       {
           cout<<"{2";
           int * ak = arr[ind];
           int size=0;
           while(ak)
           {
               ak++;size++;
           }
           lastAnswer = *arr[c%size];
           cout<<lastAnswer<<'\n';//only this cout is not debug
       }
               
       
       
   }

   
}

** I added added also debug code in this program.** For this input:

2 5
1 0 5
1 1 7
1 0 3
2 1 0
2 1 1

Output is:

it :0, C:5 {1: $arr[ind] ad:0 $Size at beg:0 $Elem n[size]:5  $E:5 for index:0 ads:0x1c8d5b0

it :1, C:7 {1: $arr[ind] ad:0 $Size at beg:0 $Elem n[size]:7  $E:7 for index:1 ad:0x1c8d4d0

it :2, C:3 {1: $arr[ind] ad:0x1c8d5b0 $Size at beg:0 $Elem n[size]:3  $E:3 for index:0 ad:0x1c8d410

it :3, 

Expected:

7

3

But without debug output, it doesn't print anything but shows "Runtime Error" which occurs after 3 iteration during getting from cin data I know that i should add delete or free function to prevent leak of memory but i think it would not change that i have error (or change my mind)

In advance thanks for your help :)

How to use ternary Operator in my C/C++ code

I have 3 values. Can you guide me on how can I use the ternary operator instead of if-else if statement in the mentioned example?

if(status == ok)
{
  return;
}
else
{
 if(status == warning)
 {
   return E_ABORT;
 } 
 else if(status == stop)
 { 
   return E_FAIL;
 }

In 2 cases (stop and warning) i want message and in ok case just want return, no message want to display

How can I crop face rectangles from the frame in C++ code?

 # Detect face
        if len(video_frames) == 0:
            face_rects = faceCascade.detectMultiScale(gray, 1.3, 5)

        # Select ROI
        if len(face_rects) > 0:
            for (x, y, w, h) in face_rects:
                roi_frame = img[y:y + h, x:x + w]
            if roi_frame.size != img.size:
                roi_frame = cv2.resize(roi_frame, (500, 500))
                frame = np.ndarray(shape=roi_frame.shape, dtype="float")
                frame[:] = roi_frame * (1. / 255)
                video_frames.append(frame)

    frame_ct = len(video_frames)
    cap.release()

This is part of the python code from this link https://github.com/rohintangirala/eulerian-remote-heartrate-detection/blob/master/preprocessing.py I am converting this to C++. Could someone provide me the C++ code for this?

lundi 26 avril 2021

error: call to 'CrossProduct' is ambiguous

I have created a template class named Vector in a header file, say foo.h. Here is how I defined the template class

template <class T, int dimensions> class Vector {
  private:
    T component_[dimensions];
  public: 
    Vector(const T& a = 0) {
      for (int i = 0; i < dimensions; i++)
        component_[i] = a;
    } // default/scalar constructor
    Vector(const Vector& v) {
      for (int i = 0; i < dimensions; i++)
        component_[i] = v.component_[i];
    } // copy constructor
    ~Vector() {;} // destructor

    void set(int i, const T& a) {
      component_[i] = a;
    } // change ith component of the vector
}; 

... and few other member functions. Then I created an alias for 3D vector as follows

typedef Vector<double, 3> Point3D;

Following this, I declared few function prototypes for 3D vectors

Point3D CrossProduct(const Point3D&, const Point3D&);
double ScalarTripleProduct(const Point3D&, const Point3D&, const Point3D&);
Point3D VectorTripleProduct(const Point3D&, const Point3D&, const Point3D&);

This is the end of foo.h. I then defined these three function in foo.cpp. Here is the code below.

#include "foo.h"

Point3D CrossProduct(const Point3D& a, const Point3D& b) {
  Point3D c;
  c.set(0, a[1] * b[2] - a[2] * b[1]);
  c.set(1, a[2] * b[0] - a[0] * b[2]);
  c.set(2, a[0] * b[1] - a[1] * b[0]);
  return c;
} // vector cross product: a X b, defined only for 3D vectors                                                                                                                                                                                                               
double ScalarTripleProduct(const Point3D& a, const Point3D& b,
    const Point3D& c) {
  return a * CrossProduct(b, c);
} // scalar triple product: a . (b X c), defined only for 3D vectors

Point3D VectorTripleProduct(const Point3D& a,
    const Point3D& b, const Point3D& c) {
  return CrossProduct(a, CrossProduct(b, c));;
} // vector triple product: a X (b X c), defined only fr 3D vectors

Now when I try to compile foo.cpp, I get the following errors

foo.cpp: error: call to 'CrossProduct' is ambiguous
        return a * CrossProduct(b, c);
                   ^~~~~~~~~~~~
./foo.h: note: candidate function
        Point3D CrossProduct(const Point3D&, const Point3D&);
                ^
foo.cpp: note: candidate function
Point3D CrossProduct(const Point3D& a, const Point3D& b) {
        ^
foo.cpp: error: call to 'CrossProduct' is ambiguous
        return CrossProduct(a, CrossProduct(b, c));;
                               ^~~~~~~~~~~~
./foo.h: note: candidate function
        Point3D CrossProduct(const Point3D&, const Point3D&);
                ^
foo.cpp: note: candidate function
Point3D CrossProduct(const Point3D& a, const Point3D& b) {
        ^

I am not sure about what went wrong. Could you please help me with this? Thank you.

auto & vs auto &&: Which one should we use in a for loop

I've read this link: What is the correct way of using C++11's range-based for?, I've known why we use auto && to loop a vector<bool>. But I still have one more question about auto & and auto &&.

class Test {};
vector<Test> vec = {Test{}, Test{}, Test{}};
vector<Test> vec2;
// case 1
for (auto &it : vec) {
    vec2.emplace_back(it);
}
// case 2
for (auto &it : vec) {
    vec2.emplace_back(std::move(it));
}
// case 3
for (auto &&it : vec) {
    vec2.emplace_back(it);
}
// case 4
for (auto &&it : vec) {
    vec2.emplace_back(std::move(it));
}

As you see, I'm trying to insert the objects from the vec into the vec2 with the method move constructor of the class Test.

I don't know which case I should use, which case is better, which cases are wrong.

Ofc, you might say that we can simply do vec2 = std::move(vec);, this is correct but I want to know how to move-construct each element in a for loop, instead of move-construct the container.

C++ object deletion crashing

I tried to include all necessary code that may be causing these problems. The program crashes the second time this code is run:

        for (int i = 0; i < player.projectiles.size(); i++)
        {
            bool temp = player.projectiles[i].move(begin, WIDTH);
            if (temp == true)
            {
                player.projectiles[i].destroy();
                player.projectiles.erase(player.projectiles.begin() + i);
            }
        }

Player.projectiles is a vector of objects from the class Projectiles. The member function move works perfectly and the function destroy looks like this:

void Projectile::destroy()
{
    delete this;
}

The first time the loop is run everything works fine, but the second time my program crashes and I can't figure out why. I suspect it has to do with deleting the object. Any help is greatly appreciated.

How do I get a rectangle (or &rc) from a memory hdc without using a handle or HWND

I am using Microsoft Windows (32 bit). Please, no Visual Studio anything, or .net.

I have the following that works if I have a windows handle to use for it:

// I have a handle to a window.    
// HWND Handle_Of_SomeWindow
// I previously assigned a handle for that and use it.

// I have some Unicode text that I am using.
wstring SomeWideStringText = L"C++ stole my lunch money.";

// I convert that wstring to LPWSTR using 
LPWSTR Text_Being_Added = const_cast<wchar_t*>(SomeWideStringText.c_str());
    

//I create a rectangle to use in my DrawTextExW
RECT rc;    

// If I have a handle to a window then I can do this.
GetClientRect(Handle_Of_SomeWindow, & rc);

//But, if I do not have a handle to a window and if I only have a hdc, then that does not work.

When I have an HDC without a window handle (I think that this is a memory dc but I do not yet understand that so well) which I am using in double buffering, then there is no handle to use. And, I can not get a handle for it. Get handle from DC does not work.

So, my question is How do I get a rectangle or &rc for that to use in my command of :

DrawTextExW(HDC_of_FRONT_BUFFER_001, Text_Being_Added, -1, & rc, DT_WORDBREAK, nullptr);

?

Maybe there might be something else other than a rectangle &rc that I could use, but I have not found it.

I have been studying this and I do not understand how to get a rectangle or a &rc to use.

A use-case for r-value members

I've discovered an interesting piece of code and I wonder if it is UB or not? At least, according to cppreference it should not be. Is it a valid case for using an r-value reference?

The lifetime of a temporary object may be extended by binding to a const lvalue reference or to an rvalue reference...

Something similar was discussed in this post, but it does not fully address my case.

template <typename T>
class ResourceLocator {
public:
    static void load(ResourceLocator<T>&& instance) {
        instance_ = std::move(instance);
    }

protected:
    static ResourceLocator<T>&& instance_;
    // static ResourceLocator<T>& instance_; // does not extend lifetime
    // static const ResourceLocator<T>&& instance_; // const is too limiting

please help me find error in the given c++ code [closed]

Find and correct 6 errors in the code

// This program uses two arrays to record the names of 5 types of pizza

// and the sales numbers for each of these types

// The program then finds the best and the worst selling pizzas

#include<iostream>

#include<string>

usingnamespace std;

int main()

{

constint ARR_SIZE=6; // Declare the array size and set it to 5

// Declare the array of pizza names and record values in it

int name[ARR_SIZE]=["Pepperoni","Prosciutto","Vegetarian",

"Sausage","Supreme","Mozzarella"];

int sales[ARR_SIZE]; // Declare the sales array

int worstseller_number, bestseller_number; // The subscripts of the best- and worstseller

string worstseller_name, bestseller_name; // The sale numbers of the best- and worstseller

for(int i=1; i<ARR_SIZE; i++) // A loop to enter all sales numbers

{

cout << "Enter sales for " << name[i] << ": ";

cin >> sales[i];

}

// Make the first element in name[] the bestseller and the worstseller name

worstseller_name = bestseller_name = name[0];

// Make the first element in sales[] the bestseller and the worstseller sales amount

worstseller_number = bestseller_number = sales[0];

for(int i=0; i<=ARR_SIZE; i++) // Loop through all elements in sales[]

{

if(sales[i] < worstseller_number) // If an element is less than the lowest...

{

worstseller_number=i; // make the lowest sales equal to its sales

worstseller_name=name[i]; // make the worstseller name equal to its name

}

if(sales[i]<bestseller_number) // If an element is higher than the highest...

{

bestseller_number=sales[i]; // make the highest sales equal to its sales

bestseller_name=name[i]; // make the bestseller name equal to its name

}

}

cout << "The bestselling pizza is " << bestseller_name << " with the sales of "

<< bestseller_number << endl; // Display the best selling pizza

cout << "The worst selling pizza is " << worstseller_name << " with the sales of "

<< worstseller_number << endl; } // display the worst selling pizza

cannot bind non-const lvalue reference of type ‘std::string& to an rvalue of type ‘std::string [duplicate]

I have below code. In order to cut off cost of calling fun. I set fun(string &a) use reference parameter. But it can't be compiled.

#include <iostream>

using namespace std;

void
fun (string &a) {
        string concat = "prefix_" + a;
        cout << "[fun] concat:" << concat << endl;
}

int
main(int argc, char **argv) {
        fun("test");
        return 0;
}

cannot bind non-const lvalue reference of type ‘std::string&’ {aka ‘std::__cxx11::basic_string&’} to an rvalue of type ‘std::string’ {aka ‘std::__cxx11::basic_string’}

I change fun (string &a) to fun (string a). It works. But it seems to lead to unnecessary construction.

BTW, How shold I write the right code to minimum cost of unnecessary implicit construction?

dimanche 25 avril 2021

undefined reference to `(std::__cxx11::basic_string

I am working on linking Tensorflow2 shared libraries (*.so) files into my C++ program. The libtensorflow_cc and libtensorflow_framework.so use bazel-3.7.2 and gcc7.3 and is linked to another library I have ‘libmyproj.so’. I want to link this libmyproj.so to my main program which are built with the same gcc7.3. I have tried using the -D_GLIBCXX_USE_CXX11_ABI=0 flag for ABI compatibility (from https://www.tensorflow.org/install/source and Converting std::__cxx11::string to std::string) but without any success. I am stuck at the following error:

undefined reference to ml_model::ml_model(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)' undefined reference to ml_model::preprocess_data(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::vector<float, std::allocator<float> >, int&, int&, std::vector<int, std::allocator<int> >&)' undefined reference to ml_model::get_predictions(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > int, std::vector<int, std::allocator<int> >)' in function std::__cxx11::basic_string<char, std::char_traits, std::allocator >* tensorflow::internal::MakeCheckOpString<long, int>(long const&, int const&, char const*)': undefined reference to tensorflow::internal::CheckOpMessageBuilder::NewString[abi:cxx11]()'

Any suggestions on why this is happening?

How can I associate a type with a number

I want to be able to generate a number for each type of a particular typelist.

i.e. for the following 2 typelists (where Group works like std::variant):

class myclass;

using GroupA = Group<int, double, myclass>;

static_assert( GroupA::type_number<int> == 0 );
static_assert( GroupA::type_number<double> == 1 );
static_assert( GroupA::type_number<myclass> == 2 );


using GroupB = Group<double, myclass>;  // different group => different numbering

static_assert( GroupB::type_number<double> == 0 );
static_assert( GroupB::type_number<myclass> == 1 );

I tried to recurse through the Types, but I cannot end up with one template parameter on every type

template < typename ... Types> 
struct Group
{
    
    template < typename T > 
    constexpr static int type_number = 0;
    
    template < typename T, typename ... Types >
    constexpr static int type_number = type_number<Types...> + 1;

};

I am imitating any/variant and I want to be able to sort a vector of them.

single linked list print a reverse linked list cpp [closed]

I need help trying to print a reverse linked list, I tried to print the link list in reverse order but my code prints it in the correct order instead of reversing the items, I think that my reverse function works correctly but the print function is the one that fails.

struct Node {
  ItemType value;
  Node* next;
};

class LinkedList {
 private:
  Node* head;

 public:
  void LinkedList::reverseList() {
    // Initialize current, previous and
    // next pointers
    Node* p = head;
    Node *prev = nullptr, *next = nullptr;

    while (head != nullptr) {
      // Store next
      next = head->next;

      // Reverse current node's pointer
      head->next = prev;

      // Move pointers one position ahead.
      prev = head;
      head = next;
    }
    head = prev;
  }

  // Prints the LinkedList in reverse order
  void LinkedList::printReverse() const {
    Node* p;
    p = head;
    while (p != nullptr) {
      cout << p->value << endl;
      p = p->next;
    }
    p = p->next;
  }

  for (int i = n - 1; i >= 0; i--) {
    cout << arr[i] << " " << endl;
  }

  cout << endl;
}
}

Remove duplication in equivalent const and non-const members when returning optional reference by value

This answer explains how to remove duplication in equivalent const and non-const member functions which return by reference. It doesn't help, however, in the case where your function returns an optional reference to another type. Is there a solution for this case? E.g.,

class Foo {
    const boost::optional<const Bar&> get_bar() const;
    boost::optional<Bar&> get_bar();
}

How does inheritance works in case of factory methods in cpp?

I'm trying to solve this simple riddle at codingames and i though i will excercies in OOP However it seems I've forgot how cpp works in this field and i got an error i do not comprehend.

/tmp/Answer.cpp:82:1: error: invalid abstract return type ‘Sign’
   82 | Sign from_str(const int value, const std::string& s)
      | ^~~~
/tmp/Answer.cpp:14:7: note:   because the following virtual functions are pure within ‘Sign’:
   14 | class Sign {
      |       ^~~~
/tmp/Answer.cpp:22:25: note:    ‘virtual std::string Sign::str() const’
   22 |     virtual std::string str() const = 0;
      |                         ^~~
/tmp/Answer.cpp:82:6: error: invalid abstract return type for function ‘Sign from_str(int, const string&)’
   82 | Sign from_str(const int value, const std::string& s)
      |      ^~~~~~~~
/tmp/Answer.cpp: In function ‘Sign from_str(int, const string&)’:
/tmp/Answer.cpp:85:26: error: cannot allocate an object of abstract type ‘Sign’
   85 |         return Rock(value);
      |                          ^
/tmp/Answer.cpp:87:27: error: cannot allocate an object of abstract type ‘Sign’
   87 |         return Paper(value);
      |                           ^
/tmp/Answer.cpp:89:30: error: cannot allocate an object of abstract type ‘Sign’
   89 |         return Scissors(value);
      |                              ^
/tmp/Answer.cpp:91:28: error: cannot allocate an object of abstract type ‘Sign’
   91 |         return Lizard(value);
      |                            ^
/tmp/Answer.cpp:93:27: error: cannot allocate an object of abstract type ‘Sign’
   93 |         return Spock(value);

And the code looks like this:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

class Rock;
class Paper;
class Scissors;

class Sign {
public:
    Sign(const int v): value(v) {};
    virtual ~Sign() {};
    bool operator<(const Sign& other) { return value < other.value ? false : true; }
    virtual std::string str() const = 0;

    int value{};
};

class Rock : public Sign {
public:
    Rock(const int v): Sign(v) {};
    bool operator<(const Paper& other) { return true; }
    bool operator<(const Scissors& other) { return false; }
    std::string str() const override { return "Rock"; }

};

class Paper : public Sign {
public:
    Paper(const int v): Sign(v) {};
    bool operator<(const Rock& other) { return true; }
    bool operator<(const Scissors& other) { return false; }
    std::string str() const override { return "Paper"; }
};

class Scissors : public Sign {
public:
    Scissors(const int v): Sign(v) {};
    bool operator<(const Rock& other) { return false; }
    bool operator<(const Paper& other) { return true; }
    std::string str() const override { return "Scissors"; }
};


Sign from_str(const int value, const std::string& s)
{
    if(s == "R")
        return Rock(value);
    if(s == "P")
        return Paper(value);
    if(s == "C")
        return Scissors(value);
    
    throw 1;
}

int main()
{
    int N;
    cin >> N; cin.ignore();
    std::vector<Sign> s{};

    for (int i = 0; i < N; i++) {
        int NUMPLAYER;
        string SIGNPLAYER;
        cin >> NUMPLAYER >> SIGNPLAYER; cin.ignore();
        s.emplace_back(from_str(NUMPLAYER, SIGNPLAYER));
    }
}

At this point I don't really understand why I can't use Sign as return value from the factory method that is returning concrete types and emplace it on my data pile.

And if I add to base class

virtual std::string str() const { return "Sign"; };

I will only get the base class printout.

Reflect changes in file, read with preprocessor macros

I am trying to build a simple logic, where i read a file and make some decisions based on the value in file. As far as I know I can not read a file using std library with constexpr function. I am using preprocessor macro to do that. Currently the file contains only a number 1001. Once the code is compiled and I run it I get the 2 as expected. But if I change the file to 1000 then run without recompiling the output is still 2.

I am familiar with build process and what is happening here.

Is there a way to reflect the changes in the file without recompiling it again. I am open to any suggestions or workaround, I would really appreciate it. I can use only C++11

#include <iostream>

constexpr const int ID = 
#include "file.txt" 
;

constexpr unsigned short int getRDOF()
{
    return  ID == 1000 ? 1:2;    
}
constexpr unsigned short int DOF_ = getRDOF();

int main()
{
    std::cout << "DOF_ : " << DOF_ << std::endl;
    return 0;
}

Do you ALWAYS have to deallocate a dynamic variable?

This might be more of a "good practice" question, and might be somewhat unnecessary, but I think it would be nice to understand this aspect of dynamic allocation.

As far as I understand, if you don't free (deallocate) dynamically allocated variables manually, they will only be freed when your program ends. (I have read about that here)

So if I know that I will definitely need the variables, that I have created on the heap, for the whole duration of my program, isn't it okay to never delete them manually and just let the program free them when it ends?

Or is manually controlling the allocation and deallocation of dynamic variables simply a good practice?

Function returning Int instead of float

I am experimenting with function pointers and lambdas in C++ and my function definitions are as follows -

float max(float a, float b){
    std::cout<<"In float max"<<std::endl;
    return (a > b) ? a : b;
}

int max(int a, int b){
    std::cout<<"In Int max"<<std::endl;
    return (a > b) ? a : b;
}

template<typename type1, typename type2>
int compareNumber(type1 a, type1 b, type2 function){
    return function(a, b);
}

and from my main function, I am calling it as follows -

int main(){

    std::cout<<compareNumber<float, float (float, float )>(5.2542f, 2.314f, max)<<std::endl;
    std::cout<<compareNumber<float>(1.3467f, 2.6721f, [=](float a, float b){
        return (a > b) ? a:b;
    })<<std::endl;

    std::cout<<max(5.3f, 2.7f)<<std::endl;
    std::cout<<max(1, 2)<<std::endl;
}

The Issue is that, If I simply invoke the function separately, the correct values get returned, but when using a lambda function or a function pointer, the values get cast to int for reasons I am not able to point out.
Here Is my output -

In float max
5
2
In float max
5.3
In Int max
2

I checked the output type of the output and it indeed is an integer. I had checked it as follows -

std::cout<<std::is_same<int, decltype(compareNumber<float, float (float, float )>(5.2542f, 2.314f, max))>()<<std::endl;

The above code snippet prints 1.
Could anyone please tell me as to what exactly is happening here?.
TIA

PS - I just realized that the return type is int and not type1 and had posted the question without thinking much and in a hurry. Sorry for the trivial question

What is the difference between const_iterator with std::begin() and const_iterator with std::cbegin()?

Why do we need cbegin if std::vector<int>::const_iterator itr with std::begin would do the same? Is there any problem in using first loop(UB or something)?. Both loops are giving the same result as expected.

int main()
{
  std::vector<int> A = { 1, 2, 3, 4 ,5 ,6, 7};

  for(std::vector<int>::const_iterator itr = begin(A); itr!= end(A); itr++)
  {
    //*itr = 10;//Error
    cout<<*itr<<endl;
  }

  for(std::vector<int>::const_iterator itr = cbegin(A); itr!= cend(A); itr++)
  {
    //*itr = 10;//Error
    cout<<*itr<<endl;
  }

}

samedi 24 avril 2021

assigning unsigned char * to std::string

ALL,

Consider following code:

std::string str;
unsigned char *charArray = "ABC";

Now I want to assign the charArray to str.

Calling str.assign() gives an error on MSVC 2017.

There is a constructor for the string that takes the char *, but apparently there is no assignment.

And I need that cross-platform if possible.

Now that charArray comes from the database API, therefore I can't just assign "ABC" directly to str.

Is such assignment exist?

TIA!

Error is

cannot convert argument 1 from 'SQLCHAR *' to 'std::initializer_list<_Elem>' 1> with 1> [ 1> _Elem=wchar_t 1> ] note: No constructor could take the source type, or constructor overload resolution was ambiguous

And SQLCHAR is a typedef to unsigned char under MSVC 2017.

EDIT2

To whim suggested to close because it already has the answer - it doesn't. The types are cmpletely different there. Please reconsider.

Fast & efficient text file data read in C

I have a college project (data structures and algorithms) to do in the C/C++ language. The project is about to create a simulation of a social website that is scalable and good in performance. I am saving the data into text files.

There are 2 ways to read data and run the program-

  1. Fetch the required data from the text files when needed.
  2. Fetch all the text file data during run time into some data structure and then use it.

Which one would be the best to implement considering the scenario of scaling and performance?

In template: no matching function for call to 'swap'

I am writing a a copy constructor and a copy assignment operator for linkedlist. I have finished the code. But when I try to test the copt assignment operator, I got this error message: In template: no matching function for call to 'swap'. What is wrong with my code? And How should I fix them? I already have a Node.cpp implemented:

/** @file Node.cpp
    Listing 4-2 */
#include "Node.h"

template<class ItemType>
Node<ItemType>::Node() : next(nullptr)
{
} // end default constructor

template<class ItemType>
Node<ItemType>::Node(const ItemType& anItem) : item(anItem), next(nullptr)
{
} // end constructor

template<class ItemType>
Node<ItemType>::Node(const ItemType& anItem, Node<ItemType>* nextNodePtr) :
        item(anItem), next(nextNodePtr)
{
} // end constructor

template<class ItemType>
void Node<ItemType>::setItem(const ItemType& anItem)
{
    item = anItem;
} // end setItem

template<class ItemType>
void Node<ItemType>::setNext(Node<ItemType>* nextNodePtr)
{
    next = nextNodePtr;
} // end setNext

template<class ItemType>
ItemType Node<ItemType>::getItem() const
{
    return item;
} // end getItem

template<class ItemType>
Node<ItemType>* Node<ItemType>::getNext() const
{
    return next;
} // end getNext

Then I have a ListInterface:

/** Interface for the ADT list
    Listing 8-1
    @file ListInterface.h */

#ifndef LIST_INTERFACE_
#define LIST_INTERFACE_

template<class ItemType>
class ListInterface
{
public:
    /** Sees whether this list is empty.
     @return  True if the list is empty; otherwise returns false. */
    virtual bool isEmpty() const = 0;

    /** Gets the current number of entries in this list.
     @return  The integer number of entries currently in the list. */
    virtual int getLength() const = 0;

    /** Inserts an entry into this list at a given position.
     @pre  None.
     @post  If 1 <= position <= getLength() + 1 and the insertion is
        successful, newEntry is at the given position in the list,
        other entries are renumbered accordingly, and the returned
        value is true.
     @param newPosition  The list position at which to insert newEntry.
     @param newEntry  The entry to insert into the list.
     @return  True if the insertion is successful, or false if not. */
    virtual bool insert(int newPosition, const ItemType& newEntry) = 0;

    /** Removes the entry at a given position from this list.
     @pre  None.
     @post  If 1 <= position <= getLength() and the removal is successful,
        the entry at the given position in the list is removed, other
        items are renumbered accordingly, and the returned value is true.
     @param position  The list position of the entry to remove.
     @return  True if the removal is successful, or false if not. */
    virtual bool remove(int position) = 0;

    /** Removes all entries from this list.
     @post  The list contains no entries and the count of items is 0. */
    virtual void clear() = 0;

    /** Gets the entry at the given position in this list.
     @pre  1 <= position <= getLength().
     @post  The desired entry has been returned.
     @param position  The list position of the desired entry.
     @return  The entry at the given position. */
    virtual ItemType getEntry(int position) const = 0;

    /** Replaces the entry at the given position in this list.
     @pre  1 <= position <= getLength().
     @post  The entry at the given position is newEntry.
     @param position  The list position of the entry to replace.
     @param newEntry  The replacement entry.
     @return  The replaced entry. */
    virtual ItemType replace(int position, const ItemType& newEntry) = 0;

    /** Destroys this list and frees its assigned memory. */
    virtual ~ListInterface() { }
}; // end ListInterface
#endif

and the LinkedList.cpp

#include "LinkedList.h"
#include <stdexcept>
#include <iostream>
#include <assert.h>
#include <algorithm>

template<class ItemType>
LinkedList<ItemType>::LinkedList() : headPtr(nullptr), itemCount(0)
{
} // end default constructor

template<class ItemType>
LinkedList<ItemType>::LinkedList(const LinkedList<ItemType>& aList)
{
    itemCount = aList->itemCount;
    Node<ItemType>* origPtr = aList->headPtr;

    if (origPtr == nullptr)
        headPtr = nullptr;
    else {
        headPtr = new Node<ItemType>();
        headPtr->setItem(origPtr->getItem());

        Node<ItemType>* newPtr = headPtr; //Last node pointer
        while (origPtr != nullptr) {
            origPtr = origPtr->getNext();   // advance pointer
            ItemType nextItem = origPtr->getItem(); // get next item
            // create a new node containing the next item
            Node<ItemType>* newNodePtr = new Node<ItemType>(nextItem);

            newPtr->setNext(newNodePtr); // link new node to last
            newPtr = newPtr->getNext(); //advance pointer
        }
        newPtr->setNext(newPtr); // connect null to last
    }
}

template<class ItemType>
LinkedList<ItemType>& LinkedList<ItemType>::operator=(const
        LinkedList<ItemType>& aList) {
    std::swap(headPtr, aList.headPtr);
    return *this;
}

template<class ItemType>
void LinkedList<ItemType>::clear()
{
    while (!isEmpty())
        remove(1);
} // end clear

template<class ItemType>
LinkedList<ItemType>::~LinkedList()
{
    clear();
} // end destructor

template<class ItemType>
bool LinkedList<ItemType>::isEmpty() const
{
    return itemCount == 0;
}  // end isEmpty

template<class ItemType>
int LinkedList<ItemType>::getLength() const
{
    return itemCount;
}  // end getLength

template<class ItemType>
ItemType LinkedList<ItemType>::getEntry(int position) const
{
    // Enforce precondition
    bool ableToGet = (position >= 1) && (position <= itemCount);
    if (ableToGet)
    {
        Node<ItemType>* nodePtr = getNodeAt(position);
        return nodePtr->getItem();
    }
    else
    {
        std::string message = "getEntry() called with an empty list or ";
        message = message + "invalid position.";
        throw(std::invalid_argument(message));
    } // end if
} // end getEntry

template<class ItemType>
Node<ItemType>* LinkedList<ItemType>::getNodeAt(int position) const
{
    // Debugging check of precondition
    assert( (position >= 1) && (position <= itemCount) );

    // Count from the beginning of the chain
    Node<ItemType>* curPtr = headPtr;
    for (int skip = 1; skip < position; skip++)
        curPtr = curPtr->getNext();

    return curPtr;
}  // end getNodeAt

template<class ItemType>
bool LinkedList<ItemType>::insert(int newPosition, const ItemType& newEntry)
{
    bool ableToInsert = (newPosition >= 1) && (newPosition <= itemCount + 1);
    if (ableToInsert)
    {
        // Create a new node containing the new entry
        auto* newNodePtr = new Node<ItemType>(newEntry);
        // Attach new node to chain
        if (newPosition == 1)
        {
            // Insert new node at beginning of chain
            newNodePtr->setNext(headPtr);
            headPtr = newNodePtr;
        }
        else
        {
            // Find node that will be before new node
            Node<ItemType>* prevPtr = getNodeAt(newPosition - 1);

            // Insert new node after node to which prevPtr points
            newNodePtr->setNext(prevPtr->getNext());
            prevPtr->setNext(newNodePtr);
        } // end if

        itemCount++; // Increase count of entries
    }  // end if

    return ableToInsert;
}  // end insert

template<class ItemType>
bool LinkedList<ItemType>::remove(int position)
{
    bool ableToRemove = (position >= 1) && (position <= itemCount);
    if (ableToRemove)
    {
        Node<ItemType>* curPtr = nullptr;
        if (position == 1)
        {
            // Remove the first node in the chain
            curPtr = headPtr; // Save pointer to node
            headPtr = headPtr->getNext();
        }
        else
        {
            // Find node that is before the one to remove
            Node<ItemType>* prevPtr = getNodeAt(position - 1);

            // Point to node to remove
            curPtr = prevPtr->getNext();

            // Disconnect indicated node from chain by connecting the
            // prior node with the one after
            prevPtr->setNext(curPtr->getNext());
        } // end if

        // Return node to system
        curPtr->setNext(nullptr);
        delete curPtr;
        curPtr = nullptr;
        itemCount--; // Decrease count of entries
    } // end if

    return ableToRemove;
} // end remove

In my main, I have following code:

const int ITEM_COUNT = 6;
    LinkedList<std::string>* list = new LinkedList<std::string>();
    list->insert(1, "Amy");
    list->insert(2, "Bob");
    list->insert(3, "Joe");


    for (int i = 0; i < ITEM_COUNT; i++) {
        std::cout << list->getEntry(i + 1) << '\n';
    }

    LinkedList<std::string>* list2 = new LinkedList<std::string>();
    *list2 = *list;

I was trying to check if my copy operator does right, but the error appears on the code: In template: no matching function for call to 'swap'

*list2 = *list;