mercredi 31 mai 2017

Is it possible to determine if a parameter of a function is signed or unsigned?

There are ways to determine if a function exists, and there are ways to determine if a function has a particular signature. But is there a way to determine if it has a signature that contains a signed or unsigned parameter while the name may be overloaded?

Example

struct A {
 void fn(int) {}
};

struct B {
 void fn(unsigned) {}
};

struct C {
 void fn(int) {}
 void fn(unsigned) {}
};

The closest I could think that this would be possible is if I tested specifically for every signed type, and then if not found, every unsigned type. That will however, exclude any enum type or new type in the future.

When is an rvalue evaluated?

So I understand that s2 binds to the expression s1 + s1, but is this evaluated at the time s2 is assigned or is it lazy and evaluated when s2 += "Test"; is called? And also would s2 hold memory for a temporary string?

#include <iostream>
#include <string>

int main()
{
    std::string s1 = "Test";
    std::string&& s2 = s1 + s1;
    s2 += "Test";
    std::cout << s2 << '\n';
}

Why std::make_unique

My code:

t = std::make_unique<std::thread>(std::bind(&Widget::generateNum, this));

crash at ~thread() , error msg is 'r6010 abort() has been called'

Dependent lookup in decltype on return type fails to compile

I've been playing with trailing return types that resolve to the same type, with a different expression, but resolves to something legal. This works:

template <typename>
struct Cls {
  static std::size_t f();
};

template <typename T>
auto Cls<T>::f() -> decltype(std::size_t{}) { return 0; }

But if I change the definition to something that should be equivalent, it fails

template <typename T>
auto Cls<T>::f() -> decltype(sizeof(T)) { return 0; }

clang's error (gcc is similar):

error: return type of out-of-line definition of 'Cls::f' differs from that in the declaration
auto Cls<T>::f() -> decltype(sizeof(T)) { return 0; }
             ^
note: previous declaration is here
  static std::size_t f();
         ~~~~~~~~~~~ ^

If I replace sizeof(T) with sizeof(int) it compiles successfully. Why is it illegal with a dependent type only?

Compiling error '/usr/bin/ld: cannot find -lgmpxx'

I've installed GMP 6.1.2, I'm using gcc 5.4, I'm running Ubuntu 16.04.1. I'm compiling a .cpp file that uses gmpxx using g++ -std=c++11 -o code -I/path/to/file code.cpp -lgmpxx -lgmp, after running I obtain the error

/usr/bin/ld: cannot find -lgmpxx collect2: error: ld returned 1 exit status

I've read all the threads I could find for this problem but in my case nothing seemed to worked, others usually didn't have the library installed or had to use -L to indicate the library location, none of these worked for me. The file that needs to be searched is gmpxx.h.

In addition, I use the same command to compile in another computer and it works, the only difference is -std=c++11 included in the command shown but this is due to the gcc version I'm using.

Hash table doesn't read last line off of test file

I was assigned to create a chained hash table using a vector of vectors. It is designed to hold objects of type Entry. I have written all of the functions and the constructor but when I try to use the constructor that reads an input and then output it back to me in order of keys, whichever string was on the last line of the .txt file its reading from is gone. I think its a problem with my constructor because when I try to use get to get that specific value from the table before printing it its gone. I was hoping for some insight to where I might be going wrong from someone with a little more experience. Thanks. Heres my code:

Entry Header File:

#ifndef entry_h
#define entry_h

// entry.h - defines class Entry            


#include <string>
#include <iosfwd>

class Entry {

public:
    // constructor                                          
    Entry(unsigned int key = 0, std::string data = "");

    // access and mutator functions                         
    unsigned int get_key() const;
    std::string get_data() const;
    static unsigned int access_count();
    void set_key(unsigned int k);
    void set_data(std::string d);

    // operator conversion function simplifies comparisons  
    operator unsigned int () const;

    // input and output friends                             
    friend std::istream& operator>>
    (std::istream& inp, Entry &e);
    friend std::ostream& operator<<
    (std::ostream& out, Entry &e);

private:
    unsigned int key;
    std::string data;
    static unsigned int accesses;
};

#endif /* entry_h */

Table header file:

//
//  table.h
//  
//
#ifndef table_h
#define table_h

#include <string>
#include <vector>
#include <algorithm>
#include "entry.h"

using namespace std;

class Table {

 public:
  Table(unsigned int max_entries = 100);
  //Builds empty table to hold 100 entries
  Table(unsigned int entries, std::istream& input);
  //Builds table to hold entries, reads and puts them 1 at a time
  ~Table();
  //Destructor
  void put(unsigned int key, std::string data);
  //Creates new entry for the table
  //Updates if key is used
  void put(Entry e);
  //Creates a copy of e in the table
  string get(unsigned int key) const;
  //Returns string associated with key
  //Returns empty string if key isnt used
  bool remove(unsigned int key);
  //Removes entry in given key
  //Returns true of removed, false of no entry
  int find(Entry e);
  //index in second array that e exists, 0 if not found
  friend std::ostream& operator<< (std::ostream& out, const Table& t);
  //Prints each entry in the table in order of their key


 private:
  int size;
  int num_entries;
  unsigned int hashkey(unsigned int key) const;

  vector<vector<Entry> > A;
};

#endif /* table_h */

Table Implementation File:

//table.cpp

#include<iostream>
#include<vector>
#include<algorithm>
#include "table.h"

using namespace std;


Table::Table(unsigned int max_entries){
  max_entries = 100;
  size = max_entries * 2;
  A.resize(size);
}

Table::Table(unsigned int entries, std::istream& input){
  size = entries*2;
  A.resize(size);
  num_entries = entries;
  Entry temp;
  for (size_t i = 0; i < entries; i++) {
    input >> temp;
    put(temp);
  }
}

/*
Table::~Table() {
  for (int i = 0; i <size; i++) {
    for (int j = 0; j < A[i].size(); j++) {
      delete A[i][j];
    }
  }
  }*/

Table::~Table() {
  A.clear();
}

void Table::put(unsigned int key, std::string data){
  Entry e;
  e.set_key(key);
  e.set_data(data);
  put(e);
  num_entries++;
}

void Table::put(Entry e) {
  /*if (!A[hashkey(e.get_key())].empty()) {
  // if (find(e) != 0) {
    for(int i = 0; i < A[hashkey(e.get_key())].size(); i++) {
      if(A[hashkey(e.get_key())][i].get_key() == e.get_key()){
    A[hashkey(e.get_key())][i] = e;
    return;
      }
    }
  }
  else {
    A[hashkey(e.get_key())].push_back(e);
    num_entries++;
    }*/

  if (A[hashkey(e.get_key())].empty()) {
    A[hashkey(e.get_key())].push_back(e);
    }
  else {
    for(size_t i = 0; i < A[hashkey(e.get_key())].size(); i++) {
    if (A[hashkey(e.get_key())][i].get_key() == e.get_key()) {
      remove(A[hashkey(e.get_key())][i].get_key());
      break;
    }
      }
   A[hashkey(e.get_key())].push_back(e);
  } 
}

string Table::get(unsigned int key) const {
  if( A[hashkey(key)].size() == 0) {
    return "";
  }
  else {
    for (size_t i = 0; i < A[hashkey(key)].size(); i++) {
      if (A[hashkey(key)][i].get_key() == key) {
    return A[hashkey(key)][i].get_data();
      }
      else {
    return "";
      }
    }
  }
}

bool Table::remove(unsigned int key) {
  for (size_t i = 0; i < A[hashkey(key)].size(); i++) {
    if (A[hashkey(key)][i].get_key() == key) {
    swap(A[hashkey(key)][i],A[hashkey(key)][A[hashkey(key)].size() - 1]);
    A[hashkey(key)].pop_back();
    num_entries--; 
        return true;
      }
      else {
    return false;
      }
  }
}

int Table::find(Entry e) {
  for (size_t i = 0; i < A[hashkey(e.get_key())].size(); i++) {
      if (A[hashkey(e.get_key())][i] == e) {
    return i;
      }
      else {
    return 0;
      }
  }
}

ostream& operator << (ostream& out, const Table& t) {
  vector<Entry> order;
  for(size_t i = 0; i < t.A.size(); i++) {
    for (size_t j = 0; j < t.A[i].size(); j++) {
      order.push_back(t.A[i][j]);
    }
  }
  sort(order.begin(), order.end());
  for(Entry k: order) {
    out << k << endl;
  }
  return out;
}

unsigned int Table::hashkey(unsigned int key) const{
  const double c = 1.61803;
  // return key % size;
  return (int)(size*((key * c) - (int)(key * c)));
}

How to avoid possible object slicing when storing derived classes in a vector

I have a base class called Platform. It has some derived classes like Game, Book, Series, etc. I'm currently making a database like program, and I want to store all my objects in a vector, each row of that vector creates another vector, and that vector will be associated with a single platform. Since i want this to be more dynamic when I add more platforms and such. The issue is that I believe i have object slicing when I go and do this.

my Platform base class has a virtual getName() and setName() method with a protected string variable called name.

My derived Book class of course recreates the getName() and setName() methods without virtual and to suit the class's criteria. I also added getPage() and setPage() methods to represent the number of Pages inside of the book.

vector<*Platform> platforms
vector<vector<Platform*>> database;
Book tmpBook;
tmpBook.setName("ANYNAME");
tmpBook.setPage(376);
platforms.push_back(&tmpBook);
database.push_back(platforms);
cout << database[0][0]->getName() << database[0][0]->getPage() << endl;

expecting output of ANYNAME 376, but apparently theres an issue with the getPage command, my first fear was that object slicing has occurred. ERROR: CLASS PLATFORM HAS NO MEMBER NAMED 'getPage' So please tell me has object slicing occurred here, or am i missing something crucial but simple?

What is the solution to my problem, will I have to use unique pointers or shared pointers or boost or something? If so how would I model that?

Inserting into a map that has atomic key and value types in C++

In the following snippet:

#include <map>
#include <atomic>
#include <utility>

int main()
{

    std::map<std::atomic<int>, std::atomic<int>, std::greater<std::atomic<int>>> a_map;

    std::atomic<int> a_key;
    a_key.store(5);
    std::atomic<int> a_val;
    a_val.store(566);

    a_map.insert(std::make_pair(a_key, a_val));
}

Edit: This question was marked duplicate by a user, but the other question was for a class. I only have a std::map. Can someone please explain what is wrong here??

Why is the insert line giving a long list of cryptic errors?

g++ -std=c++11 test.cpp 
In file included from /usr/include/c++/5/bits/stl_algobase.h:64:0,
                 from /usr/include/c++/5/bits/stl_tree.h:63,
                 from /usr/include/c++/5/map:60,
                 from test.cpp:1:
/usr/include/c++/5/bits/stl_pair.h: In instantiation of ‘constexpr std::pair<_T1, _T2>::pair(const _T1&, const _T2&) [with _T1 = std::atomic<int>; _T2 = std::atomic<int>]’:
/usr/include/c++/5/bits/stl_pair.h:281:72:   required from ‘constexpr std::pair<typename std::__decay_and_strip<_Tp>::__type, typename std::__decay_and_strip<_T2>::__type> std::make_pair(_T1&&, _T2&&) [with _T1 = std::atomic<int>&; _T2 = std::atomic<int>&; typename std::__decay_and_strip<_T2>::__type = std::atomic<int>; typename std::__decay_and_strip<_Tp>::__type = std::atomic<int>]’
test.cpp:15:45:   required from here
/usr/include/c++/5/bits/stl_pair.h:113:31: error: use of deleted function ‘std::atomic<int>::atomic(const std::atomic<int>&)’
       : first(__a), second(__b) { }
                               ^
In file included from test.cpp:2:0:
/usr/include/c++/5/atomic:612:7: note: declared here
       atomic(const atomic&) = delete;
       ^
In file included from /usr/include/c++/5/bits/stl_algobase.h:64:0,
                 from /usr/include/c++/5/bits/stl_tree.h:63,
                 from /usr/include/c++/5/map:60,
                 from test.cpp:1:
/usr/include/c++/5/bits/stl_pair.h:113:31: error: use of deleted function ‘std::atomic<int>::atomic(const std::atomic<int>&)’
       : first(__a), second(__b) { }
                               ^
In file included from test.cpp:2:0:
/usr/include/c++/5/atomic:612:7: note: declared here
       atomic(const atomic&) = delete;
       ^
In file included from /usr/include/c++/5/bits/stl_algobase.h:64:0,
                 from /usr/include/c++/5/bits/stl_tree.h:63,
                 from /usr/include/c++/5/map:60,
                 from test.cpp:1:
/usr/include/c++/5/bits/stl_pair.h: In instantiation of ‘constexpr std::pair<typename std::__decay_and_strip<_Tp>::__type, typename std::__decay_and_strip<_T2>::__type> std::make_pair(_T1&&, _T2&&) [with _T1 = std::atomic<int>&; _T2 = std::atomic<int>&; typename std::__decay_and_strip<_T2>::__type = std::atomic<int>; typename std::__decay_and_strip<_Tp>::__type = std::atomic<int>]’:
test.cpp:15:45:   required from here
/usr/include/c++/5/bits/stl_pair.h:281:72: error: use of deleted function ‘constexpr std::pair<_T1, _T2>::pair(std::pair<_T1, _T2>&&) [with _T1 = std::atomic<int>; _T2 = std::atomic<int>]’
       return __pair_type(std::forward<_T1>(__x), std::forward<_T2>(__y));
                                                                        ^
/usr/include/c++/5/bits/stl_pair.h:128:17: note: ‘constexpr std::pair<_T1, _T2>::pair(std::pair<_T1, _T2>&&) [with _T1 = std::atomic<int>; _T2 = std::atomic<int>]’ is implicitly deleted because the default definition would be ill-formed:
       constexpr pair(pair&&) = default;
                 ^
/usr/include/c++/5/bits/stl_pair.h:128:17: error: use of deleted function ‘std::atomic<int>::atomic(const std::atomic<int>&)’
In file included from test.cpp:2:0:
/usr/include/c++/5/atomic:612:7: note: declared here
       atomic(const atomic&) = delete;
       ^
In file included from /usr/include/c++/5/bits/stl_algobase.h:64:0,
                 from /usr/include/c++/5/bits/stl_tree.h:63,
                 from /usr/include/c++/5/map:60,
                 from test.cpp:1:
/usr/include/c++/5/bits/stl_pair.h:128:17: error: use of deleted function ‘std::atomic<int>::atomic(const std::atomic<int>&)’
       constexpr pair(pair&&) = default;
                 ^
In file included from test.cpp:2:0:
/usr/include/c++/5/atomic:612:7: note: declared here
       atomic(const atomic&) = delete;
       ^
test.cpp: In function ‘int main()’:
test.cpp:15:46: error: no matching function for call to ‘std::map<std::atomic<int>, std::atomic<int>, std::greater<std::atomic<int> > >::insert(std::pair<std::atomic<int>, std::atomic<int> >)’
     a_map.insert(std::make_pair(a_key, a_val));
                                              ^
In file included from /usr/include/c++/5/map:61:0,
                 from test.cpp:1:
/usr/include/c++/5/bits/stl_map.h:612:7: note: candidate: std::pair<typename std::_Rb_tree<_Key, std::pair<const _Key, _Tp>, std::_Select1st<std::pair<const _Key, _Tp> >, _Compare, typename __gnu_cxx::__alloc_traits<_Alloc>::rebind<std::pair<const _Key, _Tp> >::other>::iterator, bool> std::map<_Key, _Tp, _Compare, _Alloc>::insert(const value_type&) [with _Key = std::atomic<int>; _Tp = std::atomic<int>; _Compare = std::greater<std::atomic<int> >; _Alloc = std::allocator<std::pair<const std::atomic<int>, std::atomic<int> > >; typename std::_Rb_tree<_Key, std::pair<const _Key, _Tp>, std::_Select1st<std::pair<const _Key, _Tp> >, _Compare, typename __gnu_cxx::__alloc_traits<_Alloc>::rebind<std::pair<const _Key, _Tp> >::other>::iterator = std::_Rb_tree_iterator<std::pair<const std::atomic<int>, std::atomic<int> > >; std::map<_Key, _Tp, _Compare, _Alloc>::value_type = std::pair<const std::atomic<int>, std::atomic<int> >]
       insert(const value_type& __x)
       ^
/usr/include/c++/5/bits/stl_map.h:612:7: note:   no known conversion for argument 1 from ‘std::pair<std::atomic<int>, std::atomic<int> >’ to ‘const value_type& {aka const std::pair<const std::atomic<int>, std::atomic<int> >&}’
/usr/include/c++/5/bits/stl_map.h:620:9: note: candidate: template<class _Pair, class> std::pair<typename std::_Rb_tree<_Key, std::pair<const _Key, _Tp>, std::_Select1st<std::pair<const _Key, _Tp> >, _Compare, typename __gnu_cxx::__alloc_traits<_Alloc>::rebind<std::pair<const _Key, _Tp> >::other>::iterator, bool> std::map<_Key, _Tp, _Compare, _Alloc>::insert(_Pair&&) [with _Pair = _Pair; <template-parameter-2-2> = <template-parameter-1-2>; _Key = std::atomic<int>; _Tp = std::atomic<int>; _Compare = std::greater<std::atomic<int> >; _Alloc = std::allocator<std::pair<const std::atomic<int>, std::atomic<int> > >]
         insert(_Pair&& __x)
         ^
/usr/include/c++/5/bits/stl_map.h:620:9: note:   template argument deduction/substitution failed:
/usr/include/c++/5/bits/stl_map.h:616:32: error: no type named ‘type’ in ‘struct std::enable_if<false, void>’
       template<typename _Pair, typename = typename
                                ^
/usr/include/c++/5/bits/stl_map.h:633:7: note: candidate: void std::map<_Key, _Tp, _Compare, _Alloc>::insert(std::initializer_list<std::pair<const _Key, _Tp> >) [with _Key = std::atomic<int>; _Tp = std::atomic<int>; _Compare = std::greater<std::atomic<int> >; _Alloc = std::allocator<std::pair<const std::atomic<int>, std::atomic<int> > >]
       insert(std::initializer_list<value_type> __list)
       ^
/usr/include/c++/5/bits/stl_map.h:633:7: note:   no known conversion for argument 1 from ‘std::pair<std::atomic<int>, std::atomic<int> >’ to ‘std::initializer_list<std::pair<const std::atomic<int>, std::atomic<int> > >’
/usr/include/c++/5/bits/stl_map.h:662:7: note: candidate: std::map<_Key, _Tp, _Compare, _Alloc>::iterator std::map<_Key, _Tp, _Compare, _Alloc>::insert(std::map<_Key, _Tp, _Compare, _Alloc>::const_iterator, const value_type&) [with _Key = std::atomic<int>; _Tp = std::atomic<int>; _Compare = std::greater<std::atomic<int> >; _Alloc = std::allocator<std::pair<const std::atomic<int>, std::atomic<int> > >; std::map<_Key, _Tp, _Compare, _Alloc>::iterator = std::_Rb_tree_iterator<std::pair<const std::atomic<int>, std::atomic<int> > >; std::map<_Key, _Tp, _Compare, _Alloc>::const_iterator = std::_Rb_tree_const_iterator<std::pair<const std::atomic<int>, std::atomic<int> > >; std::map<_Key, _Tp, _Compare, _Alloc>::value_type = std::pair<const std::atomic<int>, std::atomic<int> >]
       insert(const_iterator __position, const value_type& __x)
       ^
/usr/include/c++/5/bits/stl_map.h:662:7: note:   candidate expects 2 arguments, 1 provided
/usr/include/c++/5/bits/stl_map.h:673:9: note: candidate: template<class _Pair, class> std::map<_Key, _Tp, _Compare, _Alloc>::iterator std::map<_Key, _Tp, _Compare, _Alloc>::insert(std::map<_Key, _Tp, _Compare, _Alloc>::const_iterator, _Pair&&) [with _Pair = _Pair; <template-parameter-2-2> = <template-parameter-1-2>; _Key = std::atomic<int>; _Tp = std::atomic<int>; _Compare = std::greater<std::atomic<int> >; _Alloc = std::allocator<std::pair<const std::atomic<int>, std::atomic<int> > >]
         insert(const_iterator __position, _Pair&& __x)
         ^
/usr/include/c++/5/bits/stl_map.h:673:9: note:   template argument deduction/substitution failed:
test.cpp:15:32: note:   cannot convert ‘std::make_pair<std::atomic<int>&, std::atomic<int>&>(a_key, a_val)’ (type ‘std::pair<std::atomic<int>, std::atomic<int> >’) to type ‘std::map<std::atomic<int>, std::atomic<int>, std::greater<std::atomic<int> > >::const_iterator {aka std::_Rb_tree_const_iterator<std::pair<const std::atomic<int>, std::atomic<int> > >}’
     a_map.insert(std::make_pair(a_key, a_val));
                                ^
In file included from /usr/include/c++/5/map:61:0,
                 from test.cpp:1:
/usr/include/c++/5/bits/stl_map.h:688:9: note: candidate: template<class _InputIterator> void std::map<_Key, _Tp, _Compare, _Alloc>::insert(_InputIterator, _InputIterator) [with _InputIterator = _InputIterator; _Key = std::atomic<int>; _Tp = std::atomic<int>; _Compare = std::greater<std::atomic<int> >; _Alloc = std::allocator<std::pair<const std::atomic<int>, std::atomic<int> > >]
         insert(_InputIterator __first, _InputIterator __last)
         ^
/usr/include/c++/5/bits/stl_map.h:688:9: note:   template argument deduction/substitution failed:
test.cpp:15:46: note:   candidate expects 2 arguments, 1 provided
     a_map.insert(std::make_pair(a_key, a_val));

When does C++11 give warnings about operator precedence?

When writing code, for a long time I knew that && has higher precedence than ||; however, compiling it using the C++11 standard gave me a warning that I should now use parentheses when using both in a single statement.

Now I got a warning that combining >> and + also should have parentheses. Now my statements look really ugly, with 5 or more parentheses floating around them.

1) Is there a resource that says which combinations of operators now require parentheses?

2) Is there a way to silence just the operator precedence warnings, but to keep the other warnings?

Compiler gcc with flags -O2 -Wall -g

The warnings came in when I added the flag -std=c++11

How to sort items in std::map by key's member variable? C++

here is an example. std::map<abc*, int>, at here abc is a class, so the key of the map is a pointer of class abc's object, the address of pointer changes for each running, therefore the order inside map is random. inside class abc, there is an ID member variable, for each object of class abc, ID is unique. My question: is it possible to let map sorts items by ID member variable instead by address of pointer. Thank you

What do they mean by having identity but not movable for Lvalue in C++ 11?

I am now studying C++ 11 and getting confused by value category of expressions in C++ 11. According to terminology the Lvalue is the top-left point of the W, that is iM (or i-m sometimes) meaning that "has identity but cannot be moved from". This really makes me confused. Please consider the example below:

#include <iostream>

int main()
{
    int a = 0, b = 1, c = 2;
    a = std::move(b = c);
    std::cout << a << '\n';
}

This example compiled well.

We all know that the assignment b = c is an Lvalue then what do they mean by 'cannot be moved from'? Please give examples that can clearly illustrate this!

Thanks!

If creating a generic template API that supports returning a variadic list of types, should I use std::tuple or something else?

So, I have a template API that I want to publish. This API returns a class type that contains a list of types.

In general, should I use std::tuple<> to specify this or should I use something else that may be more lightweight?

I think I've heard that std::tuple<> could result in slightly slower compile times. Is this true?

Purpose of non-member functions like atomic_store()

I read the documentation of atomic_store and I understand what it is doing. The question is rather why is this non-member function there? What does it provide what member function doesn't?

There is also a bunch of such functions here.

Is it possible to get a single element of a set in C++ STL?

I have the following C++ code with C++ STL vector,

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

int main ()
{   
    vector <int> v;

    for (int i=0; i<15; i++)
        v.push_back (i);

    cout << v[10] << endl;

    return 0;
}

It normally prints the element that is stored into the 10th index. The output be 10.

But I tried the same thing with C++ STL set also,

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

int main ()
{
    set <int> myset;

    for (int i=0; i<15; i++)
        myset.insert (i);

    cout << myset[10] << endl;

    return 0;
}

It gives me Compilation error showing the following messages :(

prog.cpp: In function ‘int main()’:

prog.cpp:12:18: error: no match for ‘operator[]’ (operand types are ‘std::set’ and ‘int’) cout << myset[10] << endl;

So, my question is, is there any way to print any element of STL sets alike the STL vectors in C++? if yes, how?

Meanwhile we can use iterators but it can work with the full set, as far I know. :)

c++ - Functional with operator()

Let say I have the following code:

template<typename T> Matrix{
  private:
    int nr;
    std::vector<T> data;
  public:
    T& operator()(const int& j, const int& k){
    return this->mat.at(j+k*nr);}

    const T& operator()(const int& j, const int& k) const {
    return this->mat.at(j+k*nr);}
};

At some point I need to create a function pointer associated to const T& operator()(const int& j) const to use it as an argument in another function. Using functional, I tried:

//#include<functional>
function<const double&(const Matrix<double>&, const int&, const int&)> coef=&Matrix<double>::operator();

and I have the following error:

 no viable conversion from '<overloaded function type>' to 'function<const double &(const
  Matrix<double> &, const int &, const int &)>

I cannot get it to work and it is pretty hard to find informations on function, since the name is quite used...

Why is std::abs(9484282305798401ull) = 9484282305798400?

It turns out that on C++17 (g++ 6.3.1),

#include <iostream>
#include <cmath>

int main()
{
    std::cout << (unsigned long long)std::abs(9484282305798401ull);
}

gives an incorrect output of 9484282305798400.

As I understood from cmath, std::abs first casts the argument into a double.

According to the C++ docs, double has 52 mantissa bits, which means that the maximum integer value that I must be strictly less than 2^52 = 4503599627370496 before any loss of precision.

Am I correct to say that since 9484282305798401 exceeds this limit, std::abs ends up discarding precision to give an incorrect answer?

Multiple RenderWindows in VTK

After searching for quite a while how to have multiple completly independent renderwindows with independent interactors, I only found this: http://ift.tt/2rEQsAT

But that example just states as a question what will happen and doesn't bother to explain how that works. I am calling ->Start() on the last array element and then all start simultaniously? Is that the only way to do it? And why does it even work?

When I try to adapt the code, only the last of the renderwindows actually opens and starts interaction (as you would expect):

pC.UpdateInterface();
pC.InitializeVisualization();

ModelWindow mv;

std::vector<vtkSmartPointer<vtkRenderWindowInteractor> > interactors;
interactors.push_back(pointCloud.renderWindowInteractor);
interactors.push_back(mv.renderWindowInteractor);
interactors[1]->Start();

only starts the mv window.

This:

pC.renderWindowInteractor->Start();
mv.renderWindowInteractor->Start();

also doesn't work, since the first renderWindowInteractor is blocking and the second Start() only gets called when I close the first window.

Adding definition in CMakeLists.txt gives Segmentation fault (core dumped)

I enabled the C++11 support in CMakeLists.txt by using the

add_definitions(-std=c++11)  

Once recompiled and run I get surprisingly

Segmentation fault (core dumped)

In CMakeLists.txt C++11 support is enabled using the add_definitions

add_definitions(${PCL_DEFINITIONS})

add_definitions(-std=c++11)

Question, Is there any other way to include add_definitions or any suggestions what's wrong here ?

Function definition not being recognized by function body

I've created a class called Payload, and have a std::vector<Payload> in a class called LineShape. I've also created a function inside LineShape to get a Payload from the std::vector at a given index. This is Payload:

payload.h

class Payload {
public:

Payload (payload_type pType) {
    type = pType;
}

payload_type getPayloadType() {
    return type;
}

private:
    payload_type type;
};

and the function that is causing problems:

LineShape.h

    Payload getPayloadAt(int index) {
        return transfer.at(index);
    }

Visual Studio returns the following error:

C2334    unexpected token(s) preceding '{'; skipping apparent function body

Apparently, this means it isn't recognizing the body of the function, as a function, due to the definition of the function, but it seems okay?

Can't find what's wrong in this project

This project is about to realize a Stack based on C++11.

When I trying to complie this project, there are something wrong and I don't know why.

  • Here are the codes:

Stack.h

#include<iostream>
using std::size_t;
template <typename T>
struct Node {
    Node* next;
    T data;
    Node(T arg = 0) :data(arg), next(nullptr) { }
};

template <typename T>
class Stack {
public:
    Stack() :head(new Node<T>()), size(0) { }
    ~Stack();
    Stack& operator=(const Stack&);
    Stack(const Stack&);
    bool push(const T&);
    bool pop();
    const T get_top();
    bool isEmpty();
    Node<T>* begin();
    Node<T>* end();
private:
    Node<T>* head;
    size_t size;
    Node<T>* getEnd();
    Node<T>* getBeforeEnd();
    void free();
    void copy_from(const Stack&);
};

Stack.cpp

#include"Stack.h"
template<typename T>
Node<T>* Stack<T>::begin()
{
    if (head->next)
        return head->next;
    else
        return nullptr;
}
template<typename T>
Node<T>* Stack<T>::end()
{
    return getEnd()->next;
}
template<typename T>
Node<T>* Stack<T>::getEnd()
{
    if (!head->next)
        return nullptr;
    Node<T> *end = head->next;
    while (end->next)
        end = end->next;
    return end;
}
template<typename T>
Node<T>* Stack<T>::getBeforeEnd()
{
    int num = 0;
    auto* p = head;
    while (num < size - 1)
    {
        p = p->next;
        ++num;
    }
    return p;
}
template<typename T>
void Stack<T>::free()
{
    Node<T>* end = getEnd();
    while (end != head)
    {
        Node<T>* temp = head;
        head = head->next;
        delete temp;
    }
    delete head;
    size = 0;
}
template<typename T>
Stack<T>::~Stack<T>()
{
    free();
}
template<typename T>
void Stack<T>::copy_from(const Stack<T>& rhs)
{
    Node<T>* Head = new Node<T>;
    auto* First = Head;
    auto* beg = rhs.begin();
    while (beg != rhs.end())
    {
        Node<T>* Next = new Node<T>;
        Next->data = beg->data;
        Head->next = Next;
        Head = Next;
        beg = beg->next;
    }
    this->head = First;
    this->size = rhs.size;
}
template<typename T>
Stack<T>& Stack<T>::operator=(const Stack& rhs)
{
    if (&rhs != this)
    {
        free();
        copr_from(rhs);
    }
    return *this;
}
template<typename T>
Stack<T>::Stack(const Stack& s)
{
    free();
    copy_from(s);
    size = s.size;
}
template<typename T>
bool Stack<T>::push(const T& e)
{
    auto* end = getEnd();
    Node<T>* tail = new Node<T>;
    tail->data = e;
    end->next = tail;
    ++size;
    return true;
}
template<typename T>
bool Stack<T>::pop()
{
    auto* p = getBeforeEnd();
    auto* temp = p->next;
    p->next = nullptr;
    delete temp;
    size -= 1;
    return true;
}
template<typename T>
const T Stack<T>::get_top()
{
    const T e = getEnd()->data;
    return e;
}

template<typename T>
bool Stack<T>::isEmpty()
{
    return (head->next) ? true : false;
}

Main

#include"Stack.h"
#include<string>
#include<iostream>
using namespace std;

int main()
{
    Stack<string> s;
    string word;
    while (cin >> word)
        s.push(word);
    while (!s.isEmpty())
    {
        cout << s.get_top() << endl;
        s.pop();
    }
    return 0;
}

I use VS2017 to complie this project, here are the complie errors:

Error

std::weak_ptr assignment with std::make_shared

I stumbled upon this behaviour when using std::weak_ptr and std::make_shared and I found it a little weird. I am using C++11.

#include <iostream>
#include <memory>

int main()
{
  std::weak_ptr<int> weak;

  std::shared_ptr<int> shared {std::make_shared<int>(42)};
  weak = shared;
  std::cout << "Meaning of life: " << *weak.lock() << std::endl;

  weak = std::make_shared<int>(23);
  std::cout << "Meaning of life: " << *weak.lock() << std::endl;

  return 0;
}

The first std::cout prints fine, the second gives me a segfault. I tried looking at the pages of std::weak_ptr and std::shared_ptr on cppreference but I still don't understand why this happens. Having to create a temporary object feels cumbersome to me, is this something that has been addressed in C++14 or is there something I am failing to see?

Thanks!

Several mutexes locking in c++

In many places there is a suggestion to use std::defer_lock:

{
    std::unique_lock<std::mutex> lk1(mutex1, std::defer_lock);
    std::unique_lock<std::mutex> lk2(mutex2, std::defer_lock);
    std::lock(lk1, lk2);
    //Do some stuff
}

But what if I won't use std::defer_lock, and try to do simply that:

{
    std::unique_lock<std::mutex> lk1(mutex1);
    std::unique_lock<std::mutex> lk2(mutex2);
    //Do some stuff
}

As far as I know, this code will lock mutex1, and then lock mutex2. Unlocking will be performed in the reverse order - mutex2, and then mutex1. There is no reason to deadlock.

Documentation says, that std::lock(lk1, lk2); in the first example would lock buth mutexes simultaneously. So, is this some sort of optimization?

What does the scope resolution operator return in case of Type::var?

Consider the following example:

class A { int x; };

Now what is A::x?

  • It cannot be an lvalue because it does not refer to a storage Location.
  • It cannot be a type, because the type would be decltype(A::x).

Issue with std::stol - 'std::invalid_argument' what(): stol

I have an issue with std::stol. All answers I have found regarding to issues with std::stol or std::stoi are dealing with C++11 compiling / building.

std::string myString;
long myLong = std::stol(myString);

When I use std::stol() I get the following error:

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

Any ideas? Building with gcc -std::C++11 works fine. Note: I think this is my first C++11 expression I use.

condition variable and #pragma pack bug

I found out that this piece of code doesn't work as intended:

#pragma pack(push, 1)

class myclass {
protected:
    bool mycrasher[1];
    std::mutex mtx;
    std::condition_variable cv;

    void thread_func() {
        std::this_thread::sleep_for(std::chrono::seconds(1));

        std::chrono::milliseconds timeout(1000);
        std::unique_lock<std::mutex> l(mtx, std::defer_lock);
        while (true) {
            auto now = std::chrono::system_clock::now();
            l.lock();
            while (true) {
                std::cout << "Waiting..." << std::endl;
                auto result = cv.wait_until(l, now + timeout);
                std::cout << "Timed out..." << std::endl;
                if (result == std::cv_status::timeout)
                    break;
            }
            l.unlock();
        }
    }   

public:
    myclass() { 
        std::lock_guard<std::mutex> l(mtx);
        std::thread *t = new std::thread(&myclass::thread_func, this);
        t->detach();
    };

    void start() {
        std::cout << "myclass started." << std::endl;
        std::cout << "sizeof(std::mutex) = " << sizeof(std::mutex) << std::endl;
        std::cout << "sizeof(std::condition_variable) = " << sizeof(std::condition_variable) << std::endl;
    }
};
#pragma pack(pop)

int main() {
    myclass x;
    x.start();
    std::this_thread::sleep_for(std::chrono::seconds(60));
}

I expected the code to wait for one second on the cv.wait_until call and then repeat, but is simply hangs on the call. The issue (intuitively) goes away if I remove the #pragma directives, because I'm packing the mutex and the CV. However, when I run this code I get:

myclass started.
sizeof(std::mutex) = 40
sizeof(std::condition_variable) = 48

with or without the pragma, so it seems the packing is not the real problem.

In addition, I discovered that if I align the mycrasher variable to a 4-bytes boundary the problem disappears as well. Likewise, if I move the variable after the std::condition_variable cv declaration the problem disappears, but when moved between std::mutex mtx and std::condition_variable cv it still persists.

Why the snippet hangs on the cv.wait_until call when the CV is not properly aligned? A performance hit would be expected, but not a plain stall.

xerces does not find my attributes

this is my first question, so plz don't be angry if I do sth. wrong.

I'm using xerces-c-3.1.4 with c++11 (g++ 6.2.0 20161005) and I have problems reading attributes from XML tags by name. I'm using the DOMParser. The follwing is the XML tag I'm reading.

<gui subtype="somethingsomething" prettyname="myPrettyName" docroot=".." listenip="0.0.0.0" listenport="1234" autostart="true">

In my program I read from it as follows:

char *prettyname = MyHelpers::XMLCh2Ch(attrmap->getNamedItem(MyHelpers::String2XMLCh(CT_GUI_NAME))->getNodeValue());

With the "prettyname" attribute it works all fine but if I try to read any other attribute such as "docroot" of this element by name I get a nullpointer by calling getNamedItem(...).

I know they are there, because if I read them in a loop (like below), everything is there.

  for (XMLSize_t t = 0; t < attrmap->getLength(); t++) {
    std::cout << "attr:\n" << MyHelpers::XMLCh2String(attrmap->item(t)->getNodeName()) << " : " << MyHelpers::XMLCh2String(attrmap->item(t)->getNodeValue()) << std::endl;  

}

Now the weirdest part: I tried around a little bit with the names of the attributes to exclude the possibility tha I just hit a keyword which causes strange behavior. This made me recognize that it works fine when the attribute is not known by my .xsd grammar I use for validation. The relevant part looks as follows:

<xs:element name="gui">
<xs:complexType>
  <xs:sequence>
    <xs:element ref="address"/>
    <xs:element ref="screenconfig" maxOccurs="unbounded"/>
  </xs:sequence>
  <xs:attribute name="autostart" type="xs:string" use="required"/>
  <xs:attribute name="ddocroot" type="xs:string" use="required"/>
  <xs:attribute name="listenip" type="xs:string" use="required"/>
  <xs:attribute name="listenport" type="xs:string" use="required"/>
  <xs:attribute name="prettyname" type="xs:string" use="required"/>
  <xs:attribute name="subtype" type="xs:string" use="required"/>
</xs:complexType>

Just in case it's relevant here the initialisation of my parser. It's more or less copied from an example.

 XercesDOMParser* parser = new XercesDOMParser();
   if (parser->loadGrammar(grammarFilePath.c_str(), Grammar::SchemaGrammarType) == NULL) {
     std::cout << "couldn't load schema" << std::endl;
   }
  parser->setValidationScheme(XercesDOMParser::Val_Always);
  parser->setDoNamespaces(true);    
  parser->setDoSchema(true);
  parser->setValidationSchemaFullChecking(true);
  parser->setIncludeIgnorableWhitespace(false);

Any idea would be greatly apreciated. If you need any further details, don't hesitate to leave me a comment.

Best, fluorid

Does wrapping a std::atomic_flag in a getter/setter void its "atomicity"?

Say I have a class that contains a std::atomic_flag as private member, exposed through a getter. Something like the following (pseudo-code):

class Thing
{
private:

    std::atomic_flag ready = ATOMIC_FLAG_INIT;

public:

    isReady()
    {
        return ready.test_and_set(); 
    }
} 

My naive question is: does querying the flag through a method turn it into a non-atomic operation, being a function call non-atomic (or is it?)? Should I make my ready flag a public member and querying it directly?

what's the use of brace in constructor position in C++? [duplicate]

This question already has an answer here:

I have read part of boost, it shows:

struct activation_record {
    typedef boost::intrusive_ptr< activation_record >    ptr_t;

    thread_local static ptr_t   current_rec;

    std::atomic< std::size_t >  use_count{ 0 };
    fcontext_t                  fctx{ nullptr };
    stack_context               sctx{};
    bool                        main_ctx{ true };
};

I don't understand what's the use of { 0 } after use_count, { nullptr } after fctx, etc.

Is that a constructor ?

mardi 30 mai 2017

Using nested macro with different number of arguments in C++

The following code fails in compilation by g++ -std=c++11 compiler.

    # include<iostream>
    # include<vector>

    using namespace std;


    # define stlf(x)        x.begin(), x.end()
    # define repf(it, a, b) for(auto it = a ; it != b ; ++it)


    /*
    // Also, following alternative fails

    # define repf(it, a, b) for(auto it = a ; it != b ; ++it)
    # define stlf(x)        x.begin(), x.end()

    */



    typedef vector<int > vi;

    # define pd(x)  printf("%d", x);

    int main(void){

        vi arr(10, -1);

        repf(arr, stlf(arr))
            pd(arr[i]);


        return 0;
    }

1. Why is this happening ?

2. What could have been implementation problem for C++ Pre-Processor implementors, that they avoided this feature ?

3. How can I then use such shortcuts ??

How to manipulate console text and background colours? [duplicate]

Please list the header files, an example of how to use and if possible a description of how it works I wish to know how to change colour of the text and background in c++ console and also if possible how to alter the fonts of the text in c++ console

Thanks for the help

Platform is windows.

Compare the habits between move and smart pointer in C++?

In C++11/14, an object can be transfered by move or smark pointer.

(1) This is an example for move:

class MoveClass {
private:
    int *tab_;
    int alloc_;
    void Reset() {
        tab_ = nullptr;
        alloc_ = 0;
    }
    void Release() {
        if (tab_) delete[] tab_;
        tab_ = nullptr;
        alloc_ = 0;
    }

public:
    MoveClass() : tab_(nullptr), alloc_(0) {}
    ~MoveClass() {
        Release();
    }
    MoveClass(MoveClass && other) : tab_( other.tab_ ), alloc_( other.alloc_ ) {
        other.Reset();
    }
    MoveClass & operator=(MoveClass && other) {
        if (this == &other) return *this;
        std::swap(tab_, other.tab_);
        std::swap(alloc_, other.alloc_);
        return *this;
    }
    void DoSomething() { /*...*/ }
};

When we use this movable MoveClass, we can write code like this :

int main() {
    MoveClass a;
    a.DoSomething();  // now a has some memory resource
    MoveClass b = std::move(a);  // move a to b
    return 0;
}

Always write move-constructor/move-operator= is boring, use shared_ptr/unique_ptr some times have the same effect, just like java, reference/pointer everywhere.

(2) Here is the example:

class NoMoveClass {
private:
    int *tab_;
    int alloc_;
    void Release() {
        if (tab_) delete[] tab_;
        tab_ = nullptr;
        alloc_ = 0;
    }

public:
    NoMoveClass() : tab_(nullptr), alloc_(0) {}
    ~NoMoveClass() {
        Release();
    }
    MoveClass(MoveClass && other) = delete;
    MoveClass & operator=(MoveClass && other) = delete;
    void DoSomething() { /*...*/ }
};

We can use it like this:

int main() {
    std::shared_ptr<NoMoveClass> a(new NoMoveClass());
    a->DoSomething();
    std::shared_ptr<NoMoveClass> b = a; // also move a to b by copy pointer.
    return 0;
}

Is it a good habit to always use the 2nd one?

Why many libraries, STL use the 1st one, not the 1st one ?

Setting Preference over Constructor in Template Member Function in Template class

I'm trying to create my own implementation of a doubly-linked list for learning purpose. I wanted to use a template class to do this. I have a few constructors that have the definition like this:

template <typename TYPE>
class DList {
public:
    DList(const size_t size, const TYPE& val = TYPE());

    template <typename ITER>
    DList(ITER&& begin, ITER&& end);
};

(I have more code that I have omitted).

The first constructor copies the value provided size times (so DList<int>(5, 2) would copy the number 2, 5 times)

The second constructor copies a range (between 2 Iterators) in to the list. (so DList<int>(other.begin(), other.end()) would copy one data structure in to the DList)

The question is that how do I set the preference of the two constructors? For example if I'm instantizing my class with this line:

DList<int> listTest2(6, 2);

The compiler gets confused and chooses the iterator based constructor over the size constructor and throws errors. I want to keep the template iterator constructor because I have other classes like that one (that implements other data structures) and the iterators is a class inside the class. (so DList has a class inside it called iterator, see below for more info on what I mean).

Is there anyway to set a preference over which constructor gets called. I want it to work like how I can call std::vector<int>(other.begin, other.end) and std::vector<int>(2, 3) and both work.

I have attached the header file for my template class below:

template <typename TYPE>
class DList {
public:
    struct Node {
        Node* prev;
        TYPE data;
        Node* next;
    };

    class iterator {
    public:
        iterator();
        iterator(const Node* node);
        iterator(const iterator& it);

        iterator& operator++(); // preincrement
        iterator& operator--();

        iterator operator++(int); // postincrement
        iterator operator--(int);

        iterator& operator=(const iterator& it);

        iterator& operator-(int scale);
        iterator& operator+(int scale);

        bool operator==(const iterator& it);

        TYPE& operator*();
        TYPE& operator->();

        Node* getNode();

    private:
        Node* data;

    };

    DList();
    DList(const DList& other);

    DList(const size_t size, const TYPE& val = TYPE());

    template <typename ITER>
    DList(ITER&& begin, ITER&& end);

    iterator begin() const;
    iterator end() const;

    void clear();

    void push_back(const TYPE& val);
    void push_front(const TYPE& val);

    void pop_back();
    void pop_front();

    void insert(size_t idx, const TYPE& val);
    void insert(const DList<TYPE>::iterator it, const TYPE& val);
    void remove(const TYPE& val);

    size_t size() const;

    const TYPE& operator[](size_t idx) const;
    TYPE& operator[](size_t idx);

private:    
    Node* mHead; /// @todo convert to iterators?
    Node* mTail;
    size_t mSize;

};

UDP communication using c++ boost asio

I need to communicate with a different device in a private network over UDP. I am new to using boost, but based on what I searched online and also the tutorials on Boost website, I came up with below code.. I am currently trying to send and receive data from my own device. Just to unit test and finalize the code.

Question: I am unable to receive any message. What am I missing?

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include "boost/asio.hpp"
#include <thread>
#include <boost/array.hpp>
#include <boost/bind.hpp>

#define SRVR_UDP_PORT  10251
#define CLNT_UDP_PORT 10252

boost::array<char, 1024> recv_buffer;

void Sender(std::string in)
{
    boost::asio::io_service io_service;
    boost::asio::ip::udp::socket socket(io_service);
    boost::asio::ip::udp::endpoint remote_endpoint;
    socket.open(boost::asio::ip::udp::v4());
    remote_endpoint = boost::asio::ip::udp::endpoint(boost::asio::ip::address::from_string("192.168.1.64"), SRVR_UDP_PORT);

    boost::system::error_code err;
    socket.send_to(boost::asio::buffer(in.c_str(), in.size()), remote_endpoint, 0, err);
    socket.close();
    //int i =0;
    printf("Sending Payload --- \n");
}

void handle_receive(const boost::system::error_code& error, size_t bytes_transferred)
{
    std::cout << "Received: '" << std::string(recv_buffer.begin(), recv_buffer.begin()+bytes_transferred) << "'\n";
}


void Receiver()
{
    while(1)
    {
        boost::asio::io_service io_service;
        boost::asio::ip::udp::socket socket(io_service);
        boost::asio::ip::udp::endpoint remote_endpoint;

        //socket.open(boost::asio::ip::udp::v4());
        boost::system::error_code err;
        remote_endpoint = boost::asio::ip::udp::endpoint(boost::asio::ip::address::from_string("192.168.1.64"), CLNT_UDP_PORT);

        socket.open(boost::asio::ip::udp::v4());
        //http://ift.tt/2rCt9Yk
        socket.async_receive_from(boost::asio::buffer(recv_buffer),
                                    remote_endpoint,
                                    boost::bind(handle_receive,
                                    boost::asio::placeholders::error,
                                    boost::asio::placeholders::bytes_transferred));                                    
                                    //socket.close();
    }
    int i = 0;
    printf("Received Payload --- %d", i);

}

int main(int argc, char *argv[])
{
    //std::thread s(Sender);
    std::thread r(Receiver);
    //s.join();
    std::string input = argv[1];
    printf("Input is %s\nSending it to Sender Function...\n", input.c_str());
    Sender(input);
    r.join();
    return 0;
}

Symbol lookup error at runtime even though nm reports symbol present

I build my program like this:

g++ -std=c++11 myprog.cpp -o myprog -lqpid-proton-cpp

Then I run ./myprog and get this error:

symbol lookup error: ./myprog: undefined symbol: _ZN6proton10event_loop6injectESt8functionIFvvEE

Yet, nm reports the symbol is present in the library . . .

nm -D /usr/lib/libqpid-proton-cpp.so | grep _ZN6proton10event_loop6injectESt8functionIFvvEE

. . . yields:

000000000002f460 T _ZN6proton10event_loop6injectESt8functionIFvvEE

What am I missing here?

condition variable wait_for/wait_until bug

I'm facing a very strange behavior on a simple code snippet.

The following code is part of a larger project, runs on a separate thread and produce a 100% cpu usage, being stuck on the wait_until call of the conditional variable:

class myclass {
protected:
    std::mutex mtx;
    std::condition_variable cv_should_go;

    // ... more stuff, thread initialization...

    void my_thread_func() {
        std::chrono::milliseconds timeout(1000);
        std::unique_lock<std::mutex> l(mtx, std::defer_lock);
        while (true) {
            auto now = std::chrono::system_clock::now();
            l.lock();
            while (true) {
                std::cout << "Here 1" << std::endl;
                auto result = cv_should_go.wait_until(l, now + timeout);
                std::cout << "Here 2" << std::endl;
                if (some_condition || result == std::cv_status::timeout)
                    break;
            }
            // Other logic goes here, but suppose there's nothing...
            l.unlock();
        } 
    }
}

When some_condition condition is false, I expect a timeout after one second, a break due to the timeout itself, and again a wait of one second and so on... However, only one Here 1 line appears on the console, and the program simply stucks at the wait_until call.

Looking at CPU usage with top I can see the process using 100% of the CPU time. The very strange thing is that if I replace the cv_should_go condition variable with a CV within the scope of the function (killing the purpose of the class-scoped CV):

        ...
        std::unique_lock<std::mutex> l(mtx, std::defer_lock);
        std::condition_variable cv;
        while (true) {
            auto now = std::chrono::system_clock::now();
            l.lock();
            while (true) {
                std::cout << "Here 1" << std::endl;
                auto result = cv.wait_until(l, now + timeout);
        ...

the code runs flawlessly and produces the sequence of "Here 1" and "Here 2" every second.

The same thing happens if I replace wait_until with wait_for.

This was reproduced with g++ 4.9 and g++ 6.3 on a Debian 8 system.

Is this a bug of BOTH compilers or something hidden I can't really see?

cpprest Casablanca doesn't close file stream

i don't know the reason but my server doesn't work anymore. The problem is because it doesn't close the output file stream "uploaded",so i can't manage the file because it exists but it's empty. Suggestions?

void Server::handle_post(http_request request)

{ TRACE("\nhandle POST\n"); auto fileBuffer = std::make_shared>(); string_t uploaded = L"uploaded"; suffix++; std::wstringstream wss; wss << suffix << (".txt");

uploaded.append(wss.str());

try
{
    auto stream = concurrency::streams::fstream::open_ostream(
        uploaded,
        std::ios_base::out | std::ios_base::binary).then([request, fileBuffer](pplx::task<Concurrency::streams::basic_ostream<unsigned char>> Previous_task)
    {

        *fileBuffer = Previous_task.get();
        try
        {
            request.body().read_to_end(fileBuffer->streambuf()).get();
        }
        catch (const exception&)
        {
            wcout << L"<exception>" << std::endl;
            //return pplx::task_from_result();
        }
        //Previous_task.get().close();

    }).then([=](pplx::task<void> Previous_task)
    {


        fileBuffer->close();
        //Previous_task.get();
    }).then([](task<void> previousTask)
    {
        // This continuation is run because it is value-based.
        try
        {
            // The call to task::get rethrows the exception.

            previousTask.get();
        }
        catch (const exception& e)
        {
            wcout << e.what() << endl;
        }
    });
    //stream.get().close();
}
catch (const exception& e)
{
    wcout << e.what() << endl;
}


ManageClient( uploaded);

request.reply(status_codes::OK, U("Hello, World!")).then([](pplx::task<void> t) { handle_error(t); });
return;

}

Boost condition variable with sharable mutex

In Boost interprocess, is it possible to use a condition variable with a sharable mutex? I have one writer and multiple readers that need to wait on the writer.

More specifically, using named_condition_any::wait fails because it internally calls unlock() but sharable_lock requires unlock_sharable(). How could I get around this?

C++ type deduction in variadic templates

I started experimenting with variadic templates in C++11 and now I have a following method:

template <typename... TPath>
void Bind(PropertyPath<TPath...> propertyPath);

and currently I have to call this this way:

myItem.Value.Bind<Item *, string, int>(PropertyPath<Item *, string, int>(...));

where PropertyPath is a variadic template class with any number of parameters (and the three dots are whatever arguments I put in the constructor)

The compiler doesn't seem to be able to infer the template types for Bind based on what PropertyPath I pass in. Is there no way to make this work without specifying the parameters twice? This is what I would like to be able to do:

myItem.Value.Bind(PropertyPath<Item *, string, int>(...));

What is the right way to track Boost ASIO sessions?

sI have a server application that is based on the implementation shown here. This implementation creates a new session as a shared_ptr. As long as the client is connected, the session remains alive. When the client disconnects, a session object is destroyed. This is very convenient, but...

The problem: I would like to be able to track sessions, for two reasons:

  1. To track connected users, and group sessions from the same user
  2. To be able to shutdown all sessions and exit gracefully, when needed.

How can I do that?

Ideally, I'd like to be able to iterate over all sessions that are alive.

Failed/horrible solutions from my side

  • Add every session's shared_ptr to some container, right before new_session->start()

The problem with this is that the session is then never destroyed, not even when the user disconnects... of course, this is because an instance of shared_ptr is still alive in the container, which means I have to periodically check that the number of shared_ptr count == 1, which will complicate the design and create horrible thread-safety complications.

  • Create a container that has normal pointers of all sessions in the server instance, in addition to a mutex, and pass them both to each session, and make the destructor of the session remove itself from the container

This solution would work (I'm guessing here), but it's just very complicated that it feels ugly, and I wanted some advice before proceeding with this mess. I'm sure there's someone smarter than me out there to figure a smarter solution, or make me realize that boost ASIO has a solution for this already.

Why std::chrono::time_point is not large enough to store struct timespec?

I'm trying the recent std::chrono api and I found that on 64 bit Linux architecture and gcc compiler the time_point and duration classes are not able to handle the maximum time range of the operating system. In fact it seems the storage for these classes is a 64bit integral type, compared to timespec and timeval which are internally using two 64 bit integers, one for seconds and one for nanoseconds:

#include <iostream>
#include <chrono>
#include <typeinfo>
#include <time.h>

using namespace std;
using namespace std::chrono;

int main()
{
    cout << sizeof(time_point<nanoseconds>) << endl;                       // 8
    cout << sizeof(time_point<nanoseconds>::duration) << endl;             // 8
    cout << sizeof(time_point<nanoseconds>::duration::rep) << endl;        // 8
    cout << typeid(time_point<nanoseconds>::duration::rep).name() << endl; // l
    cout << sizeof(struct timespec) << endl;                               // 16
    cout << sizeof(struct timeval) << endl;                                // 16
    return 0;
}

On 64 bit Windows (MSVC2017) the situation is very similar: the storage type is also a 64 bit integer. This is not a problem when dealing with steady (aka monotonic) clocks, but storage limitations make the the different API implementations not suitable to store bigger dates and wider time spans, creating the ground for Y2K-like bugs. Is the problem acknowledged? Are there plans for better implementations or API improvements?

easiest way to have function of a map but that is ordered

I am trying to obtain an easy way to create something that functions like a vector of maps, that when I insert a key-value pair, it is not ordered when I put it in. I am creating a class as follows...

class Attributes: public vector<map<string,string>>
{
    public:

    private:

};

#endif

I will put a map of a string to a string to it, and then put more mappings in it. I put them in order. The problem, is that when I try to output these, they are in order.

For example, this output that looks like...

sibling1(c,b,a)? Yes(2) a='dad', b='Asher', c='Gad' a='pad', b='Gad', c='Naphtali'

should look like...

sibling1(c,b,a)? Yes(2) c='Gad', b='Asher', a='dad', c='Naphtali',b='Gad', a='pad'

I don't want a vector of vectors of strings because that messes up my easy way to look up these things for later. Again, please think of the Easiest way to change this, if possible. Thank you.

Can i make the constructor of a derived class contexpr if the base class constructor is not constexpr?

i am trying to compile an example from "Design Patterns" and i am facing the following problem:

i got the base class MapSite:

class MapSite{
    public:
    MapSite();
    virtual ~MapSite(); 
    virtual void Enter() = 0;
};

and the derived class Room:

class Room : public MapSite final{

private:
unsigned int room_number;

public:
Room(unsigned int rn) : room_number(rn) {};

virtual void Enter() override;
};

From another class i want to call the function

virtual std::unique_ptr<Room> MakeRoom(unsigned int n) {return make_unique<Room(n)>();} 

So i will get the following error:

error: temporary of non-literal type ‘Room’ in a constant expression
  virtual std::unique_ptr<Room> MakeRoom(unsigned int n) {return unique::make_unique<Room(n)>();}

So i thought the problem may be that the constructor has to be constexpr in order to call the constructor of Room from another function, but setting the constructor to:

public:
constexpr Room(unsigned int rn) : room_number(rn) {};

will produce this error:

error: call to non-constexpr function ‘MapSite::MapSite()’
  constexpr Room(unsigned int rn) : room_number(rn) {};

My basic question is whether i can make a derived class constructor constexpr, even if the base class constructor is not.

PS: make_unique is a c++14 feature which i emulated from here How to implement make_unique function in C++11? for c++11, which i am compiling with

Thanks in advance, Lukas!

Why are there const overloads of mutating Boost.Range algorithms?

The documentation (and the implementation) of Boost.Range shows overloads of the mutating algorithms that take const refs as arguments. For instance Boost.Range's Sort documentation shows:

template<class RandomAccessRange>
RandomAccessRange& sort(RandomAccessRange& rng);

template<class RandomAccessRange>
const RandomAccessRange& sort(const RandomAccessRange& rng);

template<class RandomAccessRange, class BinaryPredicate>
RandomAccessRange& sort(RandomAccessRange& rng, BinaryPredicate pred);

template<class RandomAccessRange, class BinaryPredicate>
const RandomAccessRange& sort(const RandomAccessRange& rng, BinaryPredicate pred);

What is the point of overloads 2 and 4? Sure it's nice to be able to pass temporaries, but then const& makes this point kinda of moot. Rvalue-references would be most welcome, but it is my understanding that their support in Boost.Range is too invasive, and is "deferred" to the adoption of Range.V3 (it would be nice if meanwhile it were part of Boost).

Why does this simple lambda consistently run faster inside an std::thread than inside the main function with gcc 4.9.2?

The following snippet takes a command line parameter that represents the number of threads to spawn to run a simple for loop concurrently.

If the arguments passed is 0, no std::thread is spawned.

On gcc 4.9.2, ./snippet 0 takes 10% longer than ./snippet 1 in average, i.e. the version that spawns one std::thread to execute the loop is faster than the version that just executes the loop inside main.

Does anyone know what's going on? clang-4 does not show this behaviour at all (version with one std::thread is slower), gcc 6.2 has the version with one std::thread run just slightly faster (when taking the minimum time spent over ten trials as the measured value).

Here is the snippet: ScopedNanoTimer is just a simple RAII timer. I am compiling with -g -O3 -pthread -std=c++11.

#include <thread>
#include <chrono>
#include <iostream>
#include <vector>

class ScopedNanoTimer {
   const std::chrono::high_resolution_clock::time_point t0;
   void (*cb)(long long int);

public:
   ScopedNanoTimer(void (*callback)(long long int)) : t0(std::chrono::high_resolution_clock::now()), cb(callback) {}

   ~ScopedNanoTimer()
   {
      const auto t1 = std::chrono::high_resolution_clock::now();
      const auto nanos = std::chrono::duration_cast<std::chrono::nanoseconds>(t1 - t0).count();
      cb(nanos);
   }
};

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

   // setup
   if (argc < 2) {
      std::cerr << "usage: " << argv[0] << " <n_threads>\n";
      std::cerr << "n_threads == 0 indicates completely sequential execution\n";
      return 1;
   }
   const unsigned n_threads = std::atoi(argv[1]);
   const auto n_iterations = 1000000000ul / (n_threads == 0u ? 1u : n_threads);

   // define workload
   auto task = [n_iterations]() {
      volatile auto sum = 0ul;
      for (auto i = 0ul; i < n_iterations; ++i) ++sum;
   };

   // time and print
   for (auto i = 0u; i < 10; ++i) {
      if (n_threads == 0) {
         ScopedNanoTimer timer([](long long int ns) { std::cout << ns << " "; });
         task();
      } else {
         std::vector<std::thread> threads;
         ScopedNanoTimer timer([](long long int ns) { std::cout << ns << " "; });
         for (auto i = 0u; i < n_threads; ++i) threads.emplace_back(task);
         for (auto &thread : threads) thread.join();
      }
   }
   std::cout << std::endl;
   return 0;
}

C++ vector of char vectors cannot be printed

I have a c++ vector of char vectors: std::vector<std::vector<char>> ref After putting chars in it (size increases, so chars are there) I cannot print it.

By calling this->ref.back().back() it correctly prints the last char. But if I do ref.at(0).at(pos) or ref[0].at(pos) or ref[0][pos] nothing is printed.

Chars are put in as follows:

while (infile>>c)
    {
        if (c != '>') {
            ref.back().push_back(c);
            curSeqPos++;

        }
        else {
            infile.ignore ( std::numeric_limits<std::streamsize>::max(), '\n' );
            ref.push_back(std::vector<char>(USHRT_MAX));

            curSeq++;
            curSeqPos = 0;
        }
     }

Any idea what I am doing wrong? I am a real newbie to C++ and probably missed a reference somewhere. Any help is appreciated!

CMakeLists for C++ library to use in source code

I include a header file from a library in my source file and get this following error my initial guess is there is something wrong in CMakeLists any suggestions please

/usr/include/c++/4.8/bits/c++0_warning.h:32:2: error: #error This file requires compiler and library support for the ISO C++ 2011 standard.

This support is currently experimental, and must be enabled with the -std=c++11 or -std=gnu++11 compiler options.

#error This file requires compiler and library support for the

make[2]: *** [CMakeFiles..] Error 1

make[1]: *** [CMakeFiles..] Error 2

make: *** [all] Error 2

The C++ Standard doesn`t provide a hash for this type

I am trying to create a unordered-map using a pair as a key. This is something new for me so I followed some tutorials and I wrote this:

    struct pair_hash {
        template <class T1, class T2>
        std::size_t operator () (const std::pair<T1, T2> &p) const {
            auto h1 = std::hash<T1>{}(p.first);
            auto h2 = std::hash<T2>{}(p.second);

            return h1 ^ h2;
        }
    };

int wmain(int argc, wchar_t * argv[])
{
   {...}

    using Key = std::pair<DWORD, DWORDLONG>;
    std::unordered_map<Key, USN, pair_hash> mymap;


    std::pair<DWORD, DWORDLONG> mypair(dwVolSN, fileId);

    mymap.insert({ mypair, usn });

    std::unordered_map<Key, USN>::const_iterator got;
    got = mymap.find(mypair); // HERE I GET THE ERROR

    return 0

}

more threads created than expexted

You could find the program here

I am building a program in message passing framework 0MQ. I try to implement what I posted in here

Program compiled with g++ -std=c++11 test.cpp -o test -lzmq -lpthread.

To run the program, pass one parameter as the thread number you would like to have. That parameter is then assigned to variable worker_num.

In main thread, I setup thread with:

  vector<thread> pool;
  for(int i = 0; i < worker_num; i++)
  {
    cout << "main() : creating thread, " << i << endl;
    pool.push_back(thread(task1, (void *)&context, i));
  }

I would like to make sure all worker threads have successful connection to main thread before main thread distributes jobs to them.

  while(true)
  {
    if(sync_done)
    {
      cout << "sync done in main thread" << endl;
      break;
    }

    zmq::message_t sync_msg(4);
    memcpy((void *)sync_msg.data(), SYNC_MSG, SYNC_MSGLEN);
    for(int i = 0; i < worker_num; i++)
      distask_socket.send(sync_msg);

    for(int i = 0; i < worker_num; i++)
    {
      if(sync_done)
        break;
      if(i != 0)
        this_thread::sleep_for(chrono::milliseconds(500));

      zmq::message_t res_msg;
      int ret = getres_socket.recv(&res_msg, ZMQ_DONTWAIT);

      if(ret == -1 && errno == EAGAIN)
        continue;

      int threadID = stoi(string((char *)res_msg.data()));
      sync_done = if_sync_done(threadID, sync_array, worker_num);
    }
  }

So what main thread does is: pushing #worker_num of sync msgs with its PUSH endpoint to worker threads each time and then reads confirmation msg from its PULL endpoint. If main thread retrieves #worker_num of confirmation msgs, then sync done. Format of the sync msg from worker is: the worker thread's ID in a string. So thread 0 would pass a 0 in string back to main thread.

But running the program I have:

$ ./test 1
main() : creating thread, 0
thread id:0
thread 0 receives: sync
thread 0 sends: 0
thread 0 sync done
main thread receives sync msg from thread 1
terminate called after throwing an instance of 'std::invalid_argument'
  what():  stoi
Aborted

main thread receives sync msg from thread 1 means thread are 2 threads created: thread 0 and thread 1. Any idea why? I did pass 1 as parameter. Noted that if you run the program yourself you may get other outputs.

C++ variable scope

I have C++ code different output compared to what I expected, I hope to understand how it's executed

#include <iostream>
#include <string>

int x = 8;

class A {
    public :
    A(){int x = 5 ;}
   void print (int x = 4) { std::cout <<"the scope variable"<< ::x<<"passed variable" << x ;}


    };
int main()
{
  A a ;
  a.print(7);
}

I expected to be 5 and 7 but the result is 8 and 7

c++ must take exactly one argument

I'm a new c++ learner.Now,I have a problem in my code, but I don't know how to debug it.Please help me.It's form.h file.

using namespace std;

class Form
{
friend ostream& operator << (ostream&, const Form&);
int prc; 
int wdt;
int fmt;
double val;

public:
explicit Form(int p=6):prc(p)
{
  fmt = 0;
  wdt = 0;
}

//Bound_form operator()(double d) const;

Form& scientific()
{
 fmt = ios_base::scientific;
 return *this;
 }

Form& precision(int p) 
{
 prc = p;
 return *this;
}
Form& fill(char);

std::ostream& operator<<(std::ostream& os, const Form& bf)
{
  ostringstream s;
  s.precision(bf.prc);
  s.setf(static_cast<ios_base::fmtflags>(bf.fmt), ios_base::floatfield);
  s.setf(bf.fmt,ios_base::floatfield);

  s << bf.val;
 return os << s.str() ;
 }
};

When i compile, it says: enter image description here

How to use the write() function from AdsLib

A project is organized as follow

/project

  • CMakeLists.txt
  • Makefile
  • sensorSource.cpp
  • example.cpp
  • example.bin
  • Adsdef.h
  • AdsLib.h
  • AdsLib-Linux.a

/build

  • sensorsource

In sensorSource.cpp data acquisition through sensor, data processing and computation of a position point is performed.

In example.cpp is used to establish communication between PC and embedded PC via

write(); // #include "AdsLib.h"

The question is how to use this write(); in sensorSource.cpp so that the computed position information can be forwarded directly from sensorSource.cpp to the embedded PC.

Just to elaborate more, here Makefile refers to example.cpp and CMakeLists.txt refers to sensorSource.cpp

1) In search of a reliable solution first i thought to write the equivalent of Makefile code in CMakeLists so to compile both source files using CMakeLists.txt but unfortunately I am totally stuck here with no idea how to fuse this Makefile and CMakeLists.txt or possibility to include (Adsdef.h, AdsLib.h, AdsLib-Linux.a) in sensorSource.cpp any suggestions how to approach the problem further on ?

thanks :)

lundi 29 mai 2017

Variables that can be used as data types.

Is there any way in C++ through I can store the data types in the program like (int, char, std::string etc.) in some particular kind of variable and then use that variable instead, in place of the regular data types (for eg: to declare other variables)?

For eg:-

T = some-function("int")
now std::vector < T > is equivalent to std::vector <int> ? 

How can we serialize or deserialize the object of a class in c++.Is there any predefined library?

Is there any predefined library to serialize the object in c++. If there is not how can we do that.

How does proposal N4502 work?

I was looking at the proposal N4502, and have been trying to wrap my head around it. I'm good up to section 5, but then what I thought I understood falls away. Perhaps it is just how I'm looking at it. Given the following:

// primary template handles all types not supporting the operation:
template< class, template<class> class, class = void_t< > >
struct
  detect : false_type { };
// specialization recognizes/validates only types supporting the archetype:
template< class T, template<class> class Op >
struct
  detect< T, Op, void_t<Op<T>> > : true_type { };

To use this detect metafunction, we supply it with another metafunction (i.e., a meta-callback) that fills the role of the archetypal expression. For example, here is an implementation of the is_assignable type trait:

// archetypal expression for assignment operation:
template< class T >
using
  assign_t = decltype( declval<T&>() = declval<T const &>() )
// trait corresponding to that archetype:
template< class T >
using
  is_assignable = detect<void, assign_t, T>;

I should be able to check if a type is assignable. No example of how it is use is given, so I'm assuming that it should be as easy as:

static_assert(is_assignable<int>::value, "Not assignable.");

Now just looking at this, doesn't look right. I don't see any way that assign_t is going to interact with the type T.

How this reads to me is:

is_assignable<int>
-> detect<void, assign_t, int>

Which will then fail to match any specialization and go to the base case which inherits from std::false_type.

Compiling this here agrees with my understanding.

So, what am I missing? How is this supposed to be used?

UVA 455 Wrong answer... Please help... (passed the debug cases)

I did the UVA 455 Periodic Strings and passed the test cases in debug system but still got wrong answer... I tried some other cases and fixed a bug but still cannot pass...Please help..

This is the link for the question :http://ift.tt/2qugGFU

It is finding the repeating period for a string

eg:

if the input was ABC the period is 3

if the input was AAA the period is 1

if it was ABCABC, it is 3

ABBAAB it is 6

My method is brute force actually... I summed up different length of string and check whether they are equal, cause the characters are ints...

for ABAB A (index 0)!=B(index 1) (checking length 1)

then check (A(index 0)+B(index 1)) ?= (A(index 2)+B(index 3)) It is yes then answer is 2

for ABBA if the A(index 0) != B(index 2) when the checking length is 2 then it will break immediately

if(s[i]!=s[j]){
    equal = 0;
    break;
}

Here is the full code:

#include <iostream>
#include <string>
#include <cstring>
//#include <fstream>
#define maxn 85
using namespace std;

int main(){

    //ofstream myfile;
    //myfile.open("output.txt");
    int n;
    scanf("%d",&n);
    int equal;
    int len;
    while(n--){
        char s[maxn];
        scanf("%s",&s);
        int count = 1;
        len = strlen(s);

        for(count =1; count<= len/2;count++){
            equal = 1;
            int cur = 0;
            int a = 0, b = 0;
            while(cur+count < len){
                for(int i = cur,j=i+count;i<cur + count ||( j< (cur +2*count) && j<len);i++,j++){
                    if(s[i]!=s[j]){
                        equal = 0;
                        break;
                    }
                    a += s[i];
                    if(j<len) b += s[j];
                }
                cur+=count;
                if(a!=b){
                    equal = 0;
                    break;
                }else{
                    continue;
                }
            }
            if(equal == 1){
                //if(n-1>=0) myfile << count<<"\n\n";
                //else myfile << count<<"\n";
                if(n-1>=0) cout << count<<"\n\n";
                else cout << count<<"\n";
                break;
            }
        }
        if(equal == 0) //cout << len << "\n\n";
            //if(n-1>=0) myfile << len<<"\n\n";
            //else myfile << len<<"\n";
            if(n-1>=0) cout << len<<"\n\n";
            else cout << len<<"\n";
    }
    return 0;
}

Please help...thank you so much!

What does "unhandled exception thrown: read access violation" mean?

I've been able to compile my code, but this exception keeps being thrown:

Unhandled exception thrown: read access violation. this->pExpr was 0xCCCCCCCC.

I've been able to narrow it down to the lines of code below, but I'm not quite sure how to go about fixing it.

Thank you in advance.

Code within header file

class AssignmentSTMT : public STMT
{
    string id;
    int varIx;
    EXPR * pExpr;
public:
    AssignmentSTMT(string id, int varIx, EXPR *pExpr) :
        id(id), varIx(varIx), pExpr(pExpr) {}
    string to_string() override
    {
        ostringstream os("");
        os << "assign " << id << " : " << varIx << " "<< " = " << pExpr->to_string();
        return os.str();
    }
};

Here's code within cpp file

EXPR* pExpr; // pointer to expression
 STMT* pStmt;

 expr(pExpr);   // initializes pExpr

    if (pExpr != nullptr)
    {
        // PROBLEM SUSPECTED HERE
        pStmt =  new AssignmentSTMT(pExpr); 
        RunTime::stmtTable.load(pStmt);
    }

c++ - abstract class and alternative to virtual constructor

Let say I have the following code:

class Block{
private:
  data Data;
public:
  data getData();
};

Actually, there are several ways to build a block, but always with the same member Data and method getData(), the only difference is how to build the block. In other words, the only difference is the constructor...

Instead of writing a different class for each building process, I could factorize parts of my code, defining and declaring getData in an abstract class, if there were such thing as a virtual constructor in c++ that I could write differently for each derived class corresponding to a different building process.

I do not have a lot experience for this kind of things, so I wondered if there was an alternative to a virtual constructor ? or may be a different way to do this factorization ?

PS: I am aware of http://ift.tt/2s7oBWN but it seems quite complex regarding what I want to do, which seems quite common... I just want to factorize shared code between several classes, which corresponds to everything except the constructor. And I want to force new classes corresponding to other building processes to implement a new constructor.

More details about my particular situation:

I have an algorithm where I use blocks and it does not depend on their building process, so I have implemented the algorithm using a template argument to represent a block indifferently of its building process. But I use a few methods and its constructor, so I need my classes representing blocks to all have the same kind of methods I need and the same constructor to use them as a template argument of my algorithm implementation. That is why I thought of abstract class, to force a newly implemented class representing blocks to have the methods and the constructor I need in the algorithm I implemented. May be it is a bad design pattern and that is why I am stuck...

Hiding variadic template implementation

I have some 3rdParty library with a method like this:

bool Invoke(const char* method, Value* args, size_t nargs)

It takes an array of its inner type (convertible to any primitive c++ types) and arg count as its inner params. In my code, I wrote some generalized helper to avoid manual creation and type convertion for each invoke:

template<class ... Args>
bool WrappedValue::Invoke(const char* method, Args&& ... args)
{
    3rdParty::Value values[] = 
    {
        3rdParty::Value(std::forward<Args>(args))...
    }

    return m_value.Invoke(method, values, sizeof ... (Args));
}

It works just fine, but now I should have 3rdParty code defined in my header files and lib connected directly to my main project.

Is it possible to hide implementation details and usage of such this 3rd party library? (Use some kind of pimple idiom or proxy object for 3rdParty::Value ). I know that it's not possible to use virtual template methods in c++ to create a proxy or simply move template implementation to .cpp, so I am totally stuck with this problem.

Will be grateful for any help)

std::vector

I am using a class called Signal in my Qt project. In another class definition I want to have a private member of the type std::vector<Signal>.

class Message {
public:
    std::vector<Signal> signals;
...

The Signal class only holds basic type members (int, float) and implements getters and setters. Also it has some operator overloads for +, -, = and >> via friend function.

I am compiling with the Visual C++ Compiler 12.0 and the project compiles completely without the definition of the vector. However with it, it throws this error:

std::vector<Class, std::allocator<_Ty>>: no members defined using this type with _Ty=Signal

I have included both header files, <vector> and "signal.hpp".

Also the simplest vector<int> throws exactly the same error (ofc with int where Signal was written before)...

It is compiling with Visual Studio 2017 and g++ on ArchLinux, so maybe is this a C++11 Problem I am not aware of?

Chained Hash Table using Vector of Vectors

I am making a chained hash table using a vector of vectors holding objects of type Record. Should I declare the table using pointers to Record like: vector > Table; or no pointer: vector > Table; Or if there's any reason each one might be better to use in certain instances than the other. Thank you.

How to ensure a specific class only can create an instance of another class?

How can I restrict the instantiation of a class from only within a specific class? I don't want to restrict it within a single file, so anonymous namespace is not an option for me. Please note that I want to make the declaration of the to-be-restricted class visible to the entire world, just that only one specific candidate from the entire world can only instantiate and access it. How to achieve this in c++?

OpenMP: writing data synchronized with HDF5

I currently have a project going on, in which a large dataset has to be created using HDF5. Now, the naive implementation is all nice and dandy, but very slow. The slow part is in the calculation (10x slower than write) which I cannot speed up anymore, but maybe parallelization is possible.

I guess I could use a simple #pragma omp parallel for but the dataspace.write(..) method should be squential for speed reasons (maybe it doesnt matter). See this picture for example.

/*
------------NAIVE IMPLEMENTATION-----------------
|T:<calc0><W0><calc1><W1><calc2><W2>............|
|-----------------------------------------------|
|----------PARALLEL IMPLEMENTATION--------------|
|-----------------------------------------------|
|T0:<calc0----><W0><calc4>.....<W4>.............|
|T1:<calc1---->....<W1><calc5->....<W5>.........|
|T2:<calc2--->.........<W2>calc6-->....<W6>.....|
|T3:<calc3----->...........<W3><calc7-->...<W7>.|
------------DIFFERENT IMPLEMENTATION-------------
i.e.: Queuesize=4
T0:.......<W0><W1><W2><W3><W4><W5><W6>..........|
T1:<calc0><calc3>.....<calc6>...................|
T2:<calc1>....<calc4>.....<calc7>...............|
T3:<calc2>........<calc5>.....<calc8>...........|


T          Thread
<calcn---> Calculation time
<Wn>       Write data n. Order *important*
.          Waiting
*/

Codeexample:

#include <chrono>
#include <cmath>
#include <iostream>
#include <memory>

double calculate(float *buf, const struct options *opts) {
  // dummy function just to get a time reference
  double res = 0;
  for (size_t i = 0; i < 10000; i++)
    res += std::sin(i);
  return 1 / (1 + res);
}

struct options {
  size_t idx[6];
};

class Dataspace {
public:
  void selectHyperslab(){}; // selects region in disk space
  void write(float *buf){}; // write buf to selected disk space
};

int main() {
  size_t N = 6;
  size_t dims[6] = {4 * N, 4 * N, 4 * N, 4 * N, 4 * N, 4 * N},
         buf_offs[6] = {4, 4, 4, 4, 4, 4};
  // dims: size of each dimension, multiple of 4
  // buf_offs: size of buffer in each dimension

  // Calcuate buffer size and allocate
  // the size of the buffer is usually around 1Mb
  // and not a float but a compund datatype
  size_t buf_size = buf_offs[0];
  for (auto off : buf_offs)
    buf_size *= off;
  std::unique_ptr<float[]> buf{new float[buf_size]};

  struct options opts;        // options parameters, passed to calculation fun
  struct Dataspace dataspace; // dummy Dataspace. Supplied by HDF5

  size_t i = 0;
  size_t idx0, idx1, idx2, idx3, idx4, idx5;
  auto t_start = std::chrono::high_resolution_clock::now();
  std::cout << "[START]" << std::endl;
  for (idx0 = 0; idx0 < dims[0]; idx0 += buf_offs[0])
    for (idx1 = 0; idx1 < dims[1]; idx1 += buf_offs[1])
      for (idx2 = 0; idx2 < dims[2]; idx2 += buf_offs[2])
        for (idx3 = 0; idx3 < dims[3]; idx3 += buf_offs[3])
          for (idx4 = 0; idx4 < dims[4]; idx4 += buf_offs[4])
            for (idx5 = 0; idx5 < dims[5]; idx5 += buf_offs[5]) {
              i++;
              opts.idx[0] = idx0;
              opts.idx[1] = idx1;
              opts.idx[2] = idx2;
              opts.idx[3] = idx3;
              opts.idx[4] = idx4;
              opts.idx[5] = idx5;

              dataspace.selectHyperslab(/**/); // function from HDF5
              calculate(buf.get(), &opts);     // populate buf with data
              dataspace.write(buf.get());      // has to be sequential
            }
  std::cout << "[DONE] " << i << " calls" << std::endl;
  std::chrono::duration<double> diff =
      std::chrono::high_resolution_clock::now() - t_start;
  std::cout << "Time: " << diff.count() << std::endl;
  return 0;
}

Code should work right out of the box.

I already took a quick look into OpenMP, but I can't wrap my head around yet. Can anyone give me a hint/working example? I am not good with parallelization, but wouldn't a writer-thread with a bufferqueue work? Or is using OpenMP overkill anyways and pthreads suffice? Any help is kindly appreciated,

cheers

atomic_store of shared_ptr of interface

I am trying to set the value of a shared_ptr in an atomic way:

shared_ptr<Base> a = std::make_shared<Derived>();
....
shared_ptr<Base> b;
std::atomic_store(&b,a); // Error here

I got the error message "'std::shared_ptr< Base >' is not derived from 'volatile std::atomic<_ITp>'"

How to fix this? Thanks.

How to rewrite function, without using lambda expression?

I have one library, which is written with c++11 standard(at least) and my compiler which is c++0x. Library contains some functions, that i have to revert to c++0x. Since i have no experience with lambda expressions, i am stuck at rewriting the following function:

void EventTrace::connect(Connector& connector)
{
    Connector::EventSignal& s = connector.getEventSignal();
    connection_ = s.connect(
        [this](int e)
        {
            if (decoders_.empty())
            {
                poco_information_f1(LOGGER(), "Event %d", e);
            }
            for (Decoder decoder : decoders_)
            {
                try
                {
                    decoder(e);
                }
                catch (Exception& exception)
                {
                    poco_warning_f1(LOGGER(), "EventTrace Decoder error %s", exception.displayText());
                }
            }
        }
    );
}

Any help is appreciated.

Unqualified-id before 'using'

I want to define the following alias into the namespace Library:

namespace Library
{
    template <typename T>
    using MyVector = std::vector<T, std::allocator<T> >;
}

but I get the following error from the compiler:

expected unqualified-id before 'using'

I'm following the official reference on cppreference.com but so far I couldn't make it work. What am I missing?

Template class errors [on hold]

Hi i cant figure out the errors ................................................ ...............................................

    #include<iostream>
    using namespace std;
    template <class Tobj>
    class node{
        public:
            Tobj obj_add;
            node *next;
            //----------------
            bool isEmpty(node &head);
            char menu();
            void insertAsFist(node *&head,node *&last,Tobj objADD);
            void insert(node *&head,node *&last,Tobj objADD);
            void remove(node *&head,node *&last);
            void showlist(node *curret);
    };
    //---------------------
    //dEFINITIONS ARE:
    template <class Tobj>
    bool node<Tobj>::isEmpty(node &head){
        if(head==NULL)
        return true;
        else
        return false;
    }
    template <class Tobj>
            char node<Tobj>::menu(){
                char choice;
                cout<<"Menu.\n";
                cout<<"1. Add an item.\n";
                cout<<"2. Remove an item.\n";
                cout<<"3, Show the list.\n";
                cout<"4. Exit \n";
                cin>>choice;
                return choice;

            }
            template<class Tobj>
            void node<Tobj>::insertAsFist(node &head,node &last,Tobj 
&objADD){
                node *temp=new node;
                temp->obj_add=objADD;
                temp->next=NULL;
                head=temp;
                last=temp;
            }
            template<class Tobj>
            void node<Tobj>::insert(node &head,node &last,Tobj &objADD){
                if(isEmpty(head))
                insertAsFirstElement(head,last,number);
                else{
                    node *temp=new node;
                    temp->obj_add=NULL;
                    last->next=temp;
                    last=temp;
                }
            }
            template <class Tobj>
            void node<Tobj>::remove(node &head,node &last){
                if(isEmpty(head))
                cout<<"The list is already empty.\n";
                else if (head==last){
                    delete head;
                    head==NULL;
                    last==NULL;
                }
                else {
                    node *temp=head;
                    head=head->next;
                    delete temp;

                }
            }
            template <class Tobj>
            void node<Tobj>::showlist(node &curret){
                if(isEmpty(current))
                cout<<"The list is empty.\n";
                else {
                    cout<<"The list contains:\n";
                while (current!=NULL){
                    cout<<current->obj_add.Show()<<endl;
                    current=current->next;
                }
                }
            }

//----------------------------------

........................................................... ...........................................................