samedi 31 octobre 2015

Elegantly stop the thread for blocking or non-blocking when accept or receive using asio and C++11

I am using asio for tcp server and I plan to use C++11 std for thread as well. My final goal is to have this application on Linux but I am testing it on Windows first using Visual Studio 2015.

First I am using blocking so I found there were discussion on how to stop a thread waiting on accept. There were pre-C++11 solutions such as pipe, and select. Is there a better way to do this now with C++11 and asio?

Second way is to use asynchronous, but I prefer to use the asio header only so what is the complete solution using std::bind? I couldn't find the std equivalent of this bytes_transferred. The compile complained that the asio::placeholder doesn't have this member.

    asio::async_write(socket_, asio::buffer(message_),
        std::bind(&tcp_connection::handle_write, shared_from_this(),
            std::placeholders::_1,
            asio::placeholders::bytes_transferred// complain here
            ));

The third way is, to set a timeout here. But it doesn't stop my accept. Plus, the answer was in 2012. I hope there is new was to solve this by now.

Which classic thread Synch issue is this?

First of all, This is for a school project, so I don't expect actual code. I'm not too concerned with that. However, I'm having trouble identifying which scenario this is. The project is as follows:

Create three functions: pedestrian(), carWest(), CarEast().Your program should read the input file, and launch a thread per each traffic participant the appropriate time. Each thread should execute corresponding function. Each function should contain three sections: zone entrance, zone crossing, zone exit. Use mutexes and condition variables to ensure that the traffic crosses the construction zone according to the ODOT rules. After the entrance and exit the thread should announce (print) its action. Use sleep_for()function to implement crossing the zone. The amount of time that each participant remains in the zone corresponds to his speed.

ODOT RULES:

 neither car nor pedestrians should wait if the intersection is empty;  cars cannot go in the opposite directions simultaneously on the one-lane section;  a pedestrian cannot cross the street while there is a car in the one-lane section, but multiple pedestrians can cross the street at the same time;  a car may enter the one lane section if there is a car there going in the same direction, however, a car is not allowed to pass another car;  a car does not wait for more than two cars going in the opposite direction;  a pedestrian has to yield to cars BUT a pedestrian should not wait for more than two cars (in either direction).

SAMPLE COMMAND:

0 E1 10 - corresponds to: int arrival_time >> string eastCar#1 >> int speed

So, because of the wording, I'm leaning towards a single producer-many consumer solution: http://ift.tt/1OCS2b6

since the project states the main thread should launch the control thread at the appropriate time.
Does this sound correct? I can also see it being a dining-philosopher problem, here: http://ift.tt/1nL2L2K

or even as the reader-writer problem here: http://ift.tt/1VrKxbk

Thanks for setting me straight

-cos-

OpenCV, findContours - Why do we need a

This is my question. When I have a variable where the contour points are stored:

<vector<vector<Point>> contours;

There are points/coordinates stored in:

contours[0][0].x; contours[0][0].y;
contours[0][1].x; contours[0][1].y;
...
contours[0][n].x; contours[0][n].y;

But no points/coordinates are stored in:

contours[1][0].x; contours[1][0].y;
contours[1][1].x; contours[1][1].y;
...
contours[1][n].x; contours[1][n].y;

or

contours[n][0].x; contours[n][0].y;
contours[n][1].x; contours[n][1].y;
...
contours[n][n].x; contours[n][n].y;

So why do we need a vector of vector of points, instead of a vector of points? A vector of points would be sufficient or not? But openCV wants a vector of vector of points.

Is it possible to have defined both explicit and implicit templated conversion operators?

Question is quite simple, not much to explain.

#include <iostream>

class test
{
private:
    int a, b;
public:
    test(int x, int y)
        : a(x), b(y)
    {}

    template<class T>
    explicit operator T()
    {
        return a + b;
    }

    template<class T>
    operator T()
    {
        return a + b;
    }
};

int main()
{
    test obj(1, 2);

    int a = obj; //implicit conversion

    int b = static_cast<int>(obj); //explicit conversion

    std::cin.get();
}

clang-format noop .clang-format file

I would like to start using clang-format in a extremely big existing code base. Before I commit to any of the clang-format options I would like to make sure that they work well and setting all the right rules at once could be extremely overwhelming.

I am looking on how to make clang-format to do nothing - or noop (no operation) .clang-format from which I could start modifying it to enable rules one by one.

Function overloading with different return types

I know we are not allowed to overload functions based on return type only. Suppose I have two functions double convert(string num) and int convert(string num) Consider the following sample code :

double convert(string num){
    stringstream ss;
    double d_num;
    ss<<num;
    ss>>d_num;
    return d_num;
}

int convert(string num){
    int i_num;
    /*.....
   same as previous
   .....
   */
   return i_num;
}

And in the main() :

int main(){
    string st="09122321";
    double d1=convert(st);
    int i1=convert(st);

}

Although I overloaded the function differring only in return type but as I am assigning them to data types based on their return type wasn't I supposed to get the converted string num in double d1 and int i1 ?

Now I get the error similar to:

error: new declaration 'int convert(std::string)'| error: ambiguates old declaration 'double convert(std::string)'|

How will I make the convert() work if I want it to have it different return types by overloading the function ?

Write a program that prompts the user for a collection of integers

Write a program that prompts the user for a collection of integers and displays the product of those integers. Your program should repeatedly prompt for, read data, ignore any negative numbers and terminate when a zero value is read.

here's what i did so far , Please help me to finish the rest of the code

#include <iostream>

using namespace std;

int main() {
    int Num;
    double product = 0;
    int integerNumber;
    int countNumber = 0;
    cout << "Please enter the number of student = ";
    cin >> Num;
    while (Num>countNumber)
    {
        cout << "Please enter the integer = ";
        cin >> integerNumber;
        product = product + integerNumber;
        countNumber = countNumber + 1;
    }
    cout << "The avarage Grade of all students is = " << product << endl;

    system("pause");
    return 0;
}

forward_list::remove throwing compilation error

I have the following code:

typedef std::forward_list<RdidSettings> RdidList;
RdidList m_rdids;

//ctor for RdidSettings 
RdidSettings(_In_ const GUID& rdid, _In_ bool isDr) throw() :


//Add to rdidlist method 
RdidSettings& AddRdid(  _In_ const GUID& rdid,  _In_ bool isDr  ) 
{   
    m_rdids.emplace_front(rdid, isDr);  return m_rdids.front(); 
}


//method for rdid list method 
void RemoveRdid( _In_  RdidSettings& rdidData) 
{   
    m_rdids.remove(rdidData); <<-- whats wrong with this remove ? 
}

The moment I introduce the remove method I start getting compiler error :

forward_list(1281) : error C2678: binary '==' : no operator found which takes a left-hand operand of type RdidSettings' (or there is no acceptable conversion) could be 'bool std::operator ==(const std::error_condition &,const std::error_code &) throw()'

'bool std::operator ==(const std::error_condition &,const std::error_code &) throw()' 6> \sdk\inc\ucrt\stl120\system_error(406): or 'bool std::operator ==(const std::error_code &,const std::error_condition &) throw()' 6> \sdk\inc\ucrt\exception(333): or
'bool std::operator ==(const std::exception_ptr &,std::nullptr_t)' 6> \sdk\inc\ucrt\exception(328): or 'bool std::operator ==(std::nullptr_t,const std::exception_ptr &)' 6> \sdk\inc\ucrt\exception(323): or 'bool std::operator ==(const std::exception_ptr &,const std::exception_ptr &)' 6> while trying to match the argument list '(RdidSettings, const RdidSettings)' 6> \sdk\inc\ucrt\stl120\forward_list(1276) : while compiling class template member function 'void std::forward_list>::remove(const _Ty &)' 6> with 6> [ 6> _Ty=RdidSettings 6> ] 6> hostsettings.cpp(65) : see reference to function template instantiation 'void std::forward_list>::remove(const _Ty &)' being compiled 6> with 6> [ 6> _Ty=RdidSettings 6> ] 6> \hostsettings.h(181) : see reference to class template instantiation 'std::forward_list>' being compiled 6> with 6> [ 6> _Ty=RdidSettings

Virtual destructor missing for base class in polymorphism = Ressource leak?

We know that it is needed to specify the destructor of a base class as virtual if you intend to use it polymorphically, otherwise you might have a ressource leak in your program, since only the base class destructor will be called and not the derived object destructor.

We also know that constructors / destructors are purely initialization / uninitialization constructs, and operator new / operator delete handle the allocation / unallocation of memory.

In that case, why exactly does the lack of destructor-calling incur a leak, in the case where my C++ class contains only primitive data members? Would it be more accurate to say that the operator delete cannot unallocate the memory, and that is what creates a resource leak?

How to access elements of array and vector repeatedly in c++?

I have a vector of int V'

vector<int> V={2,4,5,6,7};

I want to iterate through vector such that if index is greater than size of vector it should return again some element in vector for example V.size() is 5 if I enter V[6] I need result to return 4,if I enter v[5] it should return 2..... can I also do it with arrays?? Thanks in advance..

discrete_distrubution of struct

I had a vector of real values:

vector<double> values;

and a discrete_distribution:

discrete_distribution<size_t> dis(values.begin(), values.end());

But now I need that the vector of double values becomes a vector of structures:

struct Data
{
   double value;
   int index;
};

vector<Data> values;

How can I build the corresponding discrete_distribution without making a copy of the values into a separated vector?

Why does C++ move semantics leave the source constructed?

In C++11, "move semantics" was introduced, implemented via the two special members: move constructor and move assignment. Both of these operations leave the moved-from object constructed.

Wouldn't it have been better to leave the source in a destructed state? Isn't the only thing you can do with a moved-from object is destruct it anyway?

Variadic templates give errors on more than one parameter

I am trying out the code from http://ift.tt/1PMRizL:

#include <tuple>
#include <initializer_list>
#include <iostream>

template<typename Fun, typename...Ts>
void sequential_foreach(Fun f, const Ts&... args) {
  (void) std::initializer_list<int>{
    [&](const auto& arg){f(arg); return 0;}(args)...
  };
}

template<typename...Ts>
void print_all(std::ostream& stream, const Ts&... args) {
  sequential_foreach([&](const auto& arg){stream << arg;}, args...);
}

int main()
{
  std::string s1("string1");
  std::string s2("string2");
  print_all(std::cout, s1, s2);

  return 0;
}

But I am getting the following errors: (when I pass more than one parameter to print_all)

main.cpp: In instantiation of ‘void sequential_foreach(Fun, const Ts& ...) [with Fun = print_all(std::ostream&, const Ts& ...) [with Ts = {std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> >}; std::ostream = std::basic_ostream<char>]::<lambda(const auto:2&)>; Ts = {std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> >}]’:
main.cpp:14:67:   required from ‘void print_all(std::ostream&, const Ts& ...) [with Ts = {std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> >}; std::ostream = std::basic_ostream<char>]’
main.cpp:21:30:   required from here
main.cpp:8:5: error: uninitialized const member ‘sequential_foreach(Fun, const Ts& ...) [with Fun = print_all(std::ostream&, const Ts& ...) [with Ts = {std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> >}; std::ostream = std::basic_ostream<char>]::<lambda(const auto:2&)>; Ts = {std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> >}]::<lambda(const auto:1&)>::<f capture>’
     [&](const auto& arg){f(arg); return 0;}(args)...
     ^

What am I doing wrong? ideone link: http://ift.tt/1jZLoiI

Checking whether a class template has been instantiated?

Is there an easy way to see whether a class has been instantiated in a translation unit? An exercise from C++ Primer asks for each labelled statement, whether an instantiation happens:

template <typename T> class Stack { };
void f1(Stack<char>); // (a)
class Exercise {
    Stack<double> &rsd; // (b)
    Stack<int> si; // (c)
};
int main() {
    Stack<char> *sc; // (d)
    f1(*sc); // (e)
    int iObj = sizeof(Stack< string >); // (f)
}

I'm not sure how I could actually check my answers for these. I thought maybe I could use explicit instantiations for each class type (e.g. extern template class Stack<char>) and then never have a corresponding explicit instantiation definition in the program. That way if something was instantiated, if the definition didn't later appear then the linker would kick up an error.

However the compiler/linker doesn't always recognise such an error:

template <typename T> class A{ };
extern template class A<int>;
int main(){
    A<int> a; 
}

This compiles fine on gcc 4.9.2. However if this was the only object file in my program is should be an error as far as I can tell from [14.7.2][11] of N3337:

If an entity is the subject of both an explicit instantiation declaration and an explicit instantiation definition in the same translation unit, the definition shall follow the declaration. An entity that is the subject of an explicit instantiation declaration and that is also used in a way that would otherwise cause an implicit instantiation (14.7.1) in the translation unit shall be the subject of an explicit instantiation definition somewhere in the program; otherwise the program is ill-formed, no diagnostic required.

(I'm guessing the "no diagnostic required" is why this doesn't kick up an error?). Alternatively is it the case that instantiations happen whenever an incomplete class type isn't viable for an expression - so that I could check by removing the definition of Stack?

template <typename T> class Stack;

So that each incomplete type error corresponds to a place where an instantiation would have occured?

Remove whitespace from string excluding parts between pairs of " and ' C++

So essentially what I want to do is erase all the whitespace from an std::string object, however excluding parts within speech marks and quote marks (so basically strings), eg:

Hello, World! I am a string

Would result in:

Hello,World!Iamastring

However things within speech marks/quote marks would be ignored:

"Hello, World!" I am a string

Would result in:

"Hello, World!"Iamastring

Or:

Hello,' World! I' am a string

Would be:

Hello,' World! I'amastring

Is there a simple routine to perform this to a string? It doesn't have to be the most efficient one possible, as it will only be run once or twice every time the program runs.

Seek item within vector

I have a vector of real values, sorted by increasing order.

These values can be within the range [0, 1]. Then I pick a value x within this range and I need to find which is the index of the smaller value greater or equal to x.

I can solve this problem by iterating over the whole array:

vector<double> values;
double x;

for (auto val : values)
{
    if (x <= values)
    {
        // found
        break;
    }
}

Is there a faster way to get the same result? I was thinking about a binary search, but how to implement it?

Getting Started with Boost (Using lambda namespace)

I recently installed boost and have been trying to understand how everything works. The boost.org page gives

#include <boost/lambda/lambda.hpp>
#include <iostream>
#include <iterator>
#include <algorithm>

int main()
{
    using namespace boost::lambda;
    typedef std::istream_iterator<int> in;
    std::for_each( in(std::cin), in(), std::cout << (_1 * 3) << " " );
}

as a first code which is supposed to use the lambda namespace to multiply the input stream by 3. I'm really not used to this notation (I've always put using namespace std in my code and didn't worry about the intricacies going on in the background), and although I partly understand this code, it would be great if someone can break it up line to line and provide an explanation. For example, how does the compiler know that _1 is taken from the lambda namespace, and why do we have to specify std:: before cin and cout. Can we do without having to prefix std:: each time we use a boost library?

how to optimize this code and getting access to it or is there another way to write it? [on hold]

i want to implement a vector that has a type of matrices and this matrices has a type of a list of class(class name:classe) so i create a class schedule and a type of list of class like this:

/*
 * schedule.h
 *
 *  Created on: 29 Oct 2015
 *      Author: Latitude
 */

#ifndef SCHEDULE_H_
#define SCHEDULE_H_
#include <string>
#include "Classe.h"
#include <list>

typedef std::list<Classe*> ClasseListeType;


class schedule {
public:
    schedule;
    virtual ~schedule();

    ClasseListeType GetMat(int i,int j) { return  *Mat[i][j]; }


private:
    std::string _lannee;
    int  nbrofdays;
    int  nbrofslots;

     ClasseListeType*  Mat[nbrofdays][nbrofslots] ;

    //std::list<Classe*> _listedsclasse;
    //Mat[nbrdsjours][nbrdsperiods];
};

#endif /* SCHEDULE_H_ */

and i fill the Schedule list by this code

  c2(2,2,&p1,&g1,&m4),
       c3(3,3,&p1,&g1,&m5),
       c4(4,1,&p2,&g1,&m2),
       c5(5,2,&p2,&g1,&m6),
       c12(12,2,&p4,&g1,&m8),
       c13(13,1,&p4,&g1,&m7),
       c6(6,1,&p1,&g2,&m1),
       c7(7,2,&p1,&g2,&m4),
       c8(8,3,&p1,&g2,&m5),
       c9(9,1,&p2,&g2,&m2),
       c11(11,2,&p2,&g2,&m6),
       c14(14,1,&p4,&g2,&m7);

    Schedule lp;


       lp.GetMat(0,0).push_back(&c1);
       lp.GetMat(0,0).push_back(&c9);
       lp.GetMat(0,1).push_back(&c3);
       lp.GetMat(0,2).push_back(&c4);
       lp.GetMat(0,3).push_back(&c7);
       lp.GetMat(0,1).push_back(&c6);
       lp.GetMat(0,4).push_back(&c8);
       lp.GetMat(0,2).push_back(&c2);
       lp.GetMat(0,4).push_back(&c11);
       lp.GetMat(0,3).push_back(&c13);


         vector<Schedule*> 

So i'm not so sure for this code Hide Copy Code because it seems so complicated and i have to manage this code with genetic algorithm and vector<Schedule*> will be the chromosome vector<Schedule*> will be the chromosome`

how do i access this lists in easy way ??

so is there an eny erreur on my code or i didt in a wrong way plz help me to optimize it; tanks i advenced

Data returned as json with websocketpp but as Blob with messagepack

This is weird. I have modified a websocket-server example using websocketpp written in C++. It parses incoming stringified json-data from a client using nlohmann/json. Data is returned to the client in json-format, parsed and updating a hmtl div. All fine so far.

Then I wanted to compress json data from the client using messagepack, parse and return it in the same json-format but now I get an error since the data is now a [object Blob]. I put wireshark on but they capture exactly the same information in both scenarios.

Both are returned as

${"cnt":4,"data":"test","type":"msg"}

and have length 38.

In chrome I get the error

Uncaught SyntaxError: Unexpected token o

Here is the client before messagepack is added:

function sendMessage () {
    var m = document.getElementById("messageField").value;
    var msg = {
        "type": "msg",
        "data": m
    }
    msg = JSON.stringify(msg);
    ws.send(msg);
}

And the C++ server before message pack is added:

void on_message(connection_hdl hdl, server::message_ptr msg) {
    connection_ptr con = m_server.get_con_from_hdl(hdl);

    std::string payload = msg->get_payload();
    try {
        auto jdata = nlohmann::json::parse(payload);

        if (jdata["type"] == "lgn") {
            std::string lname = jdata["data"];
            if (con->name == "") {
                con->name = lname;
            }
        }

        if (jdata["type"] == "msg") {
            std::string clientmsg = jdata["data"];
            jdata["cnt"] = clientmsg.length();
            msg->set_payload(jdata.dump());
            m_server.send(hdl, msg);
        }
    } catch (const std::exception& e) {
        msg->set_payload("Unable to parse json");
        m_server.send(hdl, msg);
        std::cerr << "Unable to parse json: " << e.what() << std::endl;
    }
}

Pretty basic. Here are the client and server after messagepack was added:

function sendMessage () {
    var m = document.getElementById("messageField").value;
    var msg = {
        "type": "msg",
        "data": m
    }
    msg = JSON.stringify(msg);
    var buffer = msgpack.encode(msg);
    ws.send(buffer);
}

Only adding

var buffer = msgpack.encode(msg);

and changing ws.send() accordingly.

void on_message(connection_hdl hdl, server::message_ptr msg) {
    connection_ptr con = m_server.get_con_from_hdl(hdl);

    std::string payload = msg->get_payload();

    // Parse messagepack
    msgpack::unpacked unpacked_msg;
    msgpack::unpack(&unpacked_msg, payload.data(), payload.size());
    msgpack::object obj = unpacked_msg.get();
    std::string sobj;
    obj.convert(&sobj);

    try {
        auto jdata = nlohmann::json::parse(sobj);

        if (jdata["type"] == "lgn") {
            std::string lname = jdata["data"];
            if (con->name == "") {
                con->name = lname;
            }
        }

        if (jdata["type"] == "msg") {
            std::string clientmsg = jdata["data"];
            jdata["cnt"] = clientmsg.length();
            msg->set_payload(jdata.dump());
            m_server.send(hdl, msg);
        }
    } catch (const std::exception& e) {
        msg->set_payload("Unable to parse json");
        m_server.send(hdl, msg);
        std::cerr << "Unable to parse json: " << e.what() << std::endl;
    }
}

Adding

    // Parse messagepack
    msgpack::unpacked unpacked_msg;
    msgpack::unpack(&unpacked_msg, payload.data(), payload.size());
    msgpack::object obj = unpacked_msg.get();
    std::string sobj;
    obj.convert(&sobj);

and changing nlohmann::json::parse() accordingly.

The strange thing is that I only use messagepack atm. to compress incoming json data but not out. I will use it both ways if this is resolved. There must be something I'm overlooking and help is appreciated.

C++ constructor syntax and zero-initialization

This is a short question about syntax in c++:

class arrayInit {
 public:
  bool vars[2];

  arrayInit() : vars() {} //1
};

class array {
 public:
  bool vars[2];
  array() {} //2
};

What does 1 and 2 do?

Why they don't zero initialize like this: bool vars[2]={};?

What is the purpose of arrayInit() : and array()? and what is it called so I could search for it?

It's from: http://ift.tt/1M79HWt

differnt behaviour between clang and microsoft c++/QT5 with constructors and return values

According to microsoft visual studio 2013 (being built from QT creator, QT 5.4), this code is fine:

#include <string>
struct X {
  X(std::string const &) {};
};

X wibble() { return ""; }

clang however says

test.cpp(53) : error: no viable conversion from 'const char [1]' to 'X'
X wibble() { return ""; }

test.cpp(49) : note: candidate constructor (the implicit copy constructor) not viable: no known conversion from 'const char [1]' to 'const X &' for 1st argument
struct X {

test.cpp(49) : note: candidate constructor (the implicit move constructor) not viable: no known conversion from 'const char [1]' to 'X &&' for 1st argument
struct X {

test.cpp(50) : note: candidate constructor not viable: no known conversion from 'const char [1]' to 'const std::string &' (aka 'const basic_string<char, char_traits<char>, allocator<char> > &') for 1st argument
X(std::string const &) {};

It does the same thing with QString for what it's worth. Assuming clang is correct, why is it complaining?

vendredi 30 octobre 2015

g++ faulty optimization with specialized template

I'm having problem with g++ (4.9.2) optimization that is produces faulty code that is puzzling to me. And by faulty, I mean the code output is fundementally different between optimized (-O1, -O2 or -O3) and non-optimized (-O0) compilation. And, of course, the optimized code is wrong.

I have class similar to <bitset>, where info is stored at bit-level and is instantiated with any number of bits, but has a specialized template for Bits with <= 8 bits.

#include <iostream>
using namespace std;

// generalized class Bits, uses array of specialized, 1-byte Bits
template <unsigned int bits=8, bool _=(bits>8)>
class Bits {
    Bits<8,false> reg[(bits+7)>>3];

public:
    void set(int pos)  { reg[pos>>3].set(pos%8);  };
    void clr(int pos)  { reg[pos>>3].clr(pos%8);  };
    bool get(int pos)  { reg[pos>>3].get(pos%8);  };
};

// specialized, 1-byte Bits (flag stored in a char)
template <unsigned int bits> class Bits<bits,false> {
    char reg;

public:
    Bits() : reg(0) {};
    Bits(int r) : reg(r) {};

    void set(int pos) { reg |=  mark(pos);        };
    void clr(int pos) { reg &= ~mark(pos);        };
    bool get(int pos) { return (reg & mark(pos)); };

    static int mark(int pos) { return ( 1 << pos ); };
};  


int main() {
    Bits<16> b;
    Bits<8> c;

    b.set(1);
    c.set(1);

    cout << b.get(1) << endl;
    cout << c.get(1) << endl;

    return 0;
};

The test is simple, set a bit and then print said bit state to stdout. This is done with a 16-bits Bits object (the generalized templated) and 8-bit Bits object (the specialized template). The expected answer is TRUE for either objects. And when I compile with no optimization (i.e. g++-4.9 -O0 main.cpp), this is exactly what I get. Output of ./a.out is:

1
1

But when I compile with -O1 optimization (i.e. g++-4.9 -O1 main.cpp), the results is different AND partially wrong:

0
1

Specifically, Bits<8> tests correctly in both optimzation (-O0 and -O3), but Bits<16> test correctly only with -O0 and not with -O1.

The optimizer (-O1, -O2, and -O3) all just optimizes out all then Bits member functions and simply jumps to the final results, calculated at compile-time. Obviously the optimizer is making some error, but I don't know what is the root cause. Does anyone know what I should be looking for to debug the problem?

Recosystem package in R - C++ setup on Mac

Recosystem is a wrapper of LIBMF in R, thus "needs a C++ compiler that supports C++11 standard" and "It is strongly suggested to set proper flags according to your type of CPU before compiling the package" as described here.

I don't have much knowledge about C++, and thus intimidated by these statement... As a Mac user I'm totally at loss what to do to set up the C++ environment needed for this package. Anyone have done this before? Any suggestion would be appreciated. Thanks!

Destructor for LinkedList of LinkedLists

For an assignment in one of my programming classes we have to make an adjacency list that is a linked list of linked lists that would look like this.

A->B->C

B->A->D

C->D

D->A->B->C

I'm having trouble with a memory leak when trying to free up the memory allocated in the destructor. I've been trying to figure it out for a while now but haven't found/come up with any solutions that work.

Also, please ignore that the implementation is included in the header file. We were told it was ok to do for this assignment.

Valgrind Error Message:

==2316== HEAP SUMMARY:
==2316== in use at exit: 48 bytes in 2 blocks
==2316== total heap usage: 3 allocs, 1 frees, 64 bytes allocated
==2316==
==2316== 48 (32 direct, 16 indirect) bytes in 1 blocks are definitely lost in loss record 2 of 2
==2316== at 0x4C2B0E0: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==2316== by 0x4012EE: main (main.cpp:34)
==2316==
==2316== LEAK SUMMARY:
==2316== definitely lost: 32 bytes in 1 blocks
==2316== indirectly lost: 16 bytes in 1 blocks
==2316== possibly lost: 0 bytes in 0 blocks
==2316== still reachable: 0 bytes in 0 blocks
==2316== suppressed: 0 bytes in 0 blocks
==2316==
==2316== For counts of detected and suppressed errors, rerun with: -v
==2316== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

Here is some of the code I'm using (compiled with gcc c++11):
linkedlist.h

#ifndef LINKEDLIST_H
#define LINKEDLIST_H

template<typename T> struct Node
{
    T data;
    Node<T>* next;
};

template<typename T> class LinkedList
{
private:
    Node<T>* head;
    Node<T>* tail;
    Node<T>* curr;
    unsigned int size;

    void insertAtHead(T val)
    {
        Node<T>* temp = new Node<T>;
        temp->data = val;
        temp->next = nullptr;
        head = temp;
        tail = temp;
        curr = temp;
        size++;
    }

public:
    LinkedList()
    {
        head = nullptr;
        tail = nullptr;
        curr = nullptr;
        size = 0;
    }

    ~LinkedList()
    {
        Node<T>* nodePtr = head;
        Node<T>* temp;

        while (nodePtr != nullptr)
        {
            temp = nodePtr;
            nodePtr = nodePtr->next;
            delete temp;
        }

        size = 0;
    }

    void insertAtTail(T val)
    {
        if (head == nullptr)
            insertAtHead(val);
        else
        {
            Node<T>* temp = new Node<T>;
            temp->data = val;
            curr->next = temp;
            temp->next = nullptr;
            tail = temp;
            curr = temp;
            size++;
        }
    }
    // returns the value at the node location passed if it exists within the
    // linked list, otherwise nothing is returned
    T get(int location)
    {
        // std::cout << "size: " << size << std::endl;

        if (location >= 0 && location <= size)
        {
            Node<T>* temp = head;
            unsigned int counter = 0;

            while (counter != location)
            {
                temp = temp->next;
                counter++;
            }

            return temp->data;
        }
    }
};
#endif // LINKEDLIST_H

main.cpp

#include "linkedlist.h"

int main()
{
    LinkedList<LinkedList<int>*> matrix;
    matrix.insertAtTail(new LinkedList<int>);
    matrix.get(0)->insertAtTail(6);

    return 0;
}

Extern template and member templates

//A.hpp:

#ifndef A
#define A
#include <iostream>

template <typename T> class A{
public:
    template <typename U> void huh(U a) { cout << "Yello? You'll have to speak up I'm wearing a towel." << endl;}
    T name;
};

#endif

//test.cpp:

#include "A.hpp"

extern template class A<string>;

int main(){
    A<string> a;
    a.huh(2)
}


//instantiate.cpp:

#include "A.hpp"

template class A<string>;

This compiles fine on gcc 4.8.1. So is this really a valid program? My concern comes from the fact that a.huh(2) is called, where huh is a member template of an explicitly instantiated class template. There was no explicit instantiation for huh<int> anywhere in my program despite it being a member template. When the compiler sees a.huh(2), does the compiler still generate code for huh<int> in test.cpp despite the fact that code for the class A<string> isn't even generated in that same translation unit? I'd find it quite odd that class member function code could be defined in a translation unit where the class code isn't even generated, but this seems to be a completely valid thing to do? I would really have expected to have to put something like this in instantiate.cpp before it could compile:

//instantiate.cpp:

#include "A.hpp"

template class A<string>;
template void A<string>::huh(int); //not necessary apparently?

(However, if I make huh an ordinary function (no templates) then the compiler will not accept the code, so it must be special to member templates).

Differentiate between 1D and 2D container in template class constructor

So, I have a class, which has an array of arrays as a private member. I wish to have two constructors for each case (1D or 2D). But of course their declaration happens to be the same, so template deduction can't do its job without me doing something about it. Here's the code:

#include <iostream>
#include <array>

template<class T, std::size_t rows_t, std::size_t cols_t>
class test
{
private:
    std::array<std::array<T, cols_t>, rows_t> _data;
public:    
    auto begin() { return this->_data.begin(); }
    auto end() { return this->_data.end(); }


    //CONSTRUCTOR
    template<class type_t>
    test(const type_t &arr)
    {
        std::size_t j = 0;
        for (const auto &num : arr)
            this->_data[0][j++] = num;
    }

    template<class type_t>
    test(const type_t &arr)
    {
        std::size_t i = 0;
        for (const auto &el : arr)
        {
            std::size_t j = 0;
            for (const auto &num : el)
                this->_data[i][j++] = num;
            ++i;
        }
    }
};

int main()
{
    double arr[3] = { 1, 2, 3 };
    double arr2[2][2] = { {1, 2}, {3, 4} };

    test<double, 1, 3> obj = arr; 
    test<double, 2, 2> obj2 = arr2;

    for (const auto &i : obj2)
    {
        for (const auto &j : i)
            std::cout << j << " ";
        std::cout << std::endl;
    }

    std::cin.get();
}

Note: I've been reading about enable_if, but I don't quite understand how it works. Can it be done with that?

C++ vector out_of_range error (GCC 4.8.4 vs 4.8.1)

I have code that compiles and is executable using both GCC 4.8.1 and 4.8.4 (Gentoo). When I run the code on the system using 4.8.1 I don't get an out_of_range error and the program runs fine. When I compile and run it on a server using 4.8.4 I get the error:

terminate called after throwing an instance of 'std::out_of_range'
  what():  vector::_M_range_check
Abort

I've also compiled and run it in Visual Studio 2012, again with no errors. I'm wondering what might be causing the discrepancy. At first, I thought it might be an issue with comparisons using .size(), so I cast them all to int, but the issue still isn't resolved. Does anyone have any idea what might be causing this?

Edit:

Here's a snippet of the kind of code I'm using. It's pretty uniform throughout. Just some standard for loops and vectors:

// Resize points based on number of dimensions
for( int k = 0; k < (int)points.size(); k++ )
    points.at(k).resize((int)countVec.size());

Result from operator+ to be floating-point if either lhs or rhs object is floating-point

So I have written a simple template class which stores an array. I'm trying to overload the + operator so that it sums up two objects' arrays element by element. It works fine, but here is the problem.

I want it to be so that if either the lhs or rhs (or both) object is of a floating-point type, the result would also be a floating-point object.

For example: testclass({1, 2, 3}) + testclass({2.2, 3.3, 1.1}) would return a testclass<double> object.

I managed to get it to work if the rhs object is double, but can't get it right when lhs is double.

This is the code I have written so far:

#include <iostream>
#include <initializer_list>

template<class T>
class testclass
{
public:
    T data[4];
public:
    testclass() {}

    testclass(const std::initializer_list<T> &ilist)
    {
        short i = 0;
        for (const T &el : ilist) this->data[i++] = el;
    }

    auto &operator[](const short &i) { return this->data[i]; }

    //so when this is called the return object would be the same
    //type as the rhs object
    template<class type_t>
    auto operator+(const testclass<type_t> &rhs)
    {
        testclass<type_t> ret;
        for (short i = 0; i < 4; ++i)
            ret.data[i] = this->data[i] + rhs.data[i];
        return ret;
    }

};

int main()
{
    testclass<int> obj = { 1, 2, 3, 4 };
    testclass<double> obj2 = { 1.1, 2.2, 3.3, 4.4 };

    auto res = obj2 + obj;

    for (short i = 0; i < 4; ++i) 
        std::cout << res[i] << " ";

    std::cin.get();
}

Is it good habit to always initialize objects with {}?

Initializing objects with new {} syntax like this:

int a { 123 };

has benefit - you would not declare a function instead of creating a variable by mistake. I even heard that it should be habit to always do that. But see what could happen:

// I want to create vector with 5 ones in it:
std::vector<int> vi{ 5, 1 }; // ups we have vector with 5 and 1.

Is this good habit then? Is there a way to avoid such problems?

Idiomatic C++ syntax for "maybe-move" parameter passing

Consider a map-like type with slightly different behavior on the emplace operation: While it accepts Key&& and Val&& arguments, it guarantees me that any argument I pass it will remain unchanged if the key is not inserted.

I want to implement an insert_or_update type function (I realize this is not the way you would actually do it, but stick with me for an example).

my_map_type::iterator iter;
bool                  inserted_new;
std::tie(iter, inserted_new) = my_map.emplace(std::move(key), std::move(val));
if (!inserted_new)
    iter->second = std::move(val);

Someone looking at this code will think there is a bug: I am using val after I have already said std::move(val).


The most reasonable thoughts I have are to change emplace to return an optional<Val> instead of just a bool. If the key is not inserted, it will be returned to you.

my_map_type::iterator iter;
std::optional<Val>    returned_val;
std::tie(iter, returned_val) = my_map.emplace(std::move(key), std::move(val));
if (returned_val)
    iter->second = std::move(*returned_val);

The problem with this solution is performance. The most obvious issue is that it only works reasonably if moving your Val is absurdly cheap. Another problem is that under -O3, my original example does not touch the stack, while the latter puts returned_val on it (when Val = std::uint64_t on a 64-bit Linux machine with GCC 5.2).


Question: Is there a way to maintain the safety of my latter option while still getting the performance benefits of the former?

Pass Member Function to Variadic Template Function

I have a class with a function called enqueue:

template<class T, class... Args>
inline auto ThreadPool::enqueue(T && t, Args&&... args) ->std::future<typename std::result_of<T(Args ...)>::type>
{
    using return_type = typename std::result_of<T(Args...)>::type;

    auto task = std::make_shared<std::packaged_task<return_type()>> (
       std::bind(std::forward<T>(t), std::forward<Args>(args)...)
    );

    std::future<return_type> result = task->get_future();
    {
        std::unique_lock<std::mutex> lock(m_mutex);

        // Don't allow job creation after stopping pool.
        if (m_done)
            throw std::runtime_error("Enqueue on stopped ThreadPool.");

        m_tasks.emplace([task]() { (*task)(); });
    }

    m_cond.notify_one();
    m_futures.push_back(move(result));
    return result;
}

This is an inline implementation done inside of the header file alongside the ThreadPool class.

It is a singleton and should be able to take any function with its arguments, add this to a task queue and return a future of the result type of that function.

Here is the class where I am trying to use it:

void Grepper::scan(std::tr2::sys::path const& folder, std::string expression, bool verbose) {
    // Create directory iterators.
    std::tr2::sys::recursive_directory_iterator d(folder);
    std::tr2::sys::recursive_directory_iterator e;

    // Create tasks from files that match initial extension list.
    for (; d != e; ++d) {
        if (!std::tr2::sys::is_directory(d->status()) && std::find(m_extensions.begin(), m_extensions.end(), d->path().extension().generic_string()) != m_extensions.end()) {
            ThreadPool::get_instance().enqueue(grep, d->path(), expression, verbose);
        }
    }
}

Which gives a compiler error of:

Error C3867 'Grepper::grep': non-standard syntax; use '&' to create a pointer to member 

I have tried creating a functor to this function as well as passing the function as a lambda:

ThreadPool::get_instance().enqueue([this](std::tr2::sys::path p, std::string s, bool b) { grep(p, s, b); });

Which gives me the following compiler error:

Error C2893 Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...)'

For reference here is the declaration of my grep method:

void grep(std::tr2::sys::path file, std::string expression, bool verbose);

How do I pass this function and its arguments properly to the enqueue method?

boost::asio + std::future - Access violation after closing socket

I am writing a simple tcp client to send and receive single lines of text. The asynchronous operations are handled by std::future in order to faciliate blocking queries with timeouts. Unfortunately, my test application crashes with an access violation when destructing the server object. Here is my code:

TCPClient.hpp

#ifndef __TCPCLIENT_H__
#define __TCPCLIENT_H__

#include <boost/asio.hpp>
#include <boost/asio/use_future.hpp>
#include <memory>
#include <vector>
#include <future>
#include <thread>
#include <chrono>
#include <iostream>
#include <iterator>

using namespace boost::asio;

class TCPClient {
public:
    TCPClient();
    ~TCPClient();

    void connect(const std::string& address, const std::string& port);
    void disconnect();

    std::string sendMessage(const std::string& msg);
private:
    boost::asio::io_service ioservice;
    boost::asio::io_service::work work;
    std::thread t;

    std::unique_ptr<boost::asio::ip::tcp::socket> socket;
};

inline TCPClient::TCPClient() : ioservice(), work(ioservice) {
    t = std::thread([&]() {
        try {
            ioservice.run();
        }
        catch (const boost::system::system_error& e) {
            std::cerr << e.what() << std::endl;
        }
    });
}

inline TCPClient::~TCPClient() {
    disconnect();
    ioservice.stop();
    if (t.joinable()) t.join();
}

inline void TCPClient::connect(const std::string& address, const std::string& port) {
    socket.reset(new ip::tcp::socket(ioservice));

    ip::tcp::resolver::query query(address, port);
    std::future<ip::tcp::resolver::iterator> conn_result = async_connect(*socket, ip::tcp::resolver(ioservice).resolve(query), use_future);

    if (conn_result.wait_for(std::chrono::seconds(6)) != std::future_status::timeout) {
        conn_result.get(); // throws boost::system::system_error if the operation fails
    }
    else {
        //socket->close();
        // throw timeout_error("Timeout");
        throw std::exception("timeout");
    }
}

inline void TCPClient::disconnect() {
    if (socket) {
        try {
            socket->shutdown(ip::tcp::socket::shutdown_both);
            std::cout << "socket points to " << std::addressof(*socket) << std::endl;
            socket->close();
        }
        catch (const boost::system::system_error& e) {
            // ignore
            std::cerr << "ignored error " << e.what() << std::endl;
        }
    }
}

inline std::string TCPClient::sendMessage(const std::string& msg) {
    auto time_over = std::chrono::system_clock::now() + std::chrono::seconds(4);

    /*
    // Doesn't affect the error
    std::future<size_t> write_fut = boost::asio::async_write(*socket, boost::asio::buffer(msg), boost::asio::use_future);

    try {
        write_fut.get();
    }
    catch (const boost::system::system_error& e) {
        std::cerr << e.what() << std::endl;
    }
    */
    boost::asio::streambuf response;

    std::future<std::size_t> read_fut = boost::asio::async_read_until(*socket, response, '\n', boost::asio::use_future);
    if (read_fut.wait_until(time_over) != std::future_status::timeout) {
        std::cout << "read " << read_fut.get() << " bytes" << std::endl;
        return std::string(std::istreambuf_iterator<char>(&response), std::istreambuf_iterator<char>());
    }
    else {
        std::cout << "socket points to " << std::addressof(*socket) << std::endl;
        throw std::exception("timeout");
    }
}
#endif

main.cpp

#include <iostream>

#include "TCPClient.hpp"

int main(int argc, char* argv[]) {
    TCPClient client;
    try {
        client.connect("localhost", "27015");
        std::cout << "Response: " << client.sendMessage("Hello!") << std::endl;
    }
    catch (const boost::system::system_error& e) {
        std::cerr << e.what() << std::endl;
    }
    catch (const std::exception& e) {
        std::cerr << e.what() << std::endl;
    }
    system("pause");
    return 0;
}

The output is "timeout" as expected (test server sends no data on purpose), but ioservice.run() crashes immediately (access violation) after closing the socket in TCPClient::disconnect(). Am I doing some memory mismanagment here?

Compiler is MSVC 12.0.31101.00 Update 4 (Visual Studio 2013)

Variadic template divider

I have the following little variadic template which is supposed to divide a series of numbers. As I understand it, this is a rough sketch of what would happen if I call divide(20, 2, 2) -> 20/ 2 / 2. Apparently it doesn't happen that well, as the answer I get is 20... It works fine when there are only two arguments.

#include <iostream>

template<class first_t>
auto divide(const first_t &first)
{
    return first;
}

template<class first_t, class... rest_t>
double divide(const first_t &first, const rest_t&... rest)
{
    return first / divide(rest...);
}

int main()
{
    std::cout << divide(20, 2, 2); //should print 5

    std::cin.get();
}

Is it guaranteed that defaulted constructor initialize built in types automatically to 0?

Before you started to mark this as an duplicate I've already read this .But It doesn't answer my question. The linked question talks about C++98 & C++03 but my question is about defaulted constructor introduced by C++11.

Consider following program (See live demo here):

#include <iostream>
struct Test
{
    int s;
    float m;
    Test(int a,float b) : s(a),m(b)
    { }
    Test()=default;
}t;
int main()
{
    std::cout<<t.s<<'\n';
    std::cout<<t.m<<'\n';
}

My question is that is the defaulted constructor provided by compiler here always initializes built in types to by default 0 in C++11 & C++14 when they are class & struct members. Is this behavior guaranteed by C++11 standard?

Service under linux, a modern approach?

The situation: a small new project of a service listening on socket.

Preliminary study: this answer how to make a process daemon and the link in the answer: http://ift.tt/1cya1hA

Good, everything fine.
Now, for the listening part I must have no problem, but for threads I started to watch c++ 11 specs. So I included:

#include <thread>

This is nice, just calling std::thread, I can open a thread on new connections.

So I was just wondering. Id the fork part still good in c++ 11?

Is there a newer approach to build a linux service, or the howto is still good?

c++11 keywords recognition in eclipse in Ubuntu

I am using Eclipse Mars with the GCC compiler in Ubuntu 14.04. I have enabled C++11 options in the compiler settings.

The problem is I use a lot of new c++11 features like Lambda, tuple, shared_ptr, etc. The code is absolutely error-free, but eclipse doesn't recognize them, So there are a lot of errors in the Problems window.

Let me know if there are ways to include these new changes to the editor content assist or any other solution.

Cout a whole array in c++

I am fairly new to c++, is there a way in c++ through which we can cout a whole static array apart from iterating via a for loop?

int arra[10] = {1,2,3,4};
std::cout << arra << std::endl;

I tried this but, this is printing address of the first element in the array.

Capture std::promise in a lambda C++14

I want to make a state machine which works processes the submitted signals in its own thread. I use Visual Studio 2015, so C++11 and partially C++14 is supported. Signals are stored in containers. Each signal is represented as an std::function. I would like to wait from the client until the state machine processes the signal that was submitted, so it is a kind of synchronous signal.

My problem is: I cannot capture an std::promise into a lambda and add it to the container.

#include <functional>
#include <future>
#include <list>

std::list<std::function<int()>> callbacks;

void addToCallbacks(std::function<int()>&& callback)
{
    callbacks.push_back(std::move(callback));
}

int main()
{
    std::promise<int> prom;
    auto fut = prom.get_future();

    // I have made the lambda mutable, so that the promise is not const, so that I can call the set_value
    auto callback = [proms{ std::move(prom) }]() mutable { proms.set_value(5); return 5; };

    // This does not compile
    addToCallbacks(std::move(callback));

    // This does not compile either, however this lambda is a temporal value (lvalue)
    addToCallbacks([proms{ std::move(prom) }]() mutable { proms.set_value(5); return 5; });

    return 0;
}

What are the solutions if

  • I want to avoid capturing the promise by reference
  • I want to avoid capturing a * pointer or a shared_ptr to the promise

It would be nice to embed the promise into the class somehow that the lambda generates. This means that the lambda is not copyable any more, only moveable. Is it possible at all?

Is

I added <algorthm> to a standard header file that's included with most files in my project. On a Core2 Duo machine with std=c++11, testing produces the following compile error:

g++ -DNDEBUG -g2 -O2 -std=c++11 -fPIC -march=native -pipe -fsanitize=address -c cpu.cpp
In file included from /usr/lib/gcc/x86_64-linux-gnu/4.9/include/x86intrin.h:43:0,
                 from /usr/include/x86_64-linux-gnu/c++/4.9/bits/opt_random.h:33,
                 from /usr/include/c++/4.9/random:50,
                 from /usr/include/c++/4.9/bits/stl_algo.h:66,
                 from /usr/include/c++/4.9/algorithm:62,
                 from stdcpp.h:13,
                 from cpu.cpp:13:
/usr/lib/gcc/x86_64-linux-gnu/4.9/include/wmmintrin.h: In function ‘__m128i _mm_aesdec_si128(__m128i, __m128i)’:
/usr/lib/gcc/x86_64-linux-gnu/4.9/include/wmmintrin.h:44:1: error: redefinition of ‘__m128i _mm_aesdec_si128(__m128i, __m128i)’
 _mm_aesdec_si128 (__m128i __X, __m128i __Y)
 ^
In file included from cpu.cpp:12:0:
cpu.h:83:1: note: ‘__m128i _mm_aesdec_si128(__m128i, __m128i)’ previously defined here
 _mm_aesdec_si128 (__m128i a, __m128i b)
 ^

I'm trying to determine how I should proceed.

Is <algorithm> supposed to include AES intrinsics?

Templating template instantiation in different file

I'm aware that the following works:

test.h

#pragma once

#include <string>

class testclass
{
private:
    std::string _data;
public:

    template<class T> 
    testclass(const T&);

};

test.cpp

#include "test.h"

template testclass::testclass(const int&);
template testclass::testclass(const long&);

//function can be called only with `int` and `long`
template<class T> 
testclass::testclass(const T &num)
    : _data(std::to_string(num))
{}

So this is a successful way of splitting the declaration and implementation of a template function, but it has some downsides. One of them is having to hardcode all the types with which you want your function to be called and that's a drag. And if the function is quite small, you end up having written more code than you would have if you hadn't templated it...

I was wondering if something like this is possible:

test.cpp

#include "test.h"

template<class T2> //bogus syntax, but here the point of interest
template testclass::testclass(const T2&);

template<class T> 
testclass::testclass(const T &num)
    : _data(std::to_string(num))
{}

How to fix error refactoring decltype inside template

I'm passing a function into a template to become a pre-supplied argument to the constructor, but also need to use decltype on that function to pass the function type to unique_ptr<...> template instantiator(? is that the right word)

It works if I pre-use decltype as an extra template argument, but not if I invoke it inside the template on the function passed as a parameter.

I'm using g++ 4.9.2, and extending my explorations here Calling inherited template constructor of unique_ptr subclass where I subclass unique_ptr to have a fixed destructor, I find that some destructor functions do not return void, so I want a more generic template that does not need to specify the destructor function type.

My current code is:

void free_int(int* p) {
  delete p;
}

template<typename T, void (*D)(T*)>
class unique_dptr : public std::unique_ptr<T, decltype(D)> {
    public: unique_dptr(T* t) : std::unique_ptr<T, decltype(D)>(t, D) { };
};

using int_ptr = unique_dptr<int, ::free_int>;
int_ptr i(new int(2));

but note the void (*D)(T*) calling signature to restrict the destructor to a void function that takes a pointer to T

Given normal use of unique_ptr in this form:

unique_ptr<foo, decltype(&::free_foo)>

I want to have something like this:

template<typename T, typename D>
class unique_gptr : public std::unique_ptr<T, decltype(&D)> {
    public: unique_gptr(T* t) : std::unique_ptr<T, decltype(&D)>(t, D) { };
};

using int_gptr = unique_gptr<int, ::free_int>;
int_gptr ig(new int(2));

but the compiler hates it:

error: template argument 2 is invalid
class unique_gptr : public std::unique_ptr<T, decltype(&D)> {
                                                          ^

No doubt ancient C-macro style token pasting is what I am wrongly aiming at.

I have tried removing the & from decltype(&D) but that leaves the error:

error: argument to decltype must be an expression

however this is OK:

template<typename T, typename D, D F>
class unique_gptr : public std::unique_ptr<T, D> {
    public: unique_gptr(T* t) : std::unique_ptr<T, D>(t, F) { };
};

using int_gptr = unique_gptr<int, decltype(&::free_int), ::free_int>;
int_gptr ig(new int(2));

but I wonder what I am doing wrong that I can't manage move the decltype(&::free_int) into the template.


Other solutions

I realise that I can just write additional specialisations for other fixed free-function types, replacing void(*)(void*)

I realise that I can override the std::default_delete for my type.

But this is really an exercise in template composition

debugging code using opencv fails with segmentation fault

Trying to debug some c++11 code that utilizes the opencv library, yields a segmentation fault in gdb.

I am debugging following function using gdb in linux.

MatchedFeatures extract_best_features(vector<Mat> imgs)
{
  MatchedFeatures result;

  cv::Ptr<Feature2D> f2d = xfeatures2d::SIFT::create();
  //cv::Ptr<Feature2D> f2d = xfeatures2d::SURF::create();
  //cv::Ptr<Feature2D> f2d = ORB::create();

  for (auto it = 0; it < imgs.size(); ++it) {
    vector<KeyPoint> keyPoints;
    Mat descriptors;
    f2d->detect(imgs[it], keyPoints);
    f2d->compute(imgs[it], keyPoints, descriptors);
    result.imgFeatures.push_back(ImgFeatures{imgs[it], keyPoints, descriptors});
  }

  BFMatcher matcher;
  vector< DMatch > matches;
  matcher.match(result.imgFeatures[0].descriptors,
                result.imgFeatures[1].descriptors,
                matches);

  cout << matches.size() << "\n";

  //extract top 10
  sort(matches.begin(), matches.end(),
            [&](const DMatch x, const DMatch y) -> bool
            { return x.distance <= y.distance; });
  result.matches = vector<DMatch>(matches.begin(),matches.begin()+5); // <- debug fails here and matches is empty in debug mode
  return result;
}

The segmentation fault is yielded when the debugger reaches the point where I slice the matches vector. Inspecting the matches variable and looking at the stacktrace revealed that matches is empty.. However, only empty in debug mode.

The code works perfectly fine when I just run it normally, it only fails when debugging.

I noticed that the BFMatcher spawns a lot of threads when performing the match, so I suspect that the problem arises because of threads. Though I just started learning c++, so I can only guess whats wrong.

Is there some way to "wait" for the threads to finish properly in gdb? Or is there some other trick that allows me to debug and inspect this kind of code in c++ without getting segmentation faults and empty results from side-effect-generating-procedures such as match in BFMatcher?

How do I use while true in threads?

Can anyone point me at the thing I try to do in this code, because SecondLoop thread is unreachable at all. It becames reachable only if I remove while(true) loop.

#include <iostream>
#include <thread>

using namespace std;

void Loop() {
    while(true) {
        (do something)
    }
}

void SecondLoop() {
    while(true) {
        (do something)
    }
}

int main() {
    thread t1(Loop);
    t1.join();

    thread t2(SecondLoop);
    t2.join(); // THIS THREAD IS UNREACHABLE AT ALL!

    return false;
}

The reason why I use multithreading is because I need to get two loops running at the same time.

Wrong output with C++ Linked List using vector and struct [duplicate]

This question already has an answer here:

I'm new to C++, and recently have been into a problem.

I try to create a Linked List by using struct, and store all the reference in a vector, but I don't know why when I recall the value, the values changes.

I'll be more specific. Here's the code:

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

int main() {
    vector<int> a = { 2, 4, 3 };
    vector<ListNode> aListNode;

    aListNode.push_back(ListNode(a[0]));
    for (int i = 1; i < a.size(); i++) {
        aListNode.push_back(ListNode(a[i]));
        aListNode[i - 1].next = &aListNode[i];
        cout << aListNode[i - 1].next->val << endl;
    }

    cout << aListNode[0].next->val << endl;

    cin.get();

    return 0;
}

The result is:

4
3
-17891602

But the expected result is:

4
3
4

I think the problem is from using pointers, but I'm still unsure where.

how can cocos2dx 2.2.6 support c++ 11

I develop a project with cocos2d-x 2.2.6 on Mac OS 10.11.1 ,X-code 7.1 . All configuration are default. I need include header files such as <thread>, <mutex>, when I build the project I got an error , "'thread' file not found "。I googled this error then I realized that I have to update my X-code configuration to support c++11 .I modified some configuration as bellow:

TARGET->Build Settings->Apple LLVM 7.0 - Language - C++
C++ Language Dialect => c++11[-std=c++11]
C++ Standard Library => c++11[-std=c++11]
[the configuration I modified][1]
I build the project after clean. then I got a lot of errors.  
[errors][2]

Errors like bellow :
"std::string::operator=(std::string const&)", referenced from:
cocos2d::CCLabelTTF::_prepareTextDefinition(bool) in libcocos2dx.a(CCLabelTTF.o)
"std::string::operator[](unsigned long)", referenced from:
"std::string::operator+=(char const*)", referenced from:
"std::string::operator+=(std::string const&)", referenced from:
"std::_List_node_base::hook(std::_List_node_base*)", referenced from:
"std::_List_node_base::unhook()", referenced from:
"std::basic_stringstream<char, std::char_traits<char>, std::allocator<char> >::basic_stringstream(std::string const&, std::_Ios_Openmode)", referenced from:
"std::basic_stringstream<char, std::char_traits<char>, std::allocator<char> >::~basic_stringstream()", referenced from:
"std::ios_base::Init::Init()", referenced from:
"std::ios_base::Init::~Init()", referenced from:

clang: error: linker command failed with exit code 1 (use -v to see invocation)

Today I create a total new project, I won't change a word,the project run fine. but when I modify configuration, the errors show again.

I need the project support c++ 11 . How can I fix this . I have been troubled by this problem for days. Am I miss some library? thank you very much. I will be online all the time.

jeudi 29 octobre 2015

Given a string, how can I add only unique characters from another string to it?(C++)

I've been trying many different things for hours now, I tried using std::unique but I was getting funky results, then I tried using string::find. I feel like it would be easy to accomplish this if I used std::vector I'm looking for an efficient way to do this using the standard library, I read though a lot of the questions on here and cpluplus.com on this subject but I couldn't use their answers to implement what I needed. I apologize if this is trivial but I'm tired of trying different things at this point.

For example:

int main(){

  std::string unique_chars;
  std::string new_string = "ABC"

  getUniqueChars(unique_chars, new_string);
  cout << unique_chars << endl;

  new_string = "ABDF"
  getUniqueChars(unique_chars, new_string);

  cout << unique_chars; 

  return 0;
}  

void getUniqueChars(string &unique_chars, string &new_string){

   //add only unique characters from new_string to unique_chars

   return;
}

Should output:

ABC
ABCDF

How to pass vector

The question is related to a talk by Stefanus Du Toit on hourglass pattern. Its a great talk, really helpful for library writers.

Youtube Link: https://youtu.be/PVYdHDm0q6Y

Slideshare Link: http://ift.tt/1AGuMgW

Ok here is the question:

Say I have to pass a std::vector<MyObject> across the library boundary. What is the best way to do this using hourglass pattern. I am concerned about the performance as well as keeping a clean interface. Given below is a set of example interfaces that I want to implement.

Clientside C++ interface:

void MyLibraryClass::DoSomething(const std::vector<MyObject>& objs);

C Interface:

???? (Not sure what is the best practice here)

Internall library C++ interface:

MyInternalLibraryClass::DoSomething(const std::vector<MyObjectImpl>& objs);

Hope this explains my question.

How to take ownership of std::unique_ptr and std::shared_ptr

This is follow-up question for this.

How do we take ownership of a std::unique_ptr or std::shared_ptr?

Is there a way to to keep b alive?

class A{
   A() {
        b = std::unique_ptr<char[]>(new char[100] { 0 });
   }
private:
 char* b;
}

void func {
   A a;
}

std::equal_range with lambda

Lets say I have a vector of strings and I want to find all strings, that start with 'a', so I can do this:

struct cmp {
    bool operator()( const std::string &s, char c ) const { return s.front() < c; }
    bool operator()( char c, const std::string &s ) const { return s.front() < c; }
};
std::vector<std::string> strings;
...
auto range = std::equal_range( strings.begin(), strings.end(), 'a', cmp{} );
...

Is it possible to implement comparison function with generic lambda instead of structure with 2 methods?

Why is std::bitset::size non-static

I can't possibly imagine why it was chose that std::bitset::size is non-static. It makes it much harder to get a constexpr size; you have to write something like this:

template<int val>
struct int_
{
   static const constexpr value = val;
};

template<size_t size>
auto getBitsetSizeIMPL(std::bitset<size>)
{
   return int_<size>{};
}

template<typename BitsetType>
constexpr size_t getBitsetSize()
{
    return decltype(getBitsetSizeIMPL(BitsetType{}))::value;
}

When if it were static all you would have to do would be

BitsetType::size()

and there would be no sacrifice of functionality.

Is there a historical reason that I am missing or is there a technical fact I am missing?

Allocating class member with std::shared_ptr

Is my assumption, that in following example, memory referenced by b will be deallocated once instance of A goes out of scope at end of func(), correct?

class A{
   A() {
        b = std::shared_ptr<char>(new char[100] { 0 } );
   }
private:
 B* b;
}

void func {
   A a;
}

C++ Change value of structs inside a vector, that is inside a struct, that is inside another vector

I have the following code (found at this link here):

    // Example program
#include <iostream>
#include <vector>
#include <chrono>
#include <string>
#include <sstream>

struct ControlStruct {
    std::string port;
    bool timeoutOn;
    int detectionTimeout;
    bool state;
};

struct DeviceStruct {

    std::string name;

    std::vector<ControlStruct> deviceControls;

};

std::vector<DeviceStruct> devices;

int main()
{
    for (int i = 0; i < 10; i++)
    {
        ControlStruct cs;

        DeviceStruct device;

        std::stringstream ss;
        ss << "Device" << i;
        device.name = ss.str();

        for(int k = 0; k < 5; k++)
        {
            ControlStruct cs;

            ss.clear();
            ss << "Port" << i;
            cs.port = ss.str();

            cs.state = false;
            cs.timeoutOn = false;
            cs.detectionTimeout = (k * 2) + 1;

            device.deviceControls.push_back(cs);
        }

        devices.push_back(device);
    }


    //
    // Start devices
    //
    for (auto device : devices)
    {
        for (auto control : device.deviceControls)
        {
            control.timeoutOn = true;
            control.state = true;

            std::cout << "Starting device " << device.name << " with timeout of " << control.detectionTimeout << " sec." << std::endl;
        }

    }

    while (1)
    {
        for (auto device : devices)
        {
            for (auto control : device.deviceControls)
            {
                if (!control.state)
                    continue;

                std::cout << "I NEVER GET HERE!!!!!!!!!!!!" << std::endl;

                control.detectionTimeout--;

                if (control.detectionTimeout == 0)
                {
                    control.state = false;
                    std::cout << "Device " << device.name << " timed-out." << std::endl;
                }
                else
                    std::cout << "Device " << device.name << " count = " << control.detectionTimeout << std::endl;
            }
        }
    }

}

For some reason, I never get into the I NEVER GET HERE!!! code...

Is there a special way to set values of structs inside an vector inside a struct that is inside a vector ? Am I missing something here ?

I´m using C++11, gcc linux.

Thanks for helping.

How to pass program options in boost without argument name

I was wondering how is it possible to pass program options in boost without giving argument name like program.exe var1 instead of program.exe --arg1 var1. However I know how to handle this without boost lib with obtaining just argv[1], but I will be very thankful if somebody know how to handle it in boost.

Construct-in-place an unmoveable object in a map

I'm trying to construct an object in a map that contains an atomic, so it can neither be copied nor moved AFAICT.

My reading of C++ reference is that map emplace should be able to do this. But the following code does not compile because of deleted or non-existent constructors. Using make_pair does not help.

#include <atomic>
#include <unordered_map>

class Z {
  std::atomic<int> i;
};

std::unordered_map<int, Z> map;

void test(void) {
  map.emplace(0, Z()); // error
  map[0] = Z(); // error
}

Is this possible, and if not, why not?

EDIT: Compiler is gcc 4.8.1, on Linux

Modify std::less on a shared_ptr

This is what I have:

struct Foo {
  int index;
}
std::set<std::shared_ptr<Foo>> bar;

I want to order bar's elements by their indices instead of by the default std::less<std::shared_ptr<T>> function, which relates the pointers.

I read I can type std::set<std::shared_ptr<Foo>, std::owner_less<std::shared_ptr<Foo>>> bar, but I'd prefer to stick to the previous syntax.

I tried defining std::less<std::shared_ptr<Foo>>, but it's not actually being used by the set functions. Is there a way I can achieve this?

Template method specialization for multiple types

I have a class “A” which exposes the template method foo. Foo has a standard implementation which works fine with B,C. It also has a special implementation for D.

class A
{
  template<typename T>
  void foo()
  {
    //standard implementation
  }

  template<>
  void foo<D>
  {
    //special implementation
  }
}

class B{};
class C{};
class D{};

int main()
{
  A<B> a1;
  A<C> a2;
  A<D> a3;
}

Now, I need to add the class E, which requires for "foo" the same special implementation as D. Is there a way to say something like: For all the types use the standard foo. For D,E (and so on) the special implementation.

class A
{
  template<typename T>
  void foo()
  {
    //standard implementation
  }

  template<>
  void foo<D && E>  <-- PseudoCode - It doesn't work
  {
    //special implementation
  }
}

class B{};
class C{};
class D{};
class E{};

int main()
{
  A<B> a1;
  A<C> a2;
  A<D> a3;
  A<E> a4;
}

I was thinking to use the trait classes. But I was hoping there is something simpler to achieve this. Thanks

Hashing own String type with C++11

So I am trying to compile some codebase with clang (with libc++), but I keep finding uses of internal functions from libstdc++. Does anyone know some good method using standard library or boost/etc to hash custom string? Of course I could make std::string from it, but I don't use special string to make additional copies.

namespace std
{

template<>
struct hash<ct::String> : public __hash_base<size_t, ct::String>
{
    size_t operator()(const ct::String& __s) const noexcept
    { 
        return std::_Hash_impl::hash(__s.begin(), __s.end() - __s.begin()); 
    }
};

template<>
struct __is_fast_hash<hash<ct::String>> : std::false_type
{ };

}

random number generators from c++

I'm learning about the library, which improves on the old rand and srand in many ways. But with the rand it's clear that there is one and only one random number generator that gets called and updated whenever rand is used, wherever that is in your program. With the new way I'm not sure how to imitate this behaviour efficiently and with good style. For instance what if I want a dice roll and, aping online examples written in the main procedure, I write an object with a method like this:

class foo{
    public:
    float getDiceRoll(){
        std::random_device rd;
        std::default_random_engine e1(rd());
        std::uniform_int_distribution<int> uniform_dist(1, 6);
        return uniform_dist(e1);
   }
}

This looks terrible because the engine is re-created every time you want a dice roll. This is a bit of a contrived case, but in a large program you are going to have to put the declaration of the random number generator somewhere. As a first attempt to use I just want there to be one generator for all random numbers, like in the old days. What is the nicest way to achieve this? Easily available examples online are all written straight into the main procedure and so they do not answer this basic question. I cannot think of anything that doesn't seem like taking a sledgehammer to crack a nut. Any help would be great.

How to avoid multiple definition of object declared in .h file of C++ [duplicate]

This question already has an answer here:

I have a GameUI.h, Round1.cpp and GameUI.cpp file.

In GameUI.h, I have declared:

static cocos2d::sprite* battery;

Both Round1.cpp and GameUI.cpp has included GameUI.h and this is creating multiple definition problem and giving

linker command failed with exit code 1 - Error

C++TMP how to parse runtime array to variadic meta-template?

i've made my variadic meta template work (take any number of int args)

cout << findBestSum<4,5,6,3,7,20,3,50,1,-1,5>::result << endl; //outputs 103 which is good

now i meet a problem of passing a runtime input to this template, for example the standard argv (after converting it to int of course), as it is a pointer, and pointers don't exist in compile-time calculations.

is there a way to extract / expand / parse the input array as separate arguments into the template?

i could of course do something like

 findBestSum<arr[0],arr[1],arr[2]>::result

if i knew the number of arguments overhead, but i don't. the user can even input a million numbers.

p.s. just reminding, i can't do it this way: findBestSum<arr>::result because it is a pointer!! no addresses are assigned at compile-time

Tiny transmissions end up meshed together, Do I really need to parse the buffer?

I am doing some socketprogramming and I've come upon a little snag.

I've defined a protocol for communication between server and clients as part of a poker game, so when either side wants to trigger a certain action on the farside, it creates a array of ints(simple marshaling), where the very first int is the "opcode", a simple code that details how the data are to be used, as well as the size of the transmission. Any subsequent ints can be seen as arguments to that operation(where applicable), emulating function calls.

One thing the server needs to do whenever a client connects, is to notify the other clients that a new one has joined the game, so it sends a "new player has connected" message to all the other clients, which includes the tablenumber of that new player.

The problem arises when the serves tries to notify a client in quick succession, as my pseudo code will demonstrate. What happens is that the server sends two 8 byte transmissions that get received as a single 16 bytes(4 ints) on the farside. The result is that the client only passes on and uses the first 8 bytes, ignoring the rest, causing mayham(prints out a massive list of rubbish) later on when, for instance, the unlisted players say something in the chat.

Since I can't show my actual code, consider the following pseudocode on the relevant part of the serverside:

enum PROTOCOLENUMS
{
    NOTIFYPROTOCOL = //some number
}

//Reps is simple vector containing custom objects of type playerRepresentation.
for(auto player : Reps)
{
   if (player.getSocketNr() != newfiledescriptor)
   {

       int oldguyInfo[2] = 
       {NOTIFYPROTOCOL,player.getSocketNr() };
       send(newfd,oldguyInfo,sizeof(oldguyInfo),0);
       //the old players are simultaniously notified of the new player here.
   }
}

On the client side, the code responsible for receiving the transmission, and passing it on, looks something like this(error checking omitted):

short bytecount
while (true)
{
    bytecount = recv(serverSocketDescriptor,buffer,sizeof(buffer),0);
    cout<<bytecount<<endl; //Bytecount should ready 8 every time, instead it will accumulate if recv doesn't get called between sends.
    InterfacePtr->processTransmission(buffer);
}

Like I said, the problem arises when the buffer on the receiving side packs two(or more) sends into the internal cache, ie the tranmissions happen so fast that the recv() doesn't unblock in time to flush the first message out of the buffer before the second one has arrived. Thusly only the first transmission actually gets used by the subsequent processing function(IE processTransmission() ).

I guess it is also possible that the fault lies on the server side, which is to say that the underlying API sees fit to save some bandwidth by packing two small transmissions into one, instead of sending straight away. This seems unlikely though.

Now, what I really want to ask is this: Do I really have to parse the buffer after every recv in order to determine if there are more than one set of transmissions available?

Multithread in a Loop

I am presenting an "minimalist example" to try to understand how can i make multi-threading in C++11. So given this example:

std::thread t[total_threads];
for(int i = 0; i<total_threads; i++){
   t[i]= std::thread(&thread_function_1, random1, parameters1);
   t[i].join();
   t[i]= std::thread(&thread_function_2, random2, parameters2);
   t[i].join();
   t[i]= std::thread(&thread_function_2, random3, parameters3);
   t[i].join();
}

Obviously if I try to debugg this code I will have abortion errors. Since is not possible to use the same thread twice (I guess). One possible solution is to create an array with "millions" of threads to make it happen (and iterate between them). But I guess it is a bad solution. How can I make this efficiently, since I can not use the same thread twice?

what are the options for programming an open vswitch (ovs) in C/C++?

I want configure/program an open vswitch. I am aware that I can use ovs-vsctl like commands on command line interface / bash. Also I know that ovs has interface for high level controllers like pox and ryu.

I was wondering if there are any other ways to configure/program an ovs. Maybe API's for languages like C/C++ ?

In-class initialisers using = for class templates

I apologise but I cannot understand why the following will not work (g++ 4.8.1):

#include <string>

using namespace std;

template <typename T> struct A{
    //A(): s("why") { } //fine
    //string s{"what"}; //also fine
    //A() = default; //(same error as below)
    string s = "why?!"; //error: conversion from 'const char [6]' to non-scalar type 'std::string {aka std::basic_string<char>}' requested|
};

struct B{
    string s = "why?!"; //all good
};

int main(){
    A<int> a;
    B b;
}

For some reason by introducing a template I'm unable to use = for the in-class initializer of the string s. Built-in types work and indeed I'm able to circumvent it by using braces or explicitly intialising in the default constructor. Why does it kick up a fuss about using =?

C++ template with no template parameters?

I hate the boilerplate and Don't Repeat Yourself violations inherent in traditional class declarations in C++.

Is it possible to create a template with no template parameters, purely to enable the class to be defined in a header file without violating the One Definition Rule, in C++11?

Problems on creating a static map as a class member [duplicate]

This question already has an answer here:

At the moment I'm programming a 2D game framework with SDL and I have a problem with my sprite handler. I need a static map for my loaded textures.

SpriteHandler.cpp:

#include "SpriteHandler.h"


SpriteHandler::SpriteHandler(SDL_Renderer* rendere)
{
    renderer = rendere;
    console = new ConsoleHandler("SpriteHandler");
    console->printInfo("Initialisation ..");
}

bool SpriteHandler::RegisterTexture(int uuid, std::string file){
    std::string path = "./assets/textures/" + file;
    if (textures.count(uuid)){
        console->printWarning("UUID " + std::to_string(uuid) + " already registered! Skipping ..");
        return false;
    }
    if (!FileExists(path)){
        console->printWarning("Texture '" + file + "' cannot be found. Skipping ..");
        return false;
    }

    SDL_Texture* sprite = SDL_CreateTextureFromSurface(renderer, IMG_Load(path.c_str()));
    textures[uuid] = sprite;

    console->printInfo("Loaded " + file);

    return true;
}

bool SpriteHandler::FileExists(std::string StrFilename){
    GetFileAttributes(StrFilename.c_str());
    if (0xffffffff == GetFileAttributes(StrFilename.c_str()))
        return false;
    return true;
}

SpriteHandler::~SpriteHandler()
{
}

SpriteHandler.h:

#include <map>
#include <SDL.h>
#include <SDL_image.h>
#include <string>
#include <Windows.h>

#include "ConsoleHandler.h"

#pragma once
class SpriteHandler
{
private:
    static std::map<int, SDL_Texture*> textures; //Here the error occurs

    ConsoleHandler* console;
    SDL_Renderer* renderer;

    bool FileExists(std::string StrFilename);
public:
    SpriteHandler(SDL_Renderer* rendere);
    bool RegisterTexture(int uuid, std::string file);
    ~SpriteHandler();
};

Nothing special but I get a compiler error when I try to compile:

SpriteHandler.obj : error LNK2001: unresolved external symbol "private: static class std::map<int,struct SDL_Texture *,struct std::less<int>,class std::allocator<struct std::pair<int const ,struct SDL_Texture *> > > SpriteHandler::textures" (?textures@SpriteHandler@@0V?$map@HPAUSDL_Texture@@U?$less@H@std@@V?$allocator@U?$pair@$$CBHPAUSDL_Texture@@@std@@@3@@std@@A)

BTW: Sorry for bad English.

Equivalent of "typename", to indicate that a dependant name is indeed a 'template template parameter'

We reduced a portion of code we cannot find the right syntax for to a minimal example.

Let's assume the following definitions (worry not about the "why" ;)

template <class>
class Element
{};

template <template <class> class>
class Client
{};

template <class>
struct TemplatedProvider
{
    template <class T>
    using element_template = Element<T>;
};

Now, with C++11 onward, we can use either a class template or a type alias template to instantiate the Client template. The following function compiles just fine:

void fun()
{
    Client<Provider::element_template> client;
    Client<TemplatedProvider<int>::element_template> clientBis;
}

But we cannot find the proper syntax in the following case, when the template argument given to Client is a dependent name:

template <class T>
void templatedFun()
{
    Client<TemplatedProvider<T>::element_template> client;
}

Clang (tested with 3.6) is emitting the following compilation error:

template argument for template template parameter must be a class template or type alias template

Can we fix this syntax ?

const double & in template class partial specialization

Suppose the following definitions:

#define AA(x) A<decltype(x), x>

template<typename T, T x>
struct A;

template<int a>
struct A<int, a>{};

template<bool b>
struct A<bool, b>{};

template<const double &d>
struct A<const double &, d>{};

extern constexpr double myDouble = 0.2;

After these definitions, the following works:

AA(false) myA2; 

However, the compiler complains when it sees this:

AA(myDouble) myA3;

It says:

‘const double’ is not a valid type for a template non-type parameter

#define AA(x) A

On the other hand, the compiler is perfectly happy with this:

A<const double &, myDouble> myA1; 

What is the reason for this compiler error? (using g++ version 4.8.2)

How to serialize TAO::unbouded_basic_string_sequence

This does not work:

    template <class Archive, typename T>
    inline void save(Archive& arch, const TAO::unbounded_basic_string_sequence<T>& varSequence, unsigned int version)
    {
        size_t length = varSequence.length();
        arch & length & make_array(varSequence.get_buffer(), length);
    }

    template <class Archive, typename T>
    void load(Archive& arch, TAO::unbounded_basic_string_sequence<T>& varSequence, unsigned int version)
    {
        size_t length;
        arch & length;

        varSequence.length(length);
        arch & make_array(varSequence.get_buffer(), length);
    }


    template <class Archive, typename T>
    inline void serialize(Archive& arch, TAO::unbounded_basic_string_sequence<T>& varSequence, const unsigned int version)
        {
            split_free(arch, varSequence, version);
        }

The compiller says:

(..)/include/boost/serialization/access.hpp:118:9: error: request for member 'serialize' in 't', which is of non-class type 'char'

I know that C-style strings are not supported by boost::serialization. Theoretically I could use std::string for save(), but I do not know how to go back from std::string to TAO::unbouded_basic_string_sequence - there's almost no documentation for this class.

std::thread context of execution (c++14)

The problem appear when an in/out variable of a function called by std::thread changes the value during the execution...


Function:

static int func(stThread_t *&pStThread)


Parameters

pStThread: It´s a struct that has a pointer to std::thread and other variables (some flags)

typedef struct stThread {
   stThread() noexcept {...};    
   stThread(const stThread &cRigth) noexcept {...};    
   stThread & operator = (const stThread &cRigth) noexcept {...};

   std::thread *pThread;
   volatile bool bBegin;
   volatile bool bEnd;

 } stThread_t;

The function func print the address of the std::thread of the parameter pStThread and the thread id

func before 1785280 this_id 21968

after making an this_thread::sleep for 2 seconds, it print it again

func afer ... this_id 21968

   static int func(stThread_t *&pStThread) {

      std::thread::id this_id = std::this_thread::get_id();

      long long p_begin = (long long)pStThread;
      std::cout << "func before " << std::to_string(p_begin) << " this_id " << this_id << "\n";
      std::cout.flush();

      pStThread->bBegin = true;

      std::this_thread::sleep_for(std::chrono::milliseconds(2000));

      this_id = std::this_thread::get_id();
      long long p_end = (long long)pStThread;
      std::cout << "func afer " << std::to_string(p_end) << " this_id " << this_id << "\n";
      std::cout.flush();

      pStThread->bEnd = true;

      return 1;
   };

The address of the pointer to std::thread it´s changed (corrutped, deleted..?)


The pStThread is pushing_back of a list of pointer struct stThread_t

std::list<stThread_t*> listOfThreads;
listOfThreads.push_back(pStThread);

I read about std::move, but does not work with pointers


At the end there is a thread "garbage collector" that it is trying to erase all the threads pending of execution.


Full code here

#include <string>
#include <list>
#include <vector>
#include <map>
#include <thread>
#include <mutex>
#include <atomic>

#include <iostream>

typedef struct stThread {
   stThread() noexcept {
      pThread = NULL;
      bBegin = false;
      bEnd = false;
   };

   stThread(const stThread &cRigth) noexcept {
      this->pThread = cRigth.pThread;
      this->bBegin = (bool)cRigth.bBegin;
      this->bEnd = (bool)cRigth.bEnd;
   };

   stThread & operator = (const stThread &cRigth) noexcept {
      this->pThread = cRigth.pThread;
      this->bBegin = (bool)cRigth.bBegin;
      this->bEnd = (bool)cRigth.bEnd;

      return *this;
   };

   std::thread *pThread;
   volatile bool bBegin;
   volatile bool bEnd;

} stThread_t;

class CMain
{
public:
   typedef std::list<stThread_t*> MyList_threads;
   MyList_threads listOfThreads;

public:
   CMain() {

      std::cout << std::boolalpha << "Ex1 is move-constructible? "
         << std::is_move_constructible<stThread_t>::value << '\n'
         << "Ex1 is trivially move-constructible? "
         << std::is_trivially_move_constructible<stThread_t>::value << '\n'
         << "Ex1 is nothrow move-constructible? "
         << std::is_nothrow_move_constructible<stThread_t>::value << '\n'
         << "Ex2 is trivially move-constructible? "
         << std::is_trivially_move_constructible<stThread_t>::value << '\n'
         << "Ex2 is nothrow move-constructible? "
         << std::is_nothrow_move_constructible<stThread_t>::value << '\n';
   };

   static int func(stThread_t *&pStThread) {

      std::thread::id this_id = std::this_thread::get_id();

      long long p_begin = (long long)pStThread;
      std::cout << "func before " << std::to_string(p_begin) << " this_id " << this_id << "\n";
      std::cout.flush();

      pStThread->bBegin = true;

      std::this_thread::sleep_for(std::chrono::milliseconds(2000));

      this_id = std::this_thread::get_id();
      long long p_end = (long long)pStThread;
      std::cout << "func afer " << std::to_string(p_end) << " this_id " << this_id << "\n";
      std::cout.flush();

      pStThread->bEnd = true;

      return 1;
   };

   int _createThreads() {
      for (int iIdx = 0; (iIdx < 5); iIdx++) {
         stThread_t *pStThread = new stThread_t;

         pStThread->pThread = new std::thread(&CMain::func,
            std::ref(pStThread));

         if (pStThread) {
            do {
               std::this_thread::sleep_for(std::chrono::milliseconds(100));
            } while (!pStThread->bBegin);
            listOfThreads.push_back(pStThread);

            std::string sLog;
            sLog = "\nlistOfThreads.push_back " + std::to_string((long long)pStThread) + "\n";
            std::cout << sLog;
            std::cout.flush();
         }

         std::this_thread::sleep_for(std::chrono::milliseconds(1));
      }
      return 1;
   };

   int _main() {

      _createThreads();

      std::thread thread_collector([=]() {
         bool bEnd = false;
         MyList_threads::iterator it;
         it = listOfThreads.end();

         do {
            stThread_t *pStThread = NULL;

            if (it == listOfThreads.end()) {
               it = listOfThreads.begin();
               if (it == listOfThreads.end()) bEnd = true;
            }
            else it++;

            if (it != listOfThreads.end()) {
               if ((*it)->bEnd) {
                  pStThread = *it;

                  listOfThreads.erase(it);
                  it = listOfThreads.begin();
               }
            }

            if (pStThread) {
               if (pStThread->pThread) {
                  if (pStThread->pThread->joinable()) {
                     pStThread->pThread->join();

                     std::cout << " element deleted  " << std::to_string((long long)pStThread) << "\n";
                     std::cout.flush();
                  }
                  delete pStThread->pThread;
                  pStThread->pThread = NULL;
               }
               delete pStThread;
            }
            pStThread = NULL;


            std::this_thread::sleep_for(std::chrono::milliseconds(1));

         } while (!bEnd);
      });



      if (thread_collector.joinable()) {
         thread_collector.join();
      }

      return 1;
   };
};

int main()
{
   CMain _main;
   _main._main();

   return 0;
}

Unordered map vs vector

I'm building a little 2d game engine. Now I need to store the prototypes of the game objects (all type of informations). A container that will have at most I guess few thousand elements all with unique key and no elements will be deleted or added after a first load. The key value is a string.

Various threads will run, and I need to send to everyone a key(or index) and with that access other information(like a texture for the render process or sound for the mixer process) available only to those threads.

Normally I use vectors because they are way faster to accessing a known element. But I see that unordered map also usually have a constant speed if I use the ::at element access. It would make the code much cleaner and also easier to maintain because I will deal with much more understandable man made strings.

So the question is, the difference in speed between a access to a vector[n] compared to a unorderedmap.at("string") is negligible compared to his benefits?

From what I understand accessing various maps in different part of the program, with different threads running just with a "name" for me is a big deal and the speed difference isn't that great. But I'm too inexperienced to be sure of this. Although I found informations about it seem I can't really understand if I'm right or wrong.

Thank you for your time.