mardi 31 juillet 2018

What is the proper syntax here?

ALL,

class __declspec(dllexport) Foo
{
protected:
    struct Bar;
    Bar *pimpl;
};

struct Foo::Bar
{
    static std::mutex my_mutex;
};

Class Foo is interface class with a bunch of pure virtual functions that is located inside 1 header file. This header file is located inside a statically linked library.

Now in order to prevent a link error I'm trying to define my_mutex variable, but I can't figure out the syntax for it.

An obvious

Foo::pimpl::my_mutex;

gives an error.

Could someone please help?

TIA!

Undefined references to librealsense classes and function

I have installed Intel OpenVino toolkit to my Xubuntu 16.04, its samples are designed for use with webcam or similar uvcvideo sources.

I have been trying to update these samples to work with Intel Realsense R200 camera.

I have tried my R200 with ros, and it is working with out any problems. Also I installed librealsense legacy library.

Everything seems fine but I have some troubles with porting.

I have added library:

// librealsense C++ header file
#include <librealsense/rs.hpp>

Then created necessary variables:

using namespace rs;

// Window size and frame rate
int const INPUT_WIDTH   = 320;
int const INPUT_HEIGHT  = 240;
int const FRAMERATE     = 60;

// Named windows
char const *WINDOW_DEPTH = "Depth Image";
char const *WINDOW_RGB   = "RGB Image";


context     _rs_ctx;
//device * _rs_camera = _rs_ctx.get_device(0);
device*     _rs_camera = NULL;

intrinsics  _depth_intrin;
intrinsics  _color_intrin;
bool        _loop = true;

Also I added some functions:

    bool display_next_frame( )
{
    // Get current frames intrinsic data.
    _depth_intrin   = _rs_camera->get_stream_intrinsics( rs::stream::depth );
    _color_intrin   = _rs_camera->get_stream_intrinsics( rs::stream::color );

    // Create depth image
    cv::Mat depth16( _depth_intrin.height,
                     _depth_intrin.width,
                     CV_16U,
                     (uchar *)_rs_camera->get_frame_data( rs::stream::depth ) );

    // Create color image
    cv::Mat rgb( _color_intrin.height,
                 _color_intrin.width,
                 CV_8UC3,
                 (uchar *)_rs_camera->get_frame_data( rs::stream::color ) );

    // < 800
    cv::Mat depth8u = depth16;
    depth8u.convertTo( depth8u, CV_8UC1, 255.0/1000 );

    imshow( WINDOW_DEPTH, depth8u );
    cvWaitKey( 1 );

    cv::cvtColor( rgb, rgb, cv::COLOR_BGR2RGB );
    imshow( WINDOW_RGB, rgb );
    cvWaitKey( 1 );

    return true;
}


// Initialize the application state. Upon success will return the static app_state vars address
bool initialize_streaming( )
{
    bool success = false;
    if( _rs_ctx.get_device_count( ) > 0 )
    {
        _rs_camera = _rs_ctx.get_device( 0 );

        _rs_camera->enable_stream( rs::stream::color, INPUT_WIDTH, INPUT_HEIGHT, rs::format::rgb8, FRAMERATE );

        _rs_camera->start( );

        success = true;
    }
    return success;
}

But while compiling my edited main.cpp with ./build_samples.sh script which is came with toolkit.

I couldn't solve these undefined references issues:

[100%] Linking CXX executable ../intel64/Release/interactive_face_detection_sample CMakeFiles/interactive_face_detection_sample.dir/main.cpp.o: In function display_next_frame()': main.cpp:(.text+0x6af): undefined reference tors_get_stream_intrinsics' main.cpp:(.text+0x72e): undefined reference to rs_get_stream_intrinsics' main.cpp:(.text+0x7ae): undefined reference tors_get_frame_data' main.cpp:(.text+0x8d8): undefined reference to rs_get_frame_data' CMakeFiles/interactive_face_detection_sample.dir/main.cpp.o: In functioninitialize_streaming()': main.cpp:(.text+0xed9): undefined reference to rs_get_device_count' main.cpp:(.text+0xf07): undefined reference tors_get_device' main.cpp:(.text+0xf49): undefined reference to rs_enable_stream_ex' main.cpp:(.text+0xf6e): undefined reference tors_start_source' CMakeFiles/interactive_face_detection_sample.dir/main.cpp.o: In function rs::context::~context()': main.cpp:(.text._ZN2rs7contextD2Ev[_ZN2rs7contextD5Ev]+0x6): undefined reference tors_delete_context' CMakeFiles/interactive_face_detection_sample.dir/main.cpp.o: In function rs::error::error(rs_error*)': main.cpp:(.text._ZN2rs5errorC2EP8rs_error[_ZN2rs5errorC5EP8rs_error]+0x2e): undefined reference tors_get_error_message' main.cpp:(.text._ZN2rs5errorC2EP8rs_error[_ZN2rs5errorC5EP8rs_error]+0x68): undefined reference to rs_get_failed_function' main.cpp:(.text._ZN2rs5errorC2EP8rs_error[_ZN2rs5errorC5EP8rs_error]+0x79): undefined reference tors_get_failed_function' main.cpp:(.text._ZN2rs5errorC2EP8rs_error[_ZN2rs5errorC5EP8rs_error]+0xad): undefined reference to rs_get_failed_args' main.cpp:(.text._ZN2rs5errorC2EP8rs_error[_ZN2rs5errorC5EP8rs_error]+0xbe): undefined reference tors_get_failed_args' main.cpp:(.text._ZN2rs5errorC2EP8rs_error[_ZN2rs5errorC5EP8rs_error]+0xf5): undefined reference to rs_free_error' CMakeFiles/interactive_face_detection_sample.dir/main.cpp.o: In functionrs::log_to_console(rs::log_severity)': main.cpp:(.text._ZN2rs14log_to_consoleENS_12log_severityE[_ZN2rs14log_to_consoleENS_12log_severityE]+0x22): undefined reference to rs_log_to_console' CMakeFiles/interactive_face_detection_sample.dir/main.cpp.o: In functionmain': main.cpp:(.text.startup+0x134): undefined reference to rs_get_frame_data' main.cpp:(.text.startup+0xdeb): undefined reference tors_is_device_streaming' main.cpp:(.text.startup+0xe1b): undefined reference to rs_wait_for_frames' CMakeFiles/interactive_face_detection_sample.dir/main.cpp.o: In function_GLOBAL__sub_I__ZN3fLB7FLAGS_hE': main.cpp:(.text.startup+0x496f): undefined reference to `rs_create_context' collect2: error: ld returned 1 exit status interactive_face_detection_sample/CMakeFiles/interactive_face_detection_sample.dir/build.make:117: recipe for target 'intel64/Release/interactive_face_detection_sample' failed make[2]: * [intel64/Release/interactive_face_detection_sample] Error 1 CMakeFiles/Makefile2:254: recipe for target 'interactive_face_detection_sample/CMakeFiles/interactive_face_detection_sample.dir/all' failed make[1]: * [interactive_face_detection_sample/CMakeFiles/interactive_face_detection_sample.dir/all] Error 2 Makefile:127: recipe for target 'all' failed make: *** [all] Error 2

Full of my code is: https://gist.github.com/mustafaxfe/7a3b26da2d28e72c933f15a05f5db85c

Function using older class declaration before ctor

I've written the following to generate random numbers biased around a mean:

#include <random>
#include <iostream>

using namespace std;

random_device rd;
mt19937_65 eng(rd());
piecewise_linear_distribution<double> burst_distr;

void foo()
{
    double x = burst_distr(eng);
    cout << "Foo Burst: " << x << endl;
}

int main()
{
   double min, max, avg;
   cout << "MINIMUM NUMBER OF PROCESS BURST UNITS:" << endl;
   cin >> min;
   cout << "MAXIMUM NUMBER OF PROCESS BURST UNITS:" << endl;
   cin >> max;
   cout << "AVAGAGE NUMBER OF PROCESS BURST UNITS:" << endl;
   cin >> avg;
   double mean = (3 * avg) - max - min;
   piecewise_linear_distribution<double> burst_distr({ min, mean, max }
                                                     [mean_bound](double x) 
                                                     {
                                                         return x == mean_bound ? 1.0 : 0.0; 
                                                     }
                                                    );

    for (int i = 0; i < 100; ++i)
    {
        foo();
        cout << "Local Burst: " << burst_distr(eng) << endl; 
    }
    return 0;
};

When I run this however, foo() generates random numbers between 0 and 1 while the local call to burst_distr generates numbers within the range supplied.

It appears that declaring burst_distr before foo() has foo() point back to that uninitialized object but then initializing again with the same name later in main() does not update or overwrite the object in the namespace.

I've not encountered this behavior before, but how can I declare a class prior to a function definition and then call its ctor later?

Using remove_reference in function header

Say I have the following:

template <typename... A>
class MyClass
{
public:

    void func(A... args)
    {
        // do stuff
    }
};

What I really want is for func() to take l-value references, so something like this:

template <typename... A>
class MyClass
{
public:

    void func(std::remove_reference<A>::type&... args)
    {
        // do stuff
    }
};

This doesn't compile; is this sort of thing possible? Thanks.

inferring width of most template objects, but being explit with others with respect to template function?

I've noticed that modern C++ (C++11 etc..) can sometimes infer the width of a template object when passed to a function without explicitly passing the width using angle braces when invoking the function.

But, what if I want a functions argument, "bitsets", to have the width inferred automatically as a function input, and the return value, "bitset", to be explicitly specified when invoking the function using angle braces or casing. Is it possible? Example:

#include <bitset>
using namespace std;

// expand or truncate bitset without sign extension
template<int N_NEW, int N_OLD> 
bitset<N_NEW>
bresize(const bitset<N_OLD>)
{
return bitset<N_NEW> {value.to_ullong() & ((1<<N_NEW)-1) }; 
}

For instance is it possible:

bitset<16> x {0xABCD};

// version explicit everything (Not what I want)
auto y2 = bresize<32, 16>(x); 


//Inference Attempt #1
auto  y1 = bresize<32>(x); 

//Inference Attempt #2
bitset<32> y3 = bresize(x);

//Inference Attempt #3
auto y4 = (bitset<32>)bresize(x);

return

}

I just want to understand what the rules are when inferring a template size parameter in the scenario stated above... the goal is infer as much as possible regarding the input size of the bitset but to be explicit about the output size.. possible in modern c++11?

Why can this boost::asio::tcp::socket be re-used?

Below is some code from a boost::asio example. Why is it okay to move the socket_ member when constructing a chat_session if the recursive call at the bottom of the handler is going to hand this same tcp::socket out next time an accept happens? I thought that after a move operation, an object was no longer safe to use.

class chat_server
{
public:
  chat_server(boost::asio::io_service& io_service,
      const tcp::endpoint& endpoint)
    : acceptor_(io_service, endpoint),
      socket_(io_service)
  {
    do_accept();
  }

private:
  void do_accept()
  {
    acceptor_.async_accept(socket_,
        [this](boost::system::error_code ec)
        {
          if (!ec)
          {
            std::make_shared<chat_session>(std::move(socket_), room_)->start();
          }

          do_accept();
        });
  }

  tcp::acceptor acceptor_;
  tcp::socket socket_;
  chat_room room_;
};

How to use C++ Boost library by using constructor to Subtracts S seconds from self, returning self?

Here is the syntax of constructor of RW(Rogue-Wave) library, I need to write it using Boost library to meet same functionality, below is the RW syntax,

RWTime& RWTime::operator-=(unsigned long s);

output should be: It Subtracts s seconds from self, returning self

Here i tried to implement it using boost library, but not able to implement and if i include parameters then it gives error, i am new to the C++, Please anyone suggest me to do this further.

Here is my similar code(I think its wrong functionality i implemented), i found these methods from stack-overflow but not able to make it happen.

#include <iostream>
#include <boost/date_time/posix_time/posix_time.hpp>

using namespace boost::gregorian;
using namespace boost::local_time;
using namespace std;

class seconds
{
public:
seconds();
};
long seconds::seconds()
{
boost::posix_time::ptime utcTime { { 1901, 1, 1 } };
auto diff = boost::posix_time::second_clock::local_time() - utcTime;
cout<<diff.total_seconds();
cout<<"\n";
}

int main()
{
seconds obj;
}

This is my guess code, i am doing this because my requirement is to customize the boost to our own product use, I need below functionality in Boost code, please suggest me.

RWTime& RWTime::operator-=(unsigned long s);

output should be: It Subtracts s seconds from self, returning self

How to change the inserted value during the insertion?

I would like to insert the values from vector b to vector a, and multiply the values by -1 during the insertion. Currently I simply insert the elements, and multiply them by -1 afterwards:

a.insert(std::end(a), std::begin(b), std::end(b));
// ...

How is it possible to get the negative values already during the insertion, withoud modifying the original b vector?

What I would like to achieve:

old a = {2,3,4}
b = {3,4,5}

a = {2,3,4,-3,-4,-5}

What differences c++ reference with other languages [on hold]

Just like java or c# reference, what differences in c++ reference, forgive my poor English. ^_^

how to tell if a enum class value is in a specified range of enum class in a more effective way?

enum class color {
    red,
    black,
    white,
    yellow,
    green,
    blue,
};
color c;
if(c == color::red && c == color::black || c == color::green -etc.)

The last statement is too fussy,is there any better way to do it like if(c in(color::red,color::black,color::green))?

lundi 30 juillet 2018

fail to capture random engine by value

I have this code that cannot be compiled by gcc 8, but I cannot understand why.

#include <iostream>
#include <algorithm>
#include <random>
using namespace std;

template<class... T>
void diagnose(T... x);

int main()
{
    auto d = normal_distribution<double>(0.0, 1.0);
    auto g = default_random_engine();
    cout << d(g) << endl;
    auto gen = [=](){
        //diagnose(d, g);
        return d(g);   // ******
    };
    cout << gen() << endl;
}

The error message says (pointing to the line marked by *******):

error: no match for call to ‘(const std::normal_distribution<double>) (const std::linear_congruential_engine<long unsigned int, 16807, 0, 2147483647>&)

The code, however, works if I change the capture to be by reference.

If I uncomment the commented //diagnose line, the error message is like this (need also change return d(g) to return 1.0):

undefined reference to `void diagnose<std::normal_distribution<double>, std::linear_congruential_engine<unsigned long, 16807ul, 0ul, 2147483647ul> >(std::normal_distribution<double>, std::linear_congruential_engine<unsigned long, 16807ul, 0ul, 2147483647ul>)'

As you can see, in the capture-by-value case, the parameter g is a const reference. But the const does not appear in diagnosis.

Can somebody explain what is going on here?

Removing elements from vector using remove_if

I am trying to remove vector elements using remove_if. But unsuccessfully. What am I doing wrong?

Here's my code:

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

void printme(std::vector<int>& a){
    for(const auto& item: a)
    std::cout << item << std::endl;
}

int main()
{
    std::vector<int> a {1, 2, 3, 4, 5, 6};
    printme(a);  
    a.erase( (std::remove_if(a.begin(), a.end(), [](const int& x){
        return x == 2;
        }), a.end()));
    printme(a);
}

My output is just:

1 2 3 4 5 6

Expected output:

1 2 3 4 5 6 1 3 4 5 6

Is a flush required for cout in a critical section?

I have some code compiled under the c++11 standard. I have multiple threads writing to cout. I noticed when writing many lines there would be some cases where some lines were missing (like 1 out of 2000000). I was surprised to see this since my string (outStr below) was local to each thread and I had a critical section around my writes to stdout. I noticed the problem went away when I flushed the stream.

#pragma omp critical(cout)
{
    cout << outStr;
    cout.flush();
}

Is this expected behaviour? What really tricked me was the fact that when I wrote a relatively small number of lines (<100000), I would always see the number of expected lines outputted.

Overall I'm not really happy with the critical section in general since I'm noticing in my profiling that it is causing a lot of contention. I'm open to any suggestions to improve my I/O.

How to construct a tree structure with smart pointer?

Here is a code snippet which i want to get a tree structure with smart pointer.But i got c3646('parent': unknown override specifier) and c4430(missing type specifier - int assumed) in vs.Does anybody know what's going on and how do i fix it>?

#include<memory>

class Obj {
    ObjPtr parent;
};
typedef std::shared_ptr<Obj> ObjPtr;

Undefined reference to friend function template defined inside class in a namespace

This is a follow-up on my answer to this question.

The original answer I posted does not have any namespaces, and it solves the problem. However, the OP subsequently made an edit claiming that the solution does not work if the class is inside a namespace.

My initial reaction was that you can make it work by simply having using N::f; either at global scope or inside main() (or any other function). While that is certainly the case, the OP (justifiably) commented that this is not ideal, and I agree.

Nevertheless, I still thought that calling N::f without having using N::f; should work just fine, but to my surprise I got an undefined reference error when I tried the following:

#include<iostream>

namespace N
{
    template<class T>
    class Class;

    template<typename U, typename W>
    Class<W> f (Class<U>& C, const Class<U>& D);

    template<class T>
    class Class
    {

    protected: // this could be private

        T m_t;

    public:
        Class()
            :
              m_t(T())
        {}

        Class(T t)
            :
              m_t(t)
        {}

        T& getT()
        {
            return m_t;
        }

        template<typename U, typename W>
        friend Class<W> f (Class<T>& C, const Class<T>& D)
        {
            C.m_t += D.m_t;
            Class<W> R;
            std::cout << R.m_t << std::endl; // I don't want this to be possible
            return R;
        }
    };
}

int main()
{
    N::Class<int> C(42), D(24);
    std::cout << N::f<int, char>(C, D).getT() << std::endl;
}

error: undefined reference to N::Class<char> N::f<int, char>(N::Class<int>&, N::Class<int> const&)'.

At this point, I went on to try different compiler versions and discovered that the above works as it does without a namespace with GCC < 6 but not with GCC > 6. ICC 17 also seems to pick up on the protected member access inside f, but not ICC 18. Clang never picks it up.

Which is the intended behaviour? Should the definition be made available to the linker in this case without using N::f;?.


Edit 1:

To clarify, I want to retain the intended behaviour, namely restricting f to be a friend only to Class instantiations that match its arguments (so in the example f would be friend to Class<T> but not to Class<W>).

C++ Save string line by line to a file as fast as possible

I was trying to write to a file or save the string s.substr (space_pos) in a vector as fast as possible. I tried to write it to a file with ofstream or to output it with cout but it takes a long time. The size of the text file is 130mb.

This is the code:

fstream f(legitfiles.c_str(), fstream::in );
string s;
while(getline(f, s)){
    size_t space_pos = s.rfind(" ") + 1;

    cout << s.substr(space_pos) << endl;
    ofstream results("results.c_str()");
    results << s.substr(space_pos) << endl;
    results.close();

}
cout << s << endl;
f.close();

Is there a way to write or print the string in a faster way?

How output is calculated?

cout<<"dbba" - "bcx";

Here output is -5 in C++.

I want to know how this output is calculated here?

Fastest way to repeat a vector in Eigen c++

I have two vectors:

Eigen::Array2d A;
Eigen::Array4d B;

Basically, the vector A contains some value like

0.3
0.7

The idea is that I would like to get the vector B as follows

0.3
0.3
0.7
0.7

What is the fastest way to do that? I want the "fastest" way because I have to do this manipulation a lot of times. I know that I could use a mixture of replicate, transpose(), and Map functions to do it but it won't be so fast.

Should I use pointers, instead? Let's say the first two rows of B would point to the first row of A, and the two last rows of B would point to the last row of A? Does it make sense?

Casting of object pointers

obj is pointer of type B pointing to an object of D. But, what is the difference between the pointer returned by obj->getA() and obj pointer . "this" pointer returns the address of calling object which should be obj, but the return type is A*. So what exactly does obj->getA() represent , and where such a scenario can be useful ?

class A{
};

class B{
  virtual A* getA() { return NULL; }
};

class C : public A, public B{
   A* getA() { return this; }
}

class D : public C{
}

int main(){
 B *obj = new D();
 obj->getA();
}

Locking mutex before using std::condition_variable

I have a question related to std::condition_variable. I read a lot about it and all examples shown locked mutex before using std::condition_variable like that:

std::unique_lock<std::mutex> lock(mutex);
condition_variable.wait(lock);
//...

or like that:

std::unique_lock<std::mutex> lock(mutex);
condition_variable.notify_one();
//...

Is it necessery to lock mutex before using condition variable or is it thread-safe?

Generate random numbers in range given a mean

How would one generate random numbers between a min and max with a supplied mean?

For example, if the min was 4 and max was 25 with an average of 7, generate random numbers in that range that bias the resulting mean (i.e. the mean of all the generate numbers would be close to 7).

I already know how to generate numbers in a range, but the mean is a new thought to me. Is there perhaps something in the <random> library that is built for this?

C++ Singleton Instance disable re-call

When using the Meyers singleton:

class Singleton
{
public:
    static T& instance()
    {
        static T instance;
        return instance;
    }

    void Hello()
    {
        std::cout <<"Hello!\n";
    }

protected:
    Singleton() = default;
    ~Singleton() {};

private:
    Singleton(Singleton const&);
    Singleton& operator=( Singleton const& );
};

You are able to call the instance as follow:

Singleton::instance().Hello();

or

Singleton& s = Singleton::instance();
s.Hello();

But I'm wondering if there is a way to block this:

Singleton::instance().instance();

How to avoid to call instance() as a method (with the .) and only support the static call with the :: ?

Is there a way to use static_assert, template enable_if or anything else?

C++ multi chat server

i am trying to write a multi chat server without using threads. I came across select() but i am having hard time understanding how can i read a client request and send it right away when the send() blocks and the client socket might not be ready to be wriiten and by this losing the server parallel io ability.

If(fd_isset(socket,&read_fds){
    Recv()
    SendMesgToRequestedClient()
}

I thought a possible soulution is to save each client a list of pending messages and send them on fd_isset(socket,&write_fds) but then instand of saving cpu i might use a ton of memory.

Displaying Hex codes from buffer after reading from a file

I'm trying to store the hex codes read from a file into a buffer and then display it on the console, so far it doesn't seem to work. This is my code:

using namespace std;

int main()
{
 ifstream file("Fishie.ch8",ios::binary);
 if (!file.is_open())
{
    cout << "Error";
}
else
{
    file.seekg(0, ios::end);
    streamoff size = file.tellg();
    file.seekg(0, ios::beg);
    char *buffer = new char[size];
    file.read(buffer, size);
    file.close();
    for (int i = 0; i < size; i++)
    {
        cout <<hex<< buffer[i] << " ";
    }
}
delete[] buffer;
cin.get();
}

The expected output should be this:

00 e0 a2 20 62 08 60 f8 70 08 61 10 40 20 12 0e
d1 08 f2 1e 71 08 41 30 12 08 12 10 00 00 00 00
00 00 00 00 00 18 3c 3c 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
3e 3f 3f 3b 39 38 38 38 00 00 80 c1 e7 ff 7e 3c
00 1f ff f9 c0 80 03 03 00 80 e0 f0 78 38 1c 1c
38 38 39 3b 3f 3f 3e 3c 78 fc fe cf 87 03 01 00
00 00 00 00 80 e3 ff 7f 1c 38 38 70 f0 e0 c0 00
3c 18 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

Instead the above output I get some strange looking symbols with lots of empty spaces. It looks like this: binary file output What could be the problem?

How to add C++11 support in a Qt project for Android?

So I am using Qt 5.11 to build an app for Android. In the process I used this C++11 library https://github.com/nlohmann/json since the default json support provided by Qt has some problems. Anyway when I compile the project for Android it start giving me errors like: error: 'to_string' is not a member of 'std'. I found out that the Android SDK has some problems using the entirety of the feature provided by C++11. There are a few suggestions made at the following links Android ndk std::to_string support and How to use std::stoul and std::stoull in Android?

A solution seems to be adding : APP_STL:=c++_static to the Application.mk file in an Android project, but how can I do this in a Qt Project? Do I have to edit build.gradle? I already included (with no success):

CONFIG += c++11 QMAKE_CXXFLAGS += -std=c++11

Using C++ Boost library how to return the number of seconds since 00:00:00 January 1, 1901 GMT?

The seconds() method should call from main method and it should print the format of 00:00:00 January 1, 1901 GMT and it should returns(calculate) number of seconds elapsed till user input time, i am new to the C++, i tried a lot but not able to make it happen, Below is the code i tried, anyone please help

boost::posix_time::ptime timeObj = boost::posix_time::time_from_string("1901/01/01 00:00:00"); // here i tried to start the day from the mentioned date and time

boost::posix_time::ptime timeLocal = boost::posix_time::second_clock::local_time(); // Get current system time

boost::posix_time::time_duration durObj = timeLocal.time_of_day(); std::cout << "Seconds : = " << timeLocal.time_of_day().seconds() << std::endl;

after this

1) I need to get a difference of seconds from 00:00:00 January 1, 1901 GMT to user input time. 2) in front of it should returns the format of 00:00:00 January 1, 1901 GMT.

I am doing this because i am customizing this boost library for our own product use. please suggest me to do this.

External instantiation of nested template in another class

I have to sort a list of int pointers with a class SmartPointer. But in the beginning where the object liste2 of the type class ListeTriee is instantiated in main.cpp I receive an error message:

Error message from compiler

Undefined symbols for architecture x86_64:
  "ListeTriee<SmartPointer<int> >::ListeTriee()", referenced from:
      _main in main.cpp.o
  "ListeTriee<SmartPointer<int> >::~ListeTriee()", referenced from:
      _main in main.cpp.o
ld: symbol(s) not found for architecture x86_64

I think the problem occurs when instantiating a template with the given template argument in ListeTriee.cpp.

MacBook Pro, CLion 2016.3.2

Main.cpp

int main()
{
    cout << "*** 7. Liste triee de pointeurs de int AVEC SmartPointer ***************************************************" << endl;
      ListeTriee<SmartPointer<int> > liste2;
        /*
      liste2.insere(new int (5));   // ne pas oublier de redefinir operator= de SmartPointer !!!
      liste2.insere(new int (2));
      liste2.insere(new int (8));
      liste2.insere(new int (3));
      liste2.Affiche(); // redefinir operator<< de SmartPointer de telle sorte qu'il affiche la valeur du pointeur

return 0;
}

The line that causes problems is this one: ListeTriee<SmartPointer<int> > liste2;

SmartPointer.h

    #ifndef C_PROGRAMM8_SMARTPOINTER_H
    #define C_PROGRAMM8_SMARTPOINTER_H

    #include <iostream>
    #include <stdlib.h>
    #include "Ligne.h"

    using namespace std;
    template <class T> class SmartPointer{
    private:
        T *val;
    public:
        //Constructeurs
        SmartPointer<T>();
        SmartPointer<T>(SmartPointer<T> *);
        SmartPointer<T>(T *);

        //Destructeur
        ~SmartPointer<T>();

        //Surcharge d'opérateurs
        bool operator <(const SmartPointer &) const;                  //<
        friend ostream &operator<<(ostream &, SmartPointer<T> *);
        T* operator->() const;
        T& operator*() const;

        //Getter
        T* getVal() const;

        //Autre
        void Delete();
    };
    #endif //C_PROGRAMM8_SMARTPOINTER_H

SmartPointer.cpp

#include "SmartPointer.h"
template <class T>
SmartPointer<T>::SmartPointer() {
    cout << "-> Constructeur par defaut [SmartPointer]" << endl;

    val = NULL;
}
template <class T>
SmartPointer<T>::SmartPointer(T *new_Val) {
    cout << "-> Constructeur d initialisation [SmartPointer]" << endl;

    val = new_Val;
}
template <class T>
SmartPointer<T>::SmartPointer(SmartPointer<T> *new_SmartPointer) {
    cout << "-> Constructeur de copie [SmartPointer]" << endl;

    *val = *(new_SmartPointer -> val);
}
template <class T>
SmartPointer<T>::~SmartPointer() {
    cout << "-> Destructeur [SmartPointer]" << endl;
}
template <class T>
bool SmartPointer<T>::operator<(const SmartPointer &new_SmartPointer) const {
    if(*val < *(new_SmartPointer.val))
        return true;
    else
        return false;
}
template <class T>
T& SmartPointer<T>::operator*() const {
    return *val;
}
template <class T>
T* SmartPointer<T>::operator->() const {
    return val;
}
template <class T>
void SmartPointer<T>::Delete() {
    cout << "-> Appel a 'Delete' de l objet pointee" << endl;
    if(val != NULL)
        delete val;
}
template <class T>
T *SmartPointer<T>::getVal() const {
    return val;
}
template <class T>
ostream &operator<<(ostream &new_Out, SmartPointer<T> *new_SmartPointer){
    new_Out << new_SmartPointer;

    return new_Out;
}
template class SmartPointer<int>;
template class SmartPointer<Ligne>;

ListeTriee.h

#ifndef C_PROGRAMM6_LISTETRIEE_H
#define C_PROGRAMM6_LISTETRIEE_H

#include "ListeBase.h"
template <class T>
class ListeTriee : public ListeBase<T>{
public:
    //Constructeurs
    ListeTriee();
    ListeTriee(const ListeTriee &);
    //Destructeurs
    virtual ~ListeTriee();
    //Methodes virtual
    virtual T *insere(const T &);
};
#endif //C_PROGRAMM6_LISTETRIEE_H

ListeTriee.cpp

#include "ListeTriee.h"
template <class T>
ListeTriee<T>::ListeTriee() : ListeBase<T>(){
    cout << "-> Constructeur par defaut [ListeTriee]" << endl;
}
template <class T>
ListeTriee<T>::ListeTriee(const ListeTriee & new_ListeTriee) : ListeBase<T>(new_ListeTriee){
    cout << "-> Constructeur de copie [ListeTriee]" << endl;
}
template <class T>
ListeTriee<T>::~ListeTriee() {
    cout << "Destructeur [ListeTriee]" << endl;
}
template <class T>
T* ListeTriee<T>::insere(const T &new_T) {
    Cellule<T> *TmpPrec, *Tmp, *Ajout;

    Ajout = new Cellule<T>;

    Ajout -> valeur = new_T;
    Ajout -> suivant = NULL;

    if(this -> ptete == NULL) {
        this->ptete = Ajout;
    }
    else{

        TmpPrec = NULL;
        Tmp = this -> ptete;

        while(Tmp -> suivant != NULL && Ajout -> valeur > Tmp -> valeur){
            TmpPrec = Tmp;
            Tmp = Tmp -> suivant;

        }
        if(Ajout -> valeur <= Tmp -> valeur)
        {

            //Nouvelle valeur va être placée au début de la liste
            if(TmpPrec == NULL)
            {
                Ajout -> suivant = this -> ptete;
                this -> ptete = Ajout;
            }
            else{   //Val se trouve entre la position 1 et n - 1
                TmpPrec -> suivant = Ajout;
                Ajout -> suivant = Tmp;
            }

        }
        else
        {   //Élément se trouve à la fin de la liste
            Tmp -> suivant = Ajout;
            Ajout -> suivant = NULL;
        }
    }
    //cout << Ajout -> valeur << endl;

    return &Ajout -> valeur;
}
template class ListeTriee<int*>;
template class ListeTriee<int>;
template class Cellule<int>;
template class ListeTriee<Couleur>;

I have tried the explicit instantiation: template class ListeTriee<SmartPointer<int> >; at the end of ListeTriee.cpp so that the compiler can create a new class with the given template argument but the error message I get is even bigger.

How std::size_t is calculated in the template code for array type

I was reading the book C++ templates - the complete guide, 2nd edition and got the code from that which looks like this:-

template<typename T>
void compare(const T &arg1, const T &arg2)
{
    std::cout << arg1 << arg2;
}

int main() {
    compare("hello", "world1");
    return 0;
}

The above code gave me this error:- "error C2782: 'void showVal(const T &,const T &)': template parameter 'T' is ambiguous". This is reasonable because the arguments I am passing are deduced to const char[6] and const char[7]. To fix this, I have made the changes in the function which look like this after the change :-

template<typename T, std::size_t L1, std::size_t L2>
void showVal(const T (&arg1)[L1], const T(& arg2)[L2])
{
    std::cout << arg1 << arg2;
}

PS:- I've got this fix from the book

The main confusion underlies in the value of L1 and L2. How compiler knows that it has to pass 6 and 7 to the template parameter L1 and L2. Is there any rule for array type.

c++ non-type parameter pack expansion

I am writing template function that is parametrized by single type, and has variable number of parameters of the same type (not of different types). It should check if first value is among the rest. I wanted to write it like this:

#include <unordered_set>

template <typename T>
static bool value_in(T val, T vals...) {
    // compiles, but uses only vals[0]:
    const std::unordered_set<T> allowed {vals};
    // error: pack expansion does not contain any unexpanded parameter packs:
    // const std::unordered_set<T> allowed {vals...};
    return allowed.find(val) != allowed.end();
}
// usage
enum class Enumeration {one, two, three};
int main () {
    // should return true -> 0
    return value_in(Enumeration::two,
                    Enumeration::one,
                    Enumeration::two) ? 0 : 1;
}

I expected that second to work, but it doesn't compile because

test.cpp: In function ‘bool value_in(T, T, ...)’:
test.cpp:7:46: error: expansion pattern ‘vals’ contains no argument packs

I see the "(T, T, ...)" instead of "(T, T...), so probably I messed up function declaration and ended with C-style variadic function.

How to write declaration that will accept arbitrary number of parameters of the same type?

Are there any platforms where fixed width types (intXX_t) are missing?

C++11 has fixed width, 2's complement types: (u)int8_t, (u)int16_t, etc.

However, these types are optional.

Sometimes I need to use these types, so my code might be less portable because of this.

Is there any platform (with C+11 compiler available) currently, where these types don't exist?

Note 1: I know, that there is hardware which doesn't support these types. However, all such hardware I know doesn't have a C++11 conformant compiler. This question is about a C++11 implementation, where fixed width types are actually missing.

Note 2: I know, that there are mandatory least and fast types, but this question is about exact width types.

copy constuctor of templated class does not always work for newer gcc

I am maintaining some legacy C++ code, which worked fine so far. Recently I switched from Ubuntu 16.04 (gcc 5.4) to Ubuntu 18.04 (gcc 7.3) and the code did not compile anymore (With clang 6.0 it did however). I am pretty sure it is c++ version thing. I have made changes to the code and it compiles now, but I would like to have some explanation of what is going on exactly.

The culprit is the copy constructor of the following fast hash map class

template< typename Key, typename Val, size_t (*hashf)(Key const &), typename KeyCompare = std::equal_to<Key> >
class fhash_map
{
public:
  fhash_map(fhash_map const & copy);
}

Now there is some other class, let's call it UseFull, which has various fhash_map members (I call this Variant A)

class UseFull: public UseFullParent
{
private:
  fhash_map<A, B, C> _this_works;
  fhash_map<A, Spline*, C> _this_does_not_work;
  fhash_map<A, std::vector<Spline*>, C> _neither_does_this;
public:
  UseFull(UseFull const & copy)
  : UseFullParent(copy)
  {
    _this_works(copy._this_works);
    _this_does_not_work(copy._this_does_not_work);
    _neither_does_this(copy._neither_does_this);
  }
}

With gcc 7.3 this fails to compile with the messages

error: no match for call to ‘(UseFull<A, Spline*, C>) (UseFull<A, Spline*, C>&)’
error: no match for call to ‘(UseFull<A, std::vector<Spline*>, C>) (UseFull<A, std::vector<Spline*>, C>&)’

Note that the compiler only complains about the to latter members (as indicated by their names), not about the first member (_this_works).

If I now change the copy constructor (Variant B) of the UseFull class to read

  UseFull(UseFull const & copy)
  : UseFullParent(copy)
  ,_this_works(copy._this_works);
  ,_this_does_not_work(copy._this_does_not_work);
  ,_neither_does_this(copy._neither_does_this);
  {
  }

It works fine.

My questions are:

  1. why does Variant A work with an older gcc and not with a newer
  2. what could be so special about some of the members? Is it the Spline class? What could be going on there (It seems pretty normal to me)
  3. what exactly is the difference between Variant A and Variant B? (That makes the difference in this case)

template class operator overloading multiple typenames C++

I have the followign code in surf.h in which a template class with two different types are declared:

template <typename T1, typename T2>
class surf;

template <typename T1, typename T2>
ostream & operator << (ostream & str, surf<T1,T2> & ov);

template <typename T1, typename T2>
class surf
{
public:
    surf(T1 v1, T2 v2):
    v1_(v1),
    v2_(v2)
    {}

    friend ostream & operator << <T1, T2> (ostream & str, surf<T1,T2> & ov);

    T1 v1_;
    T2 v2_;

};

template <typename T1, typename T2>
ostream & operator << (ostream & str, surf<T1,T2> & ov)
{
    str << "("<<ov.v1_<<","<<ov.v2_<<")";
    return str;
}

typedef surf<int,double> intSurf;

and then defined a new class in which a vector of type T is created (in field.h)

   template<typename T>
class field;

template<typename T>
ostream & operator << (ostream & str, const field<T> & ov);

template<typename T>
class field
{
public:

    field( int n, T val):
        f_(n,val)
        {}

    friend ostream & operator << <T> (ostream & str, const field<T> & ov);
protected:

    vector<T> f_;
};

template<typename T>
ostream & operator << (ostream & str, const field<T> & ov)
{
    for(auto &fE: ov.f_)
    {
        str << fE << endl;
    }
    return str;
}

typedef field<intSurf> surfField;

and in main.cpp i use this field.

#include "field.h"

int main()
{

    surfField a(4, intSurf(2,5));   

    cout<< a << endl;

    return true;
}

I compile it with g++ (version 5.4) and get the following error:

In file included from main.cpp:2:0: field.h: In instantiation of ‘std::ostream& operator<<(std::ostream&, const field&) [with T = surf; std::ostream = std::basic_ostream]’: main.cpp:9:9: required from here field.h:36:7: error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream}’ and ‘const surf’) str << fE << endl;

What am I doing worng?

dimanche 29 juillet 2018

Why google styleguide suggests to use optional int64_t as default for big integers

Google styleguide suggests to use int64_t when value is "greater than or equal to 2^31", but according to standard it is optional, so wouldn't it be better to use int_least64_t? What benefits of use int64_t besides shorter name?

C++ Embedded Control Register Template

My current job has had me doing research into creating classes for arbitrary embedded device registers. Currently I am working with a number of targets with varying register sizes and I would like to standardize (or at least come up with some logical way) of enumerating objects for memory-mapped io, registers, etc. The current company standard is to place a variable at the register location.

volatile uint16_t &register_obj = *reinterpret_cast<volatile uint16_t *>(0x01A02);

I read a few papers and discussions on the subject of embedded C++, most notably this blog post by Niklas Hauser and this overview providing a comparison and extension of a few other papers. These posts contain further references to a great paper on representing and manipulating hardware with C and C++ as well as some mock examples and alternative ideas in Ken Smith's C++ Hardware Register Redux.

I further defined a type alias to represent the register width with:

/* These define an alias for the largest register that can exist in a 
* sub-module. Where a module (IE: UART) contains an arbitrary number of 
* sub-modules (IE UART_CTL0, UART_CTL1, UART_INTERRUPTS...) as defined in the 
* vendor's datasheet.
*/
#if defined(__MSP430__)
using reg16_t = volatile uint16_t;
#elif defined(__ARM__)
using reg32_t = volatile uint32_t;
#endif

The first code snippet then becomes:

reg16_t &register_obj = *reinterpret_cast<reg16_t *>(0x01A02);

This didn't satisfy me. I realized that "placement new" might be a good fit for my applications as registers and memory-mapped IO are effectively pre-allocated memory sections that I could overlay objects over.

I read up on variadic templates and spent hours trying to design a template that created and placed an arbitrary type at a specified address, the closest was the following:

template <typename T>
T* placeObject(uintptr_t address) {
   return new (reinterpret_cast<uintptr_t*>(address)) T;
}

but the implementation is effectively a worse version of what I started with. example:

reg16_t& control_register = *submodule_new<reg16_t>(0x0160);

I tried a struct template and came up with:

template<typename T, uintptr_t address>
struct submodule
{
    T &location = *reinterpret_cast<T *>(address);
    // Also needs to implement mutability (access policy)
};

this looked promising as it's declaration is exactly what I'm looking for:

submodule<reg16_t, 0x0160> control_register_0;

but the struct-interfacing is rather awkward:

uint8_t ENABLE = 0x4;
control_register_0.location &= ~ENABLE; // this probably doesn't work

My actual questions

  • Are there any good examples of "pure C++" class-based register templates?
  • If not, how should I structure the inheritance and construction notation so that it provides a clear intention of my goals?

The end goal for this project is to have sub-modules contain access-policies and the location of data to read and write. These sub-modules would ideally be constructed in a variadic class generator to allow for arbitrarily-many, arbitrarily-sized, interfaces to memory that provide type-safety and access policies (read-only, write-only). Something of the form:

// pseudo-code
template<typename base_type, class ...submodules>
class module
{
    // somehow assign submodules to this class
};

module<submodule<reg16_t> UARTControl0, submodule<reg16_t> UARTStatus> UART();

UART.UARTControl0.Write(0x0001);
bool uart_enabled = UART.UARTStatus.read(0x);

In c++, I can create instance with `Klass k`, can I never use `new Klass() `?

Java and c# has not "new Klass() return instance ptr" feature and I can use java and c# do most things, I don't understand, why c++ has new Klass() return instance ptr, why I need use it, can I never use new Klass() and use Klass k instead of?

I'm stuck how to advance to the next line in fstream txt file;

int gamer::loadGame()
{
fstream loadFile("Save.txt", ios::in | ios::out | ios::app);
if (loadFile)
{
    loadFile.seekg(0, loadFile.end);
    int fLen = loadFile.tellg();
    loadFile.seekg(0, loadFile.beg);
    if (fLen == 0)
    {
        return 0;
    }
    else
    {
        int l, e, g,n,c;
        string s, p;
        loadFile  >> p >> l >> e >> g>>s>>c>>n;
        for (int i = n; i !=0; i--)
        {
            loadFile >> p >> l >> e >> g;
            myLevel = l;
            myExp = e;
            myGold = g;
            myPick = p;
            saveOrder[c - 1] = s;
        }
        return 1;
    }
}
system("CLS");
gOptions();
}

I'm trying to look through one part of a save which is level gold and exp but how can i go to the next part since there can be more than one save. So how can i go from the first part of the save to the next?

Could atomic operation be seen immediately by other threads?

In this question one replier says

Atomicity means that operation either executes fully and all it's side effects are visible, or it does not execute at all.

However, below is an example given in Concurrency in Action

#include <thread>
#include <atomic>
#include <iostream>
std::atomic<int> x(0),y(0),z(0);
std::atomic<bool> go(false);
unsigned const loop_count=10;
struct read_values
{
  int x,y,z;
};
read_values values1[loop_count];
read_values values2[loop_count];
read_values values3[loop_count];
read_values values4[loop_count];
read_values values5[loop_count];
void increment(std::atomic<int>* var_to_inc,read_values* values)
{
  while(!go)
  std::this_thread::yield();
  for(unsigned i=0;i<loop_count;++i)
  {
    values[i].x=x.load(std::memory_order_relaxed);
    values[i].y=y.load(std::memory_order_relaxed);
    values[i].z=z.load(std::memory_order_relaxed);
    var_to_inc->store(i+1,std::memory_order_relaxed);
    std::this_thread::yield();
  }
}

void read_vals(read_values* values)
{
  while(!go)
  std::this_thread::yield();
  for(unsigned i=0;i<loop_count;++i)
  {
    values[i].x=x.load(std::memory_order_relaxed);
    values[i].y=y.load(std::memory_order_relaxed);
    values[i].z=z.load(std::memory_order_relaxed);
    std::this_thread::yield();
  }
}
void print(read_values* v)
{
  for(unsigned i=0;i<loop_count;++i)
  {
    if(i)
    std::cout<<",";
    std::cout<<"("<<v[i].x<<","<<v[i].y<<","<<v[i].z<<")";
  }
  std::cout<<std::endl;
}
int main()
{
  std::thread t1(increment,&x,values1);
  std::thread t2(increment,&y,values2);
  std::thread t3(increment,&z,values3);
  std::thread t4(read_vals,values4);
  std::thread t5(read_vals,values5);
  go=true;
  t5.join();
  t4.join();
  t3.join();
  t2.join();
  t1.join();
  print(values1);
  print(values2);
  print(values3);
  print(values4);
  print(values5);
}

The sample output given by author is

(0,0,0),(1,0,0),(2,0,0),(3,0,0),(4,0,0),(5,7,0),(6,7,8),(7,9,8),(8,9,8),(9,9,10)
(0,0,0),(0,1,0),(0,2,0),(1,3,5),(8,4,5),(8,5,5),(8,6,6),(8,7,9),(10,8,9),(10,9,10)
(0,0,0),(0,0,1),(0,0,2),(0,0,3),(0,0,4),(0,0,5),(0,0,6),(0,0,7),(0,0,8),(0,0,9)
(1,3,0),(2,3,0),(2,4,1),(3,6,4),(3,9,5),(5,10,6),(5,10,8),(5,10,10),(9,10,10),(10,10,10)
(0,0,0),(0,0,0),(0,0,0),(6,3,7),(6,5,7),(7,7,7),(7,8,7),(8,8,7),(8,8,9),(8,8,9)  

The output seems that the modification in one thread is not visible to other thread immediately.

And the author also says:

Thread 3 doesn’t see any of the updates to x or y; it sees only the updates it makes to z. This doesn’t stop the other threads from seeing the updates to z mixed in with the updates to x and y though.

Please explain the output :

Why this code is giving this output: 1023 1024 1025 1024 1024 1025

int a=1025;
cout<<a++<<" "<<--a<<" "<<a--<<" "<<a<<" "<<a++<<" "<<a--;

Compute constant in header file at compile time

I have a header file that contains functions based upon the user OS, it does so using:

#ifdef _WIN32 // Windows
...
#else // Linux/Unix code (I know it will be either Windows or Linux/Unix)
...
#endif

The functions defined in their appropriate blocks are currently called from main at runtime and store a constant, but this got me thinking: Can I compute this constant in the header at compile?

Something like:

#ifdef _WIN32 
// function here; call it foobar()
#define WINCONST foobar()
#else
// function here; call it xfoobar()
#define NIXCONST xfoobar()
#endif

However I am not sure that you can use function calls in the #define preprocessor directive. I know that you can use it in a manner such as #define ADD(x, y) (x + y) but thats about it.

I can not choose the compiler (GCC 8.1) / is not detected in Kdevelop

Good Afternoon, I have a problem with Kdevelop 5.2.1 under ubuntu 18.04.1, Kdevelop refuses to choose GCC 8.1, he chooses the default version 4.9.

I tried this in Cmake:

set(CMAKE_C_COMPILER "gcc-8.1")
set(CMAKE_CXX_COMPILER "/usr/bin/g++-8")

and I tried this add g++ in C/C++ compiler option (usr/bin/g++-8 or usr/bin/gcc-8), but it disappears as soon as I close the option window and reopen it. I remove GCC/G++ 4.9, I have error in Kdevelop and refuses GCC 8 or G++ 8 in /usr/bin/g++-8 or gcc-8.

I know the compiler revision with this code :

#include <iostream>

int main(int argc, char **argv) {
    std::cout << __cplusplus << std::endl;
    return 0;
}

Output this : 201402

Thank you in advance for your answers :) ,

std::map both costume compare functor and function/ lambda error

I have the following:

inputs:    
    Map1["Ram"] = 8;
    Map1["Aam"] = 8;
    Map1["Some"] = 2;
    Map1["He"] = 5;
    Map1["He"] = 6;

The expected output after insertion to the std::map<std::string, int> should be:

Output:
    "Some" 2  
    "He"   5
    "He"   6
    "Aam"  8

Please note that:

  1. sorting is according to the values, not keys.
  2. the input Map1["Ram"] = 8; has overwritten by the next input Map1["Aam"] = 8;

Approach 1: Using a functor I was thinking to manage it. I have got this two errors:

||=== Build: Debug in MyTestProgram (compiler: GNU GCC Compiler) ===|
d:\mingw\include\c++\7.3.0\bits\stl_map.h||In instantiation of 'std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](std::map<_Key, _Tp, _Compare, _Alloc>::key_type&&) [with _Key = std::__cxx11::basic_string<char>; _Tp = int; _Compare = compare_functor; _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, int> >; std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type = int; std::map<_Key, _Tp, _Compare, _Alloc>::key_type = std::__cxx11::basic_string<char>]':|
D:\Programming\C++\CPP Programs\MyTestProgram\MyTestProgram.cpp|22|required from here|
d:\mingw\include\c++\7.3.0\bits\stl_map.h|511|error: no match for call to '(std::map<std::__cxx11::basic_string<char>, int, compare_functor>::key_compare {aka compare_functor}) (std::map<std::__cxx11::basic_string<char>, int, compare_functor>::key_type&, const std::__cxx11::basic_string<char>&)'|
D:\Programming\C++\CPP Programs\MyTestProgram\MyTestProgram.cpp|12|note: candidate: bool compare_functor::operator()(const T&, const T&) const|
D:\Programming\C++\CPP Programs\MyTestProgram\MyTestProgram.cpp|12|note:   no known conversion for argument 1 from 'std::map<std::__cxx11::basic_string<char>, int, compare_functor>::key_type {aka std::__cxx11::basic_string<char>}' to 'const T& {aka const std::pair<std::__cxx11::basic_string<char>, int>&}'|
d:\mingw\include\c++\7.3.0\bits\stl_tree.h||In instantiation of 'std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_lower_bound(std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_Link_type, std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_Base_ptr, const _Key&) [with _Key = std::__cxx11::basic_string<char>; _Val = std::pair<const std::__cxx11::basic_string<char>, int>; _KeyOfValue = std::_Select1st<std::pair<const std::__cxx11::basic_string<char>, int> >; |
d:\mingw\include\c++\7.3.0\bits\stl_tree.h|1187|required from 'std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::lower_bound(const key_type&) [with _Key = std::__cxx11::basic_string<char>; _Val = std::pair<const std::__cxx11::basic_string<char>, int>; _KeyOfValue = std::_Select1st<std::pair<const std::__cxx11::basic_string<char>, int> >; _Compare = compare_functor; _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, int> >; std::_Rb_tree<_Key, _Val, _KeyOfVa|
d:\mingw\include\c++\7.3.0\bits\stl_map.h|1234|required from 'std::map<_Key, _Tp, _Compare, _Alloc>::iterator std::map<_Key, _Tp, _Compare, _Alloc>::lower_bound(const key_type&) [with _Key = std::__cxx11::basic_string<char>; _Tp = int; _Compare = compare_functor; _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, int> >; std::map<_Key, _Tp, _Compare, _Alloc>::iterator = std::_Rb_tree_iterator<std::pair<const std::__cxx11::basic_string<char>, int> >; std::map<_Key, _Tp, _Compare, _Alloc>::key_type = std::__cxx11::basic_string<char|
d:\mingw\include\c++\7.3.0\bits\stl_map.h|509|required from 'std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](std::map<_Key, _Tp, _Compare, _Alloc>::key_type&&) [with _Key = std::__cxx11::basic_string<char>; _Tp = int; _Compare = compare_functor; _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, int> >; std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type = int; std::map<_Key, _Tp, _Compare, _Alloc>::key_type = std::__cxx11::basic_string<char>]'|
Program.cpp|22|required from here|
d:\mingw\include\c++\7.3.0\bits\stl_tree.h|1872|error: no match for call to '(compare_functor) (const std::__cxx11::basic_string<char>&, const std::__cxx11::basic_string<char>&)'|
Program.cpp|12|note: candidate: bool compare_functor::operator()(const T&, const T&) const|
Program.cpp|12|note:   no known conversion for argument 1 from 'const std::__cxx11::basic_string<char>' to 'const T& {aka const std::pair<std::__cxx11::basic_string<char>, int>&}'|
||=== Build failed: 2 error(s), 7 warning(s) (0 minute(s), 0 second(s)) ===|

Approach 2: The same logic I implemented with a lambda and I have got almost the same errors:

||=== Build: Debug in MyTestProgram (compiler: GNU GCC Compiler) ===|
d:\mingw\include\c++\7.3.0\bits\stl_map.h||In instantiation of 'std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](std::map<_Key, _Tp, _Compare, _Alloc>::key_type&&) [with _Key = std::__cxx11::basic_string<char>; _Tp = int; _Compare = bool (*)(const std::pair<std::__cxx11::basic_string<char>, int>&, const std::pair<std::__cxx11::basic_string<char>, int>&); _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, int> >; std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type = int; std:|
Program.cpp|37|required from here|
d:\mingw\include\c++\7.3.0\bits\stl_map.h|511|error: invalid initialization of reference of type 'const std::pair<std::__cxx11::basic_string<char>, int>&' from expression of type 'std::map<std::__cxx11::basic_string<char>, int, bool (*)(const std::pair<std::__cxx11::basic_string<char>, int>&, const std::pair<std::__cxx11::basic_string<char>, int>&)>::key_type {aka std::__cxx11::basic_string<char>}'|
d:\mingw\include\c++\7.3.0\bits\stl_tree.h||In instantiation of 'std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_lower_bound(std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_Link_type, std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_Base_ptr, const _Key&) [with _Key = std::__cxx11::basic_string<char>; _Val = std::pair<const std::__cxx11::basic_string<char>, int>; _KeyOfValue = std::_Select1st<std::pair<const std::__cxx11::basic_string<char>, int> >; |
d:\mingw\include\c++\7.3.0\bits\stl_tree.h|1187|required from 'std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::lower_bound(const key_type&) [with _Key = std::__cxx11::basic_string<char>; _Val = std::pair<const std::__cxx11::basic_string<char>, int>; _KeyOfValue = std::_Select1st<std::pair<const std::__cxx11::basic_string<char>, int> >; _Compare = bool (*)(const std::pair<std::__cxx11::basic_string<char>, int>&, const std::pair<std::__cxx11::basic_string<char>, int>&); _Alloc = |
d:\mingw\include\c++\7.3.0\bits\stl_map.h|1234|required from 'std::map<_Key, _Tp, _Compare, _Alloc>::iterator std::map<_Key, _Tp, _Compare, _Alloc>::lower_bound(const key_type&) [with _Key = std::__cxx11::basic_string<char>; _Tp = int; _Compare = bool (*)(const std::pair<std::__cxx11::basic_string<char>, int>&, const std::pair<std::__cxx11::basic_string<char>, int>&); _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, int> >; std::map<_Key, _Tp, _Compare, _Alloc>::iterator = std::_Rb_tree_iterator<std::pair<const std::__cxx11::ba|
d:\mingw\include\c++\7.3.0\bits\stl_map.h|509|required from 'std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](std::map<_Key, _Tp, _Compare, _Alloc>::key_type&&) [with _Key = std::__cxx11::basic_string<char>; _Tp = int; _Compare = bool (*)(const std::pair<std::__cxx11::basic_string<char>, int>&, const std::pair<std::__cxx11::basic_string<char>, int>&); _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, int> >; std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type = int; std::map<_|
Program.cpp|37|required from here|
d:\mingw\include\c++\7.3.0\bits\stl_tree.h|1872|error: invalid initialization of reference of type 'const std::pair<std::__cxx11::basic_string<char>, int>&' from expression of type 'const std::__cxx11::basic_string<char>'|
||=== Build failed: 2 error(s), 7 warning(s) (0 minute(s), 0 second(s)) ===|

I have referred many answers online. But most of them were considering either Key type or Value type while comparing using the functor/ lambda, which was not my case. I would like to compare both Value and Key compared while inserting to the map.

Can anybody explain to me why these implementations fail?

Secondly, what I should have done to get above result while inserting(PS: I would like to still keep string as my key to the map and if it is possible, I do not want any temporary maps to do this result.)?

Here is my code:

#include <iostream>
#include <map>
#include <string>
#include <tuple>

typedef std::pair<std::string, int> T;
typedef bool(*compare_functional_type)(const T&, const T&);

// Way - 1: using functor
struct compare_functor
{
   bool operator()(const T& A ,const T& B)const
   {
      return std::tie(A.second, A.first) < std::tie(B.second, B.first);
      // OR in other-words:
      //return (A.second == B.second) ? A.first < B.first : A.second < B.second;
   };
};
int main()
{
   std::map<std::string, int, compare_functor> Map1;
   Map1["Ram"] = 8;
   Map1["Aam"] = 8;
   Map1["Some"] = 2;
   Map1["He"] = 5;
   Map1["He"] = 6;

   // Way - 2: using lambdas and function pointers
   compare_functional_type Lambda = [](const T& A, const T& B)
   {
      return std::tie(A.second, A.first) < std::tie(B.second, B.first);
      // OR in other-words:
      //return (A.second == B.second) ? A.first < B.first : A.second < B.second;
   };

   std::map<std::string, int, compare_functional_type> Map2(Lambda);
   Map2["Ram"] = 8;
   Map2["Aam"] = 8;
   Map2["Some"] = 2;
   Map2["He"] = 5;
   Map2["He"] = 6;

   return 0;
}

'std::shared_ptr' has not been declared , #include

I know there are a lot of similar questions around, but most of them solve the problem including memory. I had this issue before and that solution seemed to have fixed the problem last time, but not this one.

I am working on a university project with a mate who uses a macbook, i use Windows 10 but usually is not a problem. We are working with Clion and Cmake and we use SFML library.

At this time, the project works very well on her macbook but it is not running on mine. The code is the same, the directories are the same and in the same locations. Last time i had this problem and i solved, as i was saying, including in our ResourceHolder.h file. Now I can't include that file in our Character.h file (Don't know why, it's like they can't find eachother, but the Cmakelist.txt contains all our files). I tried by moving through our files-tree of course, but nothing worked. If i include memory in Character.h the project run until 96% then a lot of undefined reference errors show up.

Can someone help me or explaining me how to solve for once this problem with shared pointers? I'd like to know why i can't include that file (ResourceHolder) in another file of the same project, too.

This is the Cmake file: cmake_minimum_required(VERSION 3.8) project(BlackRose)

cmake_policy(SET CMP0074 OLD)
set(SFML_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/Libraries/SFML)

set(CMAKE_CXX_STANDARD 11)

message("Adding test subdir")
add_subdirectory(test)


set(SOURCE_FILES source/Game.cpp include/Game.h 
include/management/ResourceHolder.h source/ProceduralMap.cpp 
include/ProceduralMap.h
    include/management/ResourceIdentifier.h source/World.cpp include/World.h 
    source/Characters/Character.cpp include/Characters/Character.h
    include/Inventory.h source/Characters/PlayerCharacter.cpp 
    include/Characters/PlayerCharacter.h source/Objects/Weapon.cpp
    include/Objects/Weapon.h source/Objects/Shield.cpp i 
    include/Objects/Shield.h source/Characters/Enemy.cpp 
    include/Characters/Enemy.h
    source/Entity.cpp include/Entity.h source/Objects/Object.cpp 
    include/Objects/Object.h source/Objects/ConsumableObject.cpp
    include/Objects/ConsumableObject.h source/Objects/RangedWeapon.cpp 
    include/Objects/RangedWeapon.h source/Objects/MeleeWeapon.cpp
    include/Objects/MeleeWeapon.h source/Projectile.cpp include/Projectile.h 
    include/Random.h source/Random.cpp
    source/Objects/Tile.cpp include/Objects/Tile.h 
    source/Objects/Healpack.cpp include/Objects/Healpack.h 
    source/textDisplay.cpp include/textDisplay.h)
 add_executable(BlackRose source/main.cpp)


 set(CMAKE_MODULE_PATH ${SFML_ROOT}/sfml_cmake)
 find_package(SFML REQUIRED system window graphics network audio)
 include_directories(${SFML_INCLUDE_DIR})

 message("Add library")
 add_library(core ${SOURCE_FILES})
 target_link_libraries(BlackRose ${SFML_LIBRARIES} core)

 get_directory_property(output INCLUDE_DIRECTORIES)
 message("Include directories:" ${output})

This is the Header:

#ifndef BLACKROSE_CHARACTER_H
#define BLACKROSE_CHARACTER_H


#include <SFML/System.hpp> 
#include "../Inventory.h"
#include "../Objects/Weapon.h"
#include "../Objects/Shield.h"
#include "../Entity.h"
#include <memory>




class Character: public Entity {
public:
 Character();
 //virtual ~Character() = 0;
 virtual void move();
 virtual void fight();
 //basic interaction with the world, it will be associated with a key
 virtual bool interactWithObject(std::shared_ptr <Object> &object);
 virtual void die();
 void update();
 void display();

public:
 int hp;
 int hpMax;
 int attackDamage;

 bool barDisplayed = false;
 sf::RectangleShape bar;
 sf::RectangleShape lifeBar;

protected:
 int resistance;
 int speed;
 sf::Vector2f position;
 Inventory inventory;
 sf::Clock timerTextures;
};


#endif //BLACKROSE_CHARACTER_H

The .cpp file:

#include "../../include/Characters/Character.h"



Character::Character() {
  //all characters are this big
  rect.setSize(sf::Vector2f(32,32));

  //life bar
  bar = sf::RectangleShape(sf::Vector2f(32,5));
  lifeBar = sf::RectangleShape(sf::Vector2f(32,5));
  bar.setOutlineThickness(3);
  bar.setOutlineColor(sf::Color::Black);
  bar.setFillColor(sf::Color::Black);
  lifeBar.setFillColor(sf::Color::Green);
 /*
  bar.setPosition(position.x, position.y-16);
  lifeBar.setPosition(position.x, position.y-16);
*/


 //TODO istanzia un inventory
 }

 bool Character::interactWithObject(std::shared_ptr <Object> &object) {
 return true;
 }

 ...other methods

these are errors show up when I do not include memory:

In file included from C:\Users\Ludovico\CLionProjects\BlackRose\source\Characters\Character.cpp:5:0: c:\users\ludovico\clionprojects\blackrose\include\characters\character.h:26:42: error: 'std::shared_ptr' has not been declared virtual bool interactWithObject(std::shared_ptr &object);

                                      ^

c:\users\ludovico\clionprojects\blackrose\include\characters\character.h:26:53: error: expected ',' or '...' before '<' token virtual bool interactWithObject(std::shared_ptr &object);

                                                 ^

C:\Users\Ludovico\CLionProjects\BlackRose\source\Characters\Character.cpp:37:41: error: 'bool Character::interactWithObject' is not a static data member of 'class Character' bool Character::interactWithObject(std::shared_ptr &object) {

                                     ^

C:\Users\Ludovico\CLionProjects\BlackRose\source\Characters\Character.cpp:37:36: error: 'shared_ptr' is not a member of 'std' bool Character::interactWithObject(std::shared_ptr &object) {

                                ^

C:\Users\Ludovico\CLionProjects\BlackRose\source\Characters\Character.cpp:37:59: error: expected primary-expression before '>' token bool Character::interactWithObject(std::shared_ptr &object) {

                                                       ^

C:\Users\Ludovico\CLionProjects\BlackRose\source\Characters\Character.cpp:37:62: error: 'object' was not declared in this scope bool Character::interactWithObject(std::shared_ptr &object) {

                                                          ^

C:\Users\Ludovico\CLionProjects\BlackRose\source\Characters\Character.cpp:37:70: error: expected ',' or ';' before '{' token bool Character::interactWithObject(std::shared_ptr &object) {

                                                                  ^

CMakeFiles\core.dir\build.make:104: recipe for target 'CMakeFiles/core.dir/source/Characters/Character.cpp.obj' failed mingw32-make.exe[2]: * [CMakeFiles/core.dir/source/Characters/Character.cpp.obj] Error 1 mingw32-make.exe[2]: Waiting for unfinished jobs.... In file included from c:\users\ludovico\clionprojects\blackrose\include\characters\playercharacter.h:9:0, from C:\Users\Ludovico\CLionProjects\BlackRose\source\Characters\PlayerCharacter.cpp:5: c:\users\ludovico\clionprojects\blackrose\include\characters\Character.h:26:42: error: 'std::shared_ptr' has not been declared virtual bool interactWithObject(std::shared_ptr &object); ^ c:\users\ludovico\clionprojects\blackrose\include\characters\Character.h:26:53: error: expected ',' or '...' before '<' token virtual bool interactWithObject(std::shared_ptr &object); ^ mingw32-make.exe[2]: [CMakeFiles/core.dir/source/Characters/PlayerCharacter.cpp.obj] Error 1 mingw32-make.exe[1]: * [CMakeFiles/core.dir/all] Error 2 CMakeFiles\core.dir\build.make:118: recipe for target 'CMakeFiles/core.dir/source/Characters/PlayerCharacter.cpp.obj' failed CMakeFiles\Makefile2:108: recipe for target 'CMakeFiles/core.dir/all' failed mingw32-make.exe: *** [all] Error 2 Makefile:128: recipe for target 'all' failed

Thanks you for the patience and for your help

C++ zenity doesn't work properly

I'm trying to draw a graph with OGDF library using the FMMM algorithm. I want to allow the choice of the input and output gml file. I tried to do this with:

FILE *in;
if (!(in = popen("zenity  --title=\"Select a gml file\" --file- 
    selection","r"))) {
     return 1;
}
char buff[512];
string selectFile = "";
while (fgets(buff, sizeof(buff), in) != NULL) {
    selectFile += buff;
}
pclose(in);

FILE *out;
if (!(out = popen("zenity --file-selection --save --confirm- 
    overwrite","w"))) {
        return 1;
}
selectFile="";
while (fgets(buff, sizeof(buff), in) != NULL) {
    selectFile += buff;
}
pclose(out);

When I run this, it opens the zenity processes but for both shows the following:

enter image description here

Can someone explain where I'm wrong? Thank you

Confusion about happens before relationship in concurrency

Below is an example given in Concurrency in Action , and the author says the assert may fire, but I don't understand why.

#include <atomic>
#include <thread>
#include <assert.h>
std::atomic<bool> x,y;
std::atomic<int> z;
void write_x_then_y()
{
  x.store(true,std::memory_order_relaxed);
  y.store(true,std::memory_order_relaxed);
}
void read_y_then_x()
{
  while(!y.load(std::memory_order_relaxed));
  if(x.load(std::memory_order_relaxed))
  ++z;
}
int main()
{
  x=false;
  y=false;
  z=0;
  std::thread a(write_x_then_y);
  std::thread b(read_y_then_x);
  a.join();
  b.join();
  assert(z.load()!=0);
}

As far as I know, in each single thread, sequenced before also means happens before. So in thread a the store to x happens before y, which means x should be modified before y and the result x.store should be visible before y is modified.

But in this example the author says that the store between x and y could be reordered, why? Does that violate the rule of sequenced before and happens before?

What will happen if two atomic fetch_add execute simultaneously?

As far as I know, atomic operations of atomic type in cpp11 are guaranteed to be aomtic. However, suppose in multi-core system, if two threads do following operation simultaneously, will the result be 1?(suppose initially atomic<int> val=0;)

val.fetch_add(1,std::memory_order_relaxed);

Code to find next binary string in the lexicographic order as an output with the same number of ones?

Lets say Input is - 1011 (11), then the output should be :- 1101 (13)...

Other example could be :- input - 0110 (6) and output - 1001 (9)...

C++ why raw pointer won't increase reference count of shared_ptr?

the shared_ptr use reference count to determine when to destroy the object. And pls look at this code:

int main() {
    std::shared_ptr<int> pt = std::make_shared<int>(3);
    int *pt2 = pt.get();
    cout << "reference count " << pt.use_count() << endl;
    pt = 0;
    cout << *pt2;

};

after I set pt to 0, the reference count should become 0, and the object should be destroyed. But I can still use pt2 to access it. In my case, the result is correct, but I guess it's just luck. So does it mean that the reference count mechanism still can not make it 100% safe if the programmer want to do some stupid thing?

samedi 28 juillet 2018

Deleting a linked list node using two pointers

I know there are other approaches to delete nodes, but I couldn't figure out why mine is wrong.
I want to know at what step I made the mistake. Thank you in advance

Given a linked list called "items" that contains 5 nodes with the following data: 1 2 3 4

Goal Delete the last number ( 4 )

Code

        nodeType *p=items,*q;
        while( p->link!=nullptr)
        {  
           p = p->link;   
           cout << p->data << " ";  
        }
          // Output of the loop: 2 3 4  ("1" isn't here b/c "p" is overwritten)
          // p == address of the third node's link
          // p->data == 4 

        q = p->link; // q == the address of the node that contains 4
        p = nullptr; // unlinking the third node from the fourth node.
        delete q;   // deleting the last node ( that contains 4)

        cout << items->link->link->link->data; 
        // Output: 4 

Question
HOW COME NUMBER 4 IS STILL HERE ?!

Keep user data even after the program is exited

So I'm trying to create a simple banking program just to test my skills, but I was wondering how do I make it so that the user's data is kept. My plan is to create a .h file that handles all the balance, deposit, and withdraw stuff. But as far as I know once the user exits the program, it will delete the data and it will be gone. How do I make it so that the data stays no matter what. So like in this session the user has a balance of $1000 and makes a withdrawal of $100. Then exits. Next time they open the program that balance should be $900. How do I make that happen. BTW doing this all in c++

do sequentially-consistent atomic loads (load-load pair) form an inter-thread synchronisation point?

I am trying to understand what does sequentially-consistent ordering mean for loads. Consider this artificial example:

#include <atomic>
#include <thread>
#include <cassert>

static std::atomic<bool> preStop {false};
static std::atomic<bool> stop {false};
static std::atomic<int> counter{0};

void waiter() {
    preStop.store(true, std::memory_order_relaxed);
    while (counter.load() > 0);
    stop.store(true);
}

void performer() {
    while (true) {
        counter.fetch_add(1);
        if (stop.load()) {
            assert(preStop.load());
            return;
        }
        counter.fetch_sub(1);
        std::this_thread::yield();
    }
}

int main() {
    std::thread performerThread(performer);
    std::thread waiterThread(waiter);
    waiterThread.join();
    performerThread.join();
}

Can assert fail? Or does counter.fetch_add() synchronise with counter.load()?

It is my understanding that had operations on counter have std::memory_order_relaxed or std::memory_order_acq_rel, the load-load pair would not create a synchronisation point. Does std::memory_order_seq_cst makes any difference for load-load pairs?

Why is my while loop not executing? [duplicate]

So this a function I wrote. It basically just transfers some data from one array to another when a condition is met. My issue is the while loop won't activate. I already confirmed "sizeof(arr1)/sizeof(arr1[0])" evaluates to 8 in my case, so my loop should run. It works if I actually put in an 8 instead of the code. I also tried static casting it to an int but that didn't work. Any insight would be appreciated!

void addWinners(person arr1[], person arr2[]) {

int k{0}, j{0};

while (k < static_cast<int>((sizeof(arr1)/sizeof(arr1[0])))) {

    if (arr1[k].wins()) {
        arr2[j] = arr1[k];
        j++;
    }

    k++;
}


}

explicit instantiation: why doesn't work

Here is a simple code:

#include <iostream>
#include <array>

using namespace std;

class cl {
public:
  template <int N, typename ExtractedType>
            bool ExtractDataFromArray(std::array<uint8_t, N> &ExtractFrom,
                                      uint8_t StartBit, uint8_t BitLen, ExtractedType
                                      &out);
};

template <int N, typename ExtractedType>
bool cl::ExtractDataFromArray(std::array<uint8_t, 8> &ExtractFrom,
                          uint8_t StartBit, uint8_t BitLen, ExtractedType
                          &out) { return false;}

template
bool cl::ExtractDataFromArray<2, int>(std::array<uint8_t, 8> &ExtractFrom,
                          uint8_t StartBit, uint8_t BitLen, int &out);

Why it refuses to instantiate ExtractDataFromArray for pair <8, int>?

How to redefine a pair in c++ [duplicate]

This question already has an answer here:

I am working a lot with pairs in c++ these days so I want to do next:

Instead of:

pair<int, int> p;
cin >> p.first >> p.second;

I want to write:

pair<int, int> p;
cin >> p.x >> p.y;

I tried #define first x and similar things but it doesn't work. How to redefine this?

MSVC list initialization ICE when used with structs?

This piece of code compiles well on gcc 8.1 and clang 6.0, but gives ICE on MSVC (both 2017 and 2018 pre-release):

#include <vector>
#include <string>

struct Data {
    unsigned char data;
};

struct A {
    std::string x;
    Data y{255};
};

void f(std::vector<A> arg) {
}

int main() {
    f(std::vector<A>Test);
}

Clearly, I've run into yet another MSVC compiler bug.

But to be really sure: Does the above code conform to standard C++, or have I made an error as well?

Alias for std::dynamic_pointer_cast

I'm trying to create an alias for std::dynamic_pointer_cast but can't write something that compiles.

This is the way I'm trying:

template <typename T1, typename T2>
using dcast = std::dynamic_pointer_cast<T1, T2>;

What is wrong with it?

Member initializer list. Order of arguments evaluation

Example of a code with member initializer list.

#include <memory>

struct Throwable
{
    Throwable()
    {
        throw "Exception!";
    }
};

struct A
{
    A() : t(Throwable()), i(new int()) {}

    Throwable t;
    std::unique_ptr<int> i;
};

Can I have got a memory leak if there could be the next evaluation order.

  1. new int()
  2. Throwable()
  3. t()
  4. i()

What is the order in the Standard? We have some rules.

https://en.cppreference.com/w/cpp/language/initializer_list

3) Then, non-static data members are initialized in order of declaration in the class definition. So t will be constructed before i.

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

9) Every value computation and side effect of the first (left) argument of the built-in comma operator , is sequenced before every value computation and side effect of the second (right) argument.

But member initializer list does not use all comma rules because of the previous reference. And it is not the comma operator (https://en.cppreference.com/w/cpp/language/operator_other#Built-in_comma_operator).

10) In list-initialization, every value computation and side effect of a given initializer clause is sequenced before every value computation and side effect associated with any initializer clause that follows it in the brace-enclosed comma-separated list of initalizers.

And https://en.cppreference.com/w/cpp/language/list_initialization

List initialization is performed in the following situations:

5) in a member initializer list of a constructor if braced-init-list is used

I have another case.

Could you provide the rule which defines the order of arguments evaluation in a member initializer list?

vendredi 27 juillet 2018

Assignment to an array of std::unique_ptr

2 ways to declare an array of std::unique_ptr:

struct MyStruct
{
    int x = 0;
}

std::unique_ptr<MyStruct[]> Arr1[10];
std::array<std::unique_ptr<MyStruct>, 10> Arr2;

// Arr1[0] = ?
// Arr2[0] = ?

What is the syntax to assign an object to such an array? (I tried several ways, using std::make_unique ..it didn't work. I tried an addition of std::move ..it didn't work). It seems I miss something. My reference.

Any of the two has benefits over the other?

How can I make my makefile also look for the c++11 directory?

I compiled my program and when I upload it to be marked with fitch fork I get a few errors. The program compiles and runs when I run it outside fitch fork, I think the main problem is that my make file is not calling c++11 libraries.

Error Message:

make_clean 2

rm: cannot remove '*.o': No such file or directory rm: cannot remove 'main': No such file or directory make: *** [makefile:14: clean] Error 1

make 2

combiner.cpp: In member function 'void combiner::combineFragments(std::__cxx11::string, std::__cxx11::string, std::__cxx11::string)': combiner.cpp:75:16: error: no matching function for call to 'std::basic_ifstream::open(std::__cxx11::string&)' File1.open(f1); ^ In file included from combiner.cpp:5:0: /usr/lib/gcc/x86_64-pc-linux-gnu/5.4.0/include/g++-v5/fstream:595:7: note: candidate: void std::basic_ifstream<_CharT, _Traits>::open(const char*, std::ios_base::openmode) [with _CharT = char; _Traits = std::char_traits; std::ios_base::openmode = std::_Ios_Openmode] open(const char* __s, ios_base::openmode __mode = ios_base::in) ^ /usr/lib/gcc/x86_64-pc-linux-gnu/5.4.0/include/g++-v5/fstream:595:7: note: no known conversion for argument 1 from 'std::__cxx11::string {aka std::__cxx11::basic_string}' to 'const char*' combiner.cpp:76:16: error: no matching function for call to 'std::basic_ifstream::open(std::__cxx11::string&)' File2.open(f2); ^ In file included from combiner.cpp:5:0: /usr/lib/gcc/x86_64-pc-linux-gnu/5.4.0/include/g++-v5/fstream:595:7: note: candidate: void std::basic_ifstream<_CharT, _Traits>::open(const char*, std::ios_base::openmode) [with _CharT = char; _Traits = std::char_traits; std::ios_base::openmode = std::_Ios_Openmode] open(const char* __s, ios_base::openmode __mode = ios_base::in) ^ /usr/lib/gcc/x86_64-pc-linux-gnu/5.4.0/include/g++-v5/fstream:595:7: note: no known conversion for argument 1 from 'std::__cxx11::string {aka std::__cxx11::basic_string}' to 'const char*' combiner.cpp:77:16: error: no matching function for call to 'std::basic_ifstream::open(std::__cxx11::string&)' File3.open(f3); ^ In file included from combiner.cpp:5:0: /usr/lib/gcc/x86_64-pc-linux-gnu/5.4.0/include/g++-v5/fstream:595:7: note: candidate: void std::basic_ifstream<_CharT, _Traits>::open(const char*, std::ios_base::openmode) [with _CharT = char; _Traits = std::char_traits; std::ios_base::openmode = std::_Ios_Openmode] open(const char* __s, ios_base::openmode __mode = ios_base::in) ^ /usr/lib/gcc/x86_64-pc-linux-gnu/5.4.0/include/g++-v5/fstream:595:7: note: no known conversion for argument 1 from 'std::__cxx11::string {aka std::__cxx11::basic_string}' to 'const char*' combiner.cpp:84:20: error: 'stoi' was not declared in this scope num = stoi(stemp); ^ combiner.cpp:103:20: error: 'stoi' was not declared in this scope num = stoi(stemp); ^ combiner.cpp:121:20: error: 'stoi' was not declared in this scope num = stoi(stemp); ^ make: *** [makefile:5: combiner.o] Error 1

make_run1 2

make: ./main: Command not found make: *** [makefile:11: run] Error 127

Code:

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <string>
#include <fstream>

using namespace std;

#include "combiner.h"

void combiner::setRows(int a)
{
    rows = a;
}

void combiner::setCols(int a)
{
    cols = a;
}

int combiner::getRows()
{
    return rows;
}

int combiner::getCols()
{
    return cols;
}

void combiner::initialiseMap()
{
    int rows = getRows();
    int cols = getCols();

    colourMap = new int * [rows];
    for(int i = 0; i < rows; i++)
    {
        colourMap[i] = new int[cols];
    }

    for(int j = 0; j < rows; j++)
    {
        for(int l = 0; l < cols; l++)
        {
            colourMap[j][l] = -1;
        }
    }
}

void combiner::displayMap()
{
    for(int j = 0; j < rows; j++)
    {
        for(int l = 0; l < cols; l++)
        {
            cout << colourMap[j][l]; 

            if(l < cols-1)
            {
                cout << ",";
            }
        }
        cout << endl;
    }
}

void combiner::combineFragments(string f1, string f2, string f3)
{       
    int num, pos, lenght, cols = getCols()-1;
    string temp, stemp;

    ifstream File1, File2, File3;
    File1.open(f1);
    File2.open(f2);
    File3.open(f3);

    while(File1 >> temp)
    {
        pos = temp.find(",");
        stemp = temp.substr(0, pos);
        temp = temp.substr(pos+1, temp.length()-pos);
        num = stoi(stemp);

        colourMap[0][0] = num;

        for(int i = 0; i < cols; i++)
        {
            pos = temp.find(",");
            stemp = temp.substr(0, pos);
            temp = temp.substr(pos+1, temp.length()-num);
            num = stoi(stemp);
            colourMap[i+1][0] = num;
        }
    }

    while(File2 >> temp)
    {
        pos = temp.find(",");
        stemp = temp.substr(0, pos);
        temp = temp.substr(pos+1, temp.length()-pos);
        num = stoi(stemp);
        colourMap[0][1] = num;

        for(int i = 0; i < cols; i++)
        {
            pos = temp.find(",");
            stemp = temp.substr(0, pos);
            temp = temp.substr(pos+1, temp.length()-num);
            num = stoi(stemp);
            colourMap[i+1][1] = num;
        }
    }

    while(File3 >> temp)
    {
        pos = temp.find(",");
        stemp = temp.substr(0, pos);
        temp = temp.substr(pos+1, temp.length()-pos);
        num = stoi(stemp);
        colourMap[0][2] = num;

        for(int i = 0; i < cols; i++)
        {
            pos = temp.find(",");
            stemp = temp.substr(0, pos);
            temp = temp.substr(pos+1, temp.length()-num);
            num = stoi(stemp);
            colourMap[i+1][2] = num;
        }
    }

    File1.close();
    File2.close();
    File3.close();
}

void combiner::smoothColours()
{
    int rows, cols, sum = 0, avg;

    rows = getRows();
    cols = getCols();
    avg = rows*cols;

    for(int j = 0; j < rows; j++)
    {
        for(int l = 0; l < cols; l++)
        {
            sum = colourMap[j][l] + sum; 
        }
    }
    avg = sum/(rows*cols);

    for(int j = 0; j < rows; j++)
    {
        for(int l = 0; l < cols; l++)
        {
            colourMap[j][l] = avg;
        }
    }
}

makefile:

combiner: combiner main.cpp
    g++ -c main.cpp combiner.cpp
    g++ -std=c++11 -o main main.o combiner.o

main: main.cpp combiner.o
    g++ -o main.a main.o

run:
    ./main

clean: 
    rm *.o main

In the following example, from where does the pointer p gets the information?

vector& vector::operator = (const vector& a)
    //make this vector a copy of a
{
    double* p = new double [ a.sz ];   // allocate new space
    copy(a.elem, a.elem+a.sz, elem);     // copy elements
    delete[] elem;                     // deallocate old space
    elem = p;                         // now we can reset elem
    sz = a.sz;
    return *this;                     // return a self-reference
}

I thought that the third argument of std::copy() should be the pointer p, but the book (Programming principles and practice using C++ - 2nd edition) says:

"When implementing the assignment, you could consider simplifying the code by freeing the memory for the old elements before creating the copy, but it is usually a very good idea not to throw away information before you know that you can replace it. Also, if you did that, strange things would happen if you assigned a vector to itself" - Page 635 and 636.

So, the pointer elem must be third argument of std::copy() to not let the pointer be invalid for a moment. I think... But from where does p gets the information to be put in the array it points to, to be able to do: elem = p ?

installation of Cygwin

I am facing some errors after I installed Cygwin software. I was running a hello world program with proper syntax but it throw some errors

C:\Users\dveer\Desktop>gcc -o hello hello.cpp
/cygdrive/c/Users/dveer/AppData/Local/Temp/ccqjKRym.o:hello.cpp:(.text+0x1c): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)'
/cygdrive/c/Users/dveer/AppData/Local/Temp/ccqjKRym.o:hello.cpp:(.text+0x1c): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)'
/cygdrive/c/Users/dveer/AppData/Local/Temp/ccqjKRym.o:hello.cpp:(.text+0x50): undefined reference to `std::ios_base::Init::Init()'
/cygdrive/c/Users/dveer/AppData/Local/Temp/ccqjKRym.o:hello.cpp:(.text+0x50): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `std::ios_base::Init::Init()'
/cygdrive/c/Users/dveer/AppData/Local/Temp/ccqjKRym.o:hello.cpp:(.rdata$.refptr._ZNSt8ios_base4InitD1Ev[.refptr._ZNSt8ios_base4InitD1Ev]+0x0): undefined reference to `std::ios_base::Init::~Init()'
/cygdrive/c/Users/dveer/AppData/Local/Temp/ccqjKRym.o:hello.cpp:(.rdata$.refptr._ZSt4cout[.refptr._ZSt4cout]+0x0): undefined reference to `std::cout'
collect2: error: ld returned 1 exit status

Prevent simultaneous function run

ALL,

Here is a pseudo-code of what I'm looking for:

class A : public Base
{
public:
    virtual int func();
    virtual int other_func();
};

class B : public Base
{
public:
    virtual int func();
    virtual int other_func();
};

class MainFrame
{
public:
    MainFrame();
    Base *CreateObject();
    int StartThread();
    int SomeOtherFunc();
private:
    Base *m_base;
};

MainFrame::MainFrame()
{
    m_base = NULL;
}

Base *MainFrame::CreateObject()
{
    if( <condition1> )
        m_base = new A();
    else
        m_base = new B();
}

int MainFrame::StartThread()
{
    int result;
    while( !TestDestroy() )
    {
        result = m_base->func();
        Sleep( 5000 );
    }
}

int MainFrame::SomeOtherFunc()
{
    m_base->other_func();
}

So in a nutshell: I have 2 classes A and B derived from the same Base class. They both have 2 functions redefined from the Base (a lot more actually, but that's irrelevant). Each of those classes is located in its own DLL.

I also have a main GUI application that calls a method of either A or B by some conditions. It is also spawn a thread at some point of time. In the thread the program calls a function of class A/B.

Now what I'd like to do is to prevent an execution of other_func() when the func() is executing.

I probably should use mutex for that but now the question is - how do I design it? Should I instantiate mutex inside the function itself or on the call inside the MainFrame method? And does the mutex have to be a global variable in this case? Can it be a member of the Base class?

Again, func() call which happens from the secondary thread, should stop the call to any other method of Base until it finishes.

TIA!

This is with C++11/MSVC 2010/gcc5.4.