mardi 30 juin 2015

Pass by value and move, or two methods

Assume I have the following class, which has a method set_value. Which implementation is better?

class S {
public:
  // a set_value method

private:
  Some_type value;
};

Pass by value, then move

void S::set_value(Some_type value)
{
  this->value = std::move(value);
}

Define two overloaded methods

void S::set_value(const Some_type& value)
{
  this->value = value;
}

void S::set_value(Some_type&& value)
{
  this->value = std::move(value);
}

The first approach requires definition of one method only while the second requires two.

However, the first approach seems to be less efficient:

  1. Copy/Move constructor for the parameter depending on the argument passed
  2. Move assignment
  3. Destructor for the parameter

While for the second approach, only one assignment operation is performed.

  1. Copy/Move assignment depending on which overloaded method is called

So, which implementation is better? Or does it matter at all?

And one more question: Is the following code equivalent to the two overloaded methods in the second approach?

template <class T>
void S::set_value(T&& value)
{
  this->value = std::forward<T>(value);
}

I need to sort a vector<vector<int> > vecOfVectors; lexicographically.

So, my vecOfVectors before sorting lexicographically is:

((0,100,17,2),(2,3,1,3),(9,92,81,8),(0,92,92,91),(10,83,7,2),(1,2,3,3))

In order to do so I am using the following function:

std::sort(vecOfVectors.begin(),vecOfVectors.end(),lexicographical_compare);

So, my vecOfVectors after sorting lexicographically is now:

((0,92,92,91),(0,100,17,2),(1,2,3,3),(2,3,1,3),(9,92,81,8),(10,83,7,2))

Now given a vector I need to search its position in this sorted vecOfVectors -- somthing like binary search will work great. Is there some build in function in c++ stl that I can use to perform the binary search?

For example: the position of (0,92,92,91) is 0; position of (0,100,17,2) is 1; position of (1,2,3,3) is 2; position of (2,3,1,3) is 3; position of (9,92,81,8) is 4; position of (10,83,7,2) is 5.

std::move in g++ 5.1

The following snippet fails to compile with g++ 5.1:

class C {
public:
    C(C &&other) {
        *this = std::move(other);
    }

    C& operator=(C &&other) { return *this; }
};

The error message is:

In constructor 'C::C(C&&)': 4:17: error: 'move' is not a member of 'std' 

I am definitely supplying the -std=c++11 flag. You can try this example yourself: http://cpp.sh/6cry

Am I missing something here? I've had code with std::move compile on this compiler before. This same code compiles fine with Visual Studio 2013's compiler.

C++ Performing mapping between vectors and unique numbers and vice versa

I need to create a dictionary data structure which maps vector to unique numbers and vice versa:

For example for mapping vectors to unique numbers, I can do the following:

   vector   ---------> unique number
   (0,7,8)                   0
   (0,8,10)                  1
   (1,2,9)                   2
   (1,2,10)                  3
   (1,3,1)                   4

Then I need to map back unique numbers to vectors, e.g. given below:

   unique numbers --------> vector   
   0                        (0,7,8)    
   1                        (0,8,10)   
   2                        (1,2,9)    
   3                        (1,2,10)   
   4                        (1,3,1)    

I tried to do this mapping by creating a structure of integers and vectors -- however, this turned to be very inefficient. Is there some c++ data structure which can perform the forward and reverse mapping efficiently.

Is using std::max for comparing two doubles safe?

I know for comparing two doubles we have to do something like this

bool AreSame(double a, double b)
{
    return fabs(a - b) < EPSILON;
}

But I do not know that does std::max compares two doubles the same way or if not the same way safely? That is what will be the answer if I call std::max(0.1,0.11) . I am getting right results but still , I am not sure! Morover I used it last night at codeforces and got my solution accepted!

Is this SFINAE technique involving variadic templates valid? [duplicate]

libstdc++'s implementation of std::experimental::optional uses a SFINAE technique that seems to work with gcc, but not with clang.

I've reduced it to the following minimal example:

// Standard enable_if class
template <bool> struct enable_if {};
template <> struct enable_if<true> { typedef int type; };

// An example trait
template <typename> struct trait { static const bool value = true; };

// Overload to call if the trait is false
template<typename T, typename enable_if<!trait<T>::value>::type...>
void foo(T);

// Overload to call if the trait is true
template<typename T, typename enable_if<trait<T>::value>::type...>
void foo(T);

// Call site
void bar() {
    foo(0);
}

This compiles with gcc, but not with clang. Clang's error is:

test.cpp:18:5: error: call to 'foo' is ambiguous
    foo(0);
    ^~~
test.cpp:11:6: note: candidate function [with T = int, $1 = <>]
void foo(T);
     ^
test.cpp:14:6: note: candidate function [with T = int, $1 = <>]
void foo(T);
     ^

Clearly, gcc is discarding the first overload as a candidate because it encounters a substitution failure while subtituting T = int into typename enable_if<!trait<T>::value>::type.

Clang, on the other hand, seems to skip performing that substitution, perhaps because it realizes that there are zero template arguments bound to that parameter pack. As a result, it doesn't encounter a substitution failure, and the first overload remains viable.

Who is right?

Understanding memory_order_relaxed

I am trying to understand the specifics of memory_order_relaxed. I am referring to this link : CPP Reference.

#include <future>
#include <atomic>

std::atomic<int*> ptr {nullptr};

void fun1(){
        ptr.store(new int{0}, std::memory_order_relaxed);
}

void fun2(){
        while(!ptr.load(std::memory_order_relaxed));
}

int main(){
        std::async(std::launch::async, fun1);
        std::async(std::launch::async, fun2);
}

Question 1: In the code above, is it technically possible for fun2 to be in an infinite loop where it sees the value of ptr as nullptr even if the thread that sets ptr has finished running?

If suppose, I change the code above to something like this instead:

#include <future>
#include <atomic>

std::atomic<int> i {0};
std::atomic<int*> ptr {nullptr};

void fun1(){
        i.store(1, std::memory_order_relaxed);
        i.store(2, std::memory_order_relaxed);
        ptr.store(new int{0}, std::memory_order_release);

}

void fun2(){
        while(!ptr.load(std::memory_order_acquire));
        int x = i.load(std::memory_order_relaxed);
}

int main(){
        std::async(std::launch::async, fun1);
        std::async(std::launch::async, fun2);
}

Related Question: Is it possible in the code above for fun2 to see the value of atomic i as 1 or is it assured that it will see the value 2?

is the overloaded operator of a std::deque slower than that of a vector

From here I read that for a std::deque the time complexity of retrieving a value using the operator [] is constant. From here I read that time complexity of using the same operator for a std::vector is constant. However in this question Why would I prefer using vector to deque one of the answers with a significant upvote count states that

std::deque doesn't have guaranteed continuous memory - and it's often somewhat slower for indexed access. A deque is typically implemented as a "list of vector".

My question is if its true that retrieval of an index location in a vector is faster than a deque (although both are constant). IS the reason for this is that a double lookup is required for a deque as opposed to a single lookup ?

g++: linker issue on Mac OS X - Undefined symbols for architecture x86_64

I asked this question before here, but got no answer, just a "detour". Now, I am trying to find an actual solution to the problem (stated below). Before anybody says that this question was asked before, I want to say that I tried solutions provided here, here, here, and here - nothing helped :(

The problem is that linker says Undefined symbols for architecture x86_64 without any other warnings or errors. The invocation, full error message, and the code being compiled is shown below.

Note: If I define the operator<< inline, the problem disappears, but this is not really a solution, but a detour :)

Thank you in advance :)

Invocation and Environment

Environment:

  • OS: Mac OS X Yosemite (10.10.4)
  • XCode: 6.4 (6E35b)
  • uname -a: Darwin wireless1x-XXX-XXX-XXX-XXX.bu.edu 14.4.0 Darwin Kernel Version 14.4.0: Thu May 28 11:35:04 PDT 2015; root:xnu-2782.30.5~1/RELEASE_X86_64 x86_6
  • g++ --version: Configured with: --prefix=/Applications/http://ift.tt/1d5DwEL --with-gxx-include-dir=/usr/include/c++/4.2.1 Apple LLVM version 6.1.0 (clang-602.0.53) (based on LLVM 3.6.0svn) Target: x86_64-apple-darwin14.4.0 Thread model: posix

Run arguments:

g++ -std=c++11 -lm -stdlib=libc++ tstLinkedList1.cpp -o tstLinkedList1

or

g++ -std=c++11 -lm -stdlib=libstdc++ tstLinkedList1.cpp -o tstLinkedList1

I also tried adding -lc++ in both cases - same thing :(

Error

Edit: Error happens in the operator<< overloading, which is defined in the very end of the LinkedList.hpp file below

using -stdlib=libc++:

Undefined symbols for architecture x86_64:
  "operator<<(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, LinkedList<int> const&)", referenced from:
      _main in tstLinkedList1-66598f.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

using -stdlib=libstdc++:

Undefined symbols for architecture x86_64:
  "operator<<(std::ostream&, LinkedList<int> const&)", referenced from:
      _main in tstLinkedList1-8d9300.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Codes

LinkedList.hpp:

#pragma once

template <typename T> class LinkedList;
template <typename T>
std::ostream& operator<<(std::ostream& os, const LinkedList<T>& list);


/** Node class
 * 
 * @tparam T template type
 */
template <typename T>
class Node {
private:
  T _elem;                      //!< Stored value
  Node<T>* _next;               //!< Next element

  friend class LinkedList<T>;   //!< Friend class
};


/** Singly Linked List
 *
 * @tparam T template type
 */
template <typename T>
class LinkedList {
public:
  LinkedList();
  ~LinkedList();
  std::size_t size() const;
  bool empty() const;
  const T& front() const;
  void addFront(const T& e);
  void removeFront();
public:
  // Housekeeping
  friend std::ostream& operator<<(std::ostream& os, const LinkedList<T>& list);
private:
  Node<T>* _head;
  std::size_t _size;
};

/** Constructor */
template <typename T>
LinkedList<T>::LinkedList() : _head(nullptr), _size(0) {}

/** Destructor */
template <typename T>
LinkedList<T>::~LinkedList() {
  while (!empty()) removeFront();
}

/** Number of elements in the list
 * 
 * @returns std::size_t Number of elements in the list
 */
template <typename T>
std::size_t LinkedList<T>::size() const {
  return this->_size;
}

/** Empty?
 *
 * @returns bool True if empty
 */
template <typename T>
bool LinkedList<T>::empty() const {
  return _head == nullptr;
}

/** Get front element (read-only)
 *
 * @returns T
 */
template <typename T>
const T& LinkedList<T>::front() const {
  return _head->_elem;
}

/** Add element in the front of the list
 * 
 * @param e Element to be added
 */
template <typename T>
void LinkedList<T>::addFront(const T& e) {
  Node<T>* v = new Node<T>;
  v->_elem = e;
  v->_next = _head;
  _head = v;
  _size++;
}

/** Remove the first element */
template <typename T>
void LinkedList<T>::removeFront() {
  if (empty()) return;
  Node<T>* old = _head;
  _head = old->_next;
  _size--;
  delete old;
}

/** Operator<< for the linked list
 *
 * @returns std::ostream
 * @param LHS->std::ostream
 * @param RHS->LinkedList<T>
 */
template <typename T>
std::ostream& operator<<(std::ostream& os, const LinkedList<T>& list) {
  os << "TEST";
  return os;
}

tstLinkedList1.cpp:

#include <iostream>
#include "LinkedList.hpp"

using namespace std;

int main() {
  LinkedList<int> ll1;
  ll1.removeFront();
  ll1.addFront(1);

  std::cout << ll1 << std::endl;
}

Make std::getline() on std::stringstream block on eof (or find alternative stream class)

What I am looking for

A pipe like stream, connecting std::istream with std::ostream. I should be able to write something to the std::ostream part and then read it from the std::istream part. When calling std::getline() on the istream part, it should block until data from the std::ostream part is available.

std::stringstream does pretty much what I want, except for it doesn't block. When calling std::getline() on an empty std::stringstream, it just returns and sets the eof() flag.

Why I need this

For testing a Console class that does input/output with streams, I need the counterparts to read the output of the Console class and produce input for it. std::getline() on std::cin is blocking, so the pipe stream should also block if it is empty.

Details

I have a Console class which handles console input and output. A simplified version is like

class Console {
public:
  Console(): Console(std::cin, std::cout) {}
  Console(istream &istr, ostream &ostr): _istr(istr), _ostr(ostr) {}

  string ask(const string &question) {
    _istr << question << "\n";
    string answer;
    std::getline(_ostr, answer);
    return answer;
  }
private:
  istream &_istr;
  ostream &_ostr;
};

In production, _istr will be set to std::cin and _ostr will be set to std::cout. In test cases, I will set them to own in-memory stream classes.

For this, I wanted to use std::stringstream, because I can then test the output with

void EXPECT_OUTPUT_LINE(const string &expected) {
  string actual;
  std::getline(ostr, actual);
  EXPECT_EQ(expected, actual);
}

and send input with

void sendInputLine(const string &line) {
  istr << line << "\n";
}

In this case, the Console class runs in a different thread, because it should block its thread when trying to read from _istr. The general test case would then look like

TEST(ConsoleTest, MyTest) {
  stringstream istr, ostr;
  future<string> answer = std::async(std::launch::async, [&] () {
    Console(ostr, istr).ask("Question?");
  });
  EXPECT_OUTPUT_LINE("Question?");
  sendInputLine("Answer");
  EXPECT_EQ("Answer", answer.get());
}

However, it turns out std::getline() isn't blocking. When used with std::cin, it does block. When used with an empty std::stringstream, std::getline immediately returns and sets the eof flag.

So even if my test case says sendInputLine("bla"), this doesn't have any effect, because the Console class doesn't wait for it and its std::getline() call might already have returned in the past on the empty stringstream.

The same problem is in the EXPECT_OUTPUT_LINE. It calls std::getline to get the output of the Console class, but it doesn't wait for it. If this happens before the Console class actually made any output, then it just returns and sets the eof flag for the stringstream.

C++11 / C++03 and std::vector thread safety

I am reading about thread safety of various stl containers from this link Now I came across this point which states for C++11 only

Different elements in the same container can be modified concurrently by different threads, except for the elements of std::vector<bool> (for example, a vector of std::future objects can be receiving values from multiple threads)

Does this mean if I have a method such as this which is being used by multiple threads simultaneously (notice the method does not have any locks)

void ChangeValue(int index , int value)
{
   someVector[index] = value;
}

Is the above method safe. My understanding is that it is safe for C++11 only. However when I look at the other statement mentioned in the link

All const member functions can be called concurrently by different threads on the same container. In addition, the member functions begin(), end(), rbegin(), rend(), front(), back(), data(), find(), lower_bound(), upper_bound(), equal_range(), at(), and, except in associative containers, operator[], behave as const for the purposes of thread safety (that is, they can also be called concurrently by different threads on the same container). More generally, the C++ standard library functions do not modify objects unless those objects are accessible, directly or indirectly, via the function's non-const arguments, including the this pointer.

I come to the conclusion that in C++03 the above method can be safely used as well. Kindly let me know if my understanding is correct.

Casting function pointer to void(*)(), then recasting to original type

This question is for tests purposes, nothing more.

I'm currently trying to store function pointers with a different number of parameters (and these parameters can have different types).

Basically, I've coded the following code snippet in C++11:

#include <functional>
#include <iostream>

void fct(int nb, char c, int nb2, int nb3) {
  std::cout << nb << c << nb2 << nb3 << std::endl;
}

template <typename... Args>
void call(void (*f)(), Args... args) {
  (reinterpret_cast<void(*)(Args...)>(f))(args...);
}

int main(void) {
  call(reinterpret_cast<void(*)()>(&fct), 42, 'c', 19, 94);
}

I convert a void(*)(int, char, int, int) function pointer into a generic void(*)() function pointer. Then, by using variadic template parameters, I simply recast the function pointer to its original type and call the function with some parameters.

This code compiles and runs. Most of the times, it displays the good values. However, this code gives me some Valgrind errors under Mac OS (concerning uninitialized values) and it sometimes displays some unexpected garbage.

==52187== Conditional jump or move depends on uninitialised value(s)
==52187==    at 0x1004E4C3F: _platform_memchr$VARIANT$Haswell (in /usr/lib/system/libsystem_platform.dylib)
==52187==    by 0x1002D8B96: __sfvwrite (in /usr/lib/system/libsystem_c.dylib)
==52187==    by 0x1002D90AA: fwrite (in /usr/lib/system/libsystem_c.dylib)
==52187==    by 0x100025D29: std::__1::__stdoutbuf<char>::overflow(int) (in /usr/lib/libc++.1.dylib)
==52187==    by 0x10001B91C: std::__1::basic_streambuf<char, std::__1::char_traits<char> >::xsputn(char const*, long) (in /usr/lib/libc++.1.dylib)
==52187==    by 0x10003BDB0: std::__1::ostreambuf_iterator<char, std::__1::char_traits<char> > std::__1::__pad_and_output<char, std::__1::char_traits<char> >(std::__1::ostreambuf_iterator<char, std::__1::char_traits<char> >, char const*, char const*, char const*, std::__1::ios_base&, char) (in /usr/lib/libc++.1.dylib)
==52187==    by 0x10003B9A7: std::__1::num_put<char, std::__1::ostreambuf_iterator<char, std::__1::char_traits<char> > >::do_put(std::__1::ostreambuf_iterator<char, std::__1::char_traits<char> >, std::__1::ios_base&, char, long) const (in /usr/lib/libc++.1.dylib)
==52187==    by 0x1000217A4: std::__1::basic_ostream<char, std::__1::char_traits<char> >::operator<<(int) (in /usr/lib/libc++.1.dylib)
==52187==    by 0x1000011E8: fct(int, char, int, int) (in ./a.out)
==52187==    by 0x1000013C2: void call<int, char, int, int>(void (*)(), int, char, int, int) (in ./a.out)
==52187==    by 0x100001257: main (in ./a.out)

I find this quite curious because when I call the function, I have recasted the function pointer to its original type. I thought it was similar to casting a datatype to void* and then recasting it into the original datatype.

What is wrong with my code? Can't we cast function pointers to void(*)() pointer and then recast this pointer to the original function pointer signature?

If not, is there some other ways to achieve this? I'm not interested in std::bind which does not what I want.

Vectors in c++, contain unique elements

I have a program here that is supposed to remove all repeating elements in a vector and only have unique elements.

void simplifyVector(vector<string> i){

/*vector<string>*/;

sort(i.begin(), i.end());

auto iter = unique(i.begin(), i.end());

while (iter != i.end())
{
    i.erase(iter);
}



  for (const auto &s : i)
    {
        cout << s << " ";
    }
    cout << endl;


}

Sadly, i get the run time error vector iterator incompatible .

Help please!

Iterating over maps with vectors as a value

I am trying to create a map which takes in a string as a key and has a vector of unsigned ints as its value. One of my functions, takes in this map and is declared as follows:

void setAllDAC(std::map<string, std::vector<unsigned int> > dacs){
    //program the control register
    progdac(dacs[k_DACName_ChipContReg][1],dacs[k_DACName_ChipContReg][0]);
    //make iterator
    std::map<std::string, std::vector<unsigned int> > ::iterator it;
    for(it = dacs.begin(); it !=dacs.end(); it ++){
        std::string stmp = it ->first;
        std::vector vtmp = it ->second;
            if(stmp != k_DACName_ChipContReg){
                progdac(vtmp[1],vtmp[0]);
            }
    }
}

Where the header of the function progdac is as follows:

int progdac(int dacaddress, int dacvalue)

When I try to compile this program I get the following error:

src/common/PixelFECInterface.cc:2674: error: no match for ‘operator=’ in ‘it >=...

and

src/common/PixelFECInterface.cc:2670: error: passing ‘const std::map<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::vector<unsigned int, std::allocator<unsigned int> >, std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::vector<unsigned int, std::allocator<unsigned int> > > > >’ as ‘this’ argument of ‘_Tp& std::map

I should also point out that line 2670 corresponds to the call to progdac and line 2674 corresponds to the for loop. What exactly is wrong with the code?

C++ wcout unocode(Cyrillic, Japanese)

Good day. In my application i use cyrillic and japanese character. When i use _setmode(_fileno(stdout), _O_U16TEXT).OS Windows

My output data look like 1. cyrillic : Привет 2. japanese : ??? What could be the problem?

C++ variadic template, recursion decltype

I know there are already a lot of questions concerning this topic, but so far I found no response that satisfactorily answers the following questions. Given the following code.

#include <utility>

template<typename T, typename K>
std::pair<T, K> pair()
{
    return std::pair<T, K>();
}

template<typename T, typename...K>
std::pair<T, decltype(pair<K...>())> pair()
{
    return std::pair<T, decltype(pair<K...>())>();
}


int main(int argc, char **argv)
{
    auto m2 = pair<int, int>();
    auto m3 = pair<int, int, int>();    
    auto m4 = pair<int, int, int, int>();   // <- Compile Error here
    return 0;
}

A call to

pair<int, int>() 

shall return an object

std::pair<int, int>

and this works perfectly for up to three template parameters. As mentioned in the code calling the pair function with four template parameters fails and g++ (5.1.0) returns the following error.

main.cpp: In function 'int main(int, char**)':
main.cpp:20:37: error: no matching function for call to 'pair()'
  auto m4 = pair<int, int, int, int>(); // <- Compile Error here
                                     ^
main.cpp:4:17: note: candidate: template<class T, class K> std::pair<_T1, _T2> pair()
 std::pair<T, K> pair()
                     ^
main.cpp:4:17: note:   template argument deduction/substitution failed:
main.cpp:20:37: error: wrong number of template arguments (4, should be 2)
  auto m4 = pair<int, int, int, int>(); // <- Compile Error here
                                     ^
main.cpp:10:38: note: candidate: template<class T, class ... K> std::pair<T, decltype (pair<K ...>())> pair()
 std::pair<T, decltype(pair<K...>())> pair()
                                      ^
main.cpp:10:38: note:   template argument deduction/substitution failed:
main.cpp: In substitution of 'template<class T, class ... K> std::pair<T, decltype (pair<K ...>())> pair() [with T = int; K = {int, int, int}]':
main.cpp:20:37:   required from here
main.cpp:10:33: error: no matching function for call to 'pair()'
 std::pair<T, decltype(pair<K...>())> pair()
                                 ^
main.cpp:4:17: note: candidate: template<class T, class K> std::pair<_T1, _T2> pair()
 std::pair<T, K> pair()
                 ^
main.cpp:4:17: note:   template argument deduction/substitution failed:
main.cpp:10:33: error: wrong number of template arguments (3, should be 2)
 std::pair<T, decltype(pair<K...>())> pair()
                                 ^

Therefore my questions are:
- Is this issue g++ related?
- What is the designated way to solve this problem?

Thanks four your help!

finding shortest path of all nodes from a given node using BFS

when i increase or decrease INF value the Output Behaves Unexpectedly.. I think INF should not have any effect on the output.. length of each edge is 6 for input 1 4 2 1 2 1 3 1 the output is 6 6 -1 when I change INF to 1e8 the output is 0 0 0

 #include<iostream>
 #include<vector>
 #include<queue>
 #include<cstring>

 using namespace std;

 #define MAX 2000
  #define INF 1000000

 vector<int> adj[MAX];
 int d[MAX];
  bool visited[MAX];

 void initialise(){
   for(int i=0;i<=MAX;i++){
  visited[i]=false;
   }
  }

  void shortestPathBfs(int start){

  queue<int> q;
   q.push(start);
     visited[start]=true;
     d[start]=0;

  while(!q.empty()){
      int p=q.front();
       q.pop();
      for(int i=0;i<adj[p].size();i++){
           int v=adj[p][i];
            if(!visited[v] && d[v]>d[p]+6){
                d[v]=d[p]+6;
                q.push(v);
               visited[v]=true;
            }
        }
       }
      }

         int main(){
         int T,N,M,S,x,y;
            cin>>T;
          while(T--){
        cin>>N>>M;
      for(int i=0;i<M;i++){
         cin>>x>>y;
          adj[x].push_back(y);
          adj[y].push_back(x);
      }
      cin>>S;

       initialise();
         memset(d,INF,sizeof(d));
         shortestPathBfs(S);

   for(int i = 1; i <=N; i++) {
        if(i == S)
            continue;
        if(d[i] >= INF)
              cout<<"-1"<<" ";
        else
            cout<<d[i]<<" ";
          }
       }

      }

How to avoid move constructor when I use implicit conversion in VS 11.0

First I defined a template overloading function(c:\git\feim\core\qpropertylist.hpp)

template<class T>
inline const T QPropertyList::get(const std::string& key, const T& defVal) const
{ 
    const_iterator it = find(key);
    if (it!=this->end())
    {


        it->second.setKey(key);  //To do : remove this
        return it->second;

    } else {
        return defVal;
    }
}

In the source file( c:\git\feim\core\capfloorleg.c(77) ), I begin to make this template instantiation

tenor2 = aPL.get("Tenor2", std::string(""));

Then I get the error as follows:

>c:\git\feim\core\qpropertylist.hpp(114): error C2668: 'std::basic_string<_Elem,_Traits,_Alloc>::basic_string' : ambiguous call to overloaded function
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>,
1>              _Alloc=std::allocator<char>
1>          ] (..\..\core\capFloorLeg.C)
1>          c:\program files (x86)\microsoft visual studio 11.0\vc\include\xstring(896): could be 'std::basic_string<_Elem,_Traits,_Alloc>::basic_string(std::basic_string<_Elem,_Traits,_Alloc> &&) throw()'
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>,
1>              _Alloc=std::allocator<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 11.0\vc\include\xstring(789): or       'std::basic_string<_Elem,_Traits,_Alloc>::basic_string(const _Elem *)'
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>,
1>              _Alloc=std::allocator<char>
1>          ]
1>          while trying to match the argument list '(STC::QProperty)'
1>          c:\git\feim\core\capfloorleg.c(77) : see reference to function template instantiation 'const T STC::QPropertyList::get<std::basic_string<_Elem,_Traits,_Alloc>>(const std::string &,const T &) const' being compiled
1>          with
1>          [
1>              T=std::basic_string<char,std::char_traits<char>,std::allocator<char>>,
1>              _Elem=char,
1>              _Traits=std::char_traits<char>,
1>              _Alloc=std::allocator<char>
1>          ]

Error 2 error C2668: 'std::basic_string<_Elem,_Traits,_Alloc>::basic_string' : ambiguous call to overloaded function c:\git\feim\core\qpropertylist.hpp 111 1 core

I know this error is caused by the move constructor when I want to use implicit conversion (std::string(""))introduced by VS11.0, since in the VS8, everything is fine.

Anyone have a good idea how to avoid this error? Thanks a lot!!

Which Poco C++ PEM file to use?

When creating an application that uses Poco's HTTPSClient, which PEM file should I use -- "any.pem" or "rootcert.pem"? The sample app uses both, but my app is not based on the Poco "Application" class and my app is just consuming APIs from an HTTPS server (i.e. doesn't need private keys).

The server I'm connecting to has a certificate from a "valid authority" and is a wildcard cert (*.company.com).

Thanks for your help.

How to use another class as a class template specialization

I have a hybrid-lock class that spin tries a lock for a (compile time fixed) number of spins before falling back to blocking on a std::mutex until the lock becomes available.

Simplified:

#include <mutex>

template<unsigned SPIN_LIMIT>
class hybrid_lock {
public:
    void lock(){
        for(unsigned i(0);i<SPIN_LIMIT;++i){
            if(this->mMutex.try_lock()){
                return;        
            }
        } 
        this->mMutex.lock();
    }
    void unlock(){
        this->mMutex.unlock();
    }
private:
    std::mutex mMutex;
};

In the special case of SPIN_LIMIT==0 this falls back to being a 'plain' std::mutex (i.e. no visible spins).

So I've specialized that to:

template<>
class hybrid_lock<0> : public std::mutex {};

It works fine but is that the approved way of specializing class templates to be another (pre-existing) template?

can't run the program compiled usig minGW in windows using regex c++11 std

This program compiles fine without any error but when i run the program it exits unexpectedly saying it ran into some problem .

Analyzing using gdb the program runs into segmentation fault. I dont know much about gdb so can't examine thoroughly if somebody can reproduce the problem and explain the error that will be helpful.

Also what can i do to rectify the problem.

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

int main()
{
   bool found;
   cmatch m;
try
{
    found = regex_search("<html>blah blah blah </html>",m,regex("<.*>.* </\\1"));
    cout<< found<<endl<<m.str();
}
catch(exception & e)
{

    cout<<e.what();
}

return 0;


}

is uniform initialization & list initialization same in C++11?

I was reading about list initialization on here. It uses braces for initialization.

So, are both the terms uniform initialization & list initialization same or different in C++11?

"Overloading" constructors with SFINAE

Why does the the following attempt at overloading the constructor Foo::Foo fail? Also, I'd appreciate alternatives/workarounds

#include <vector>
#include <type_traits>

namespace xyz
{   
    struct MemoryManager{};

    template<typename T , typename Alloc=MemoryManager>
    class vector
    {
    };
}


template<typename T, template<typename,typename> class V , typename A>
struct Foo
{
    template<typename U = T ,
             typename Dummy = typename std::enable_if<
                 std::is_same<std::vector<U>, V<U,A> >::value >::type >
    Foo() // when instantiated with the std vector
    {
    }

    template<typename U = T ,
             typename Dummy = typename std::enable_if<
                 std::is_same<xyz::vector<U>, V<U,A> >::value >::type >
    Foo() // when instantiated with my custom vector
    {
    }   
};

int main()
{
}

Error message:

23:3: error: ‘template<class T, template<class, class> class V, class A> template<class U, class Dummy> Foo<T, V, A>::Foo()’ cannot be overloaded
   Foo() // when instantiated with my custom vector

18:3: error: with ‘template<class T, template<class, class> class V, class A> template<class U, class Dummy> Foo<T, V, A>::Foo()’
   Foo() // when instantiated with the std vector

Standard output strange behavior

I have an issue using Eclipse cdt and I am facing a strange behavior:

cout << "Hello world" << endl;
aFunction();
// The output here is Hello world
// END

When I take off the endl the output is nothing

cout << "Hello world";
aFunction();
// No output
// END

and when I put the endl later it works fine :

cout << "Hello world";
aFunction();
cout << endl;
// output is Hello world
// END

Now, I can't provide the function code, because it will take me a thousand of lines.

However, I tried this with a function that does nothing void toto(){} and there was not this strange thing .

cout << "Hello world";
toto();
// Gives me Hello world
// END

What I want to know is what can cause this ??

EDIT : The tests with foo are tested alone (no other instructions), In the other tests, I initialize a structure that I give as a parameter to aFunction. The function uses some metaprogramming and there is a lot of code i need to show so you understand it.

Are C++ versions of C standard library functions in the std:: namespace? [duplicate]

"C++ Primer" (5th edition) states on page 91 the advantage of including the C++ version of a C standard library header instead of the .h version: this way the included names end up in the std:: namespace and do not pollute the global namespace.

I tried including cstdio and was surprised to observe that I can use printf() without specifying std::. Interestingly, including only iostream or only string is also sufficient to get access to a global printf(). Am I missing something?

I am compiling with g++ 4.8.2 with -Wall -Wextra -Werror -std=c++11.

C++ array of char using unique_ptr

First of all, I know this is not the best way to do this, I'm just looking how it should be done. I created a class called bord,which holds a member

        std::unique_ptr<std::unique_ptr<char>[] > char_bord;

Which should be the correct syntax, then I try to initialize this in the constructor:

bord::bord():char_bord(new std::unique_ptr<char>[10])
{
    //char_bord=new std::unique_ptr<char>[10]; //This did not seem to work aswell.
    for(int i=0;i<10;i++)
      char_bord[i]=new std::unique_ptr<char>[](new char[10]); 
    return;
}

This results in the following heap of errors, which I did not manage to decipher.

jelmer@jelmer-N56JN:~/Git/Board/lib$ g++ -std=c++0x bord.c
In file included from bord.c:1:0:
bord.h:20:1: error: new types may not be defined in a return type
 class bord
 ^
bord.h:20:1: note: (perhaps a semicolon is missing after the definition of ‘bord’)
bord.c:3:12: error: return type specification for constructor invalid
 bord::bord():char_bord(new std::unique_ptr<char>[10])
            ^
bord.c: In constructor ‘bord::bord()’:
bord.c:7:46: error: expected primary-expression before ‘]’ token
       char_bord[i]=new std::unique_ptr<char>[](new char[10]); 
                                              ^
bord.c:7:60: error: parenthesized initializer in array new [-fpermissive]
       char_bord[i]=new std::unique_ptr<char>[](new char[10]); 
                                                            ^
bord.c:7:19: error: no match for ‘operator=’ (operand types are ‘std::unique_ptr<char>’ and ‘std::unique_ptr<char>*’)
       char_bord[i]=new std::unique_ptr<char>[](new char[10]); 
                   ^
bord.c:7:19: note: candidates are:
In file included from /usr/include/c++/4.9/memory:81:0,
                 from bord.h:19,
                 from bord.c:1:
/usr/include/c++/4.9/bits/unique_ptr.h:249:7: note: std::unique_ptr<_Tp, _Dp>& std::unique_ptr<_Tp, _Dp>::operator=(std::unique_ptr<_Tp, _Dp>&&) [with _Tp = char; _Dp = std::default_delete<char>]
       operator=(unique_ptr&& __u) noexcept
       ^
/usr/include/c++/4.9/bits/unique_ptr.h:249:7: note:   no known conversion for argument 1 from ‘std::unique_ptr<char>*’ to ‘std::unique_ptr<char>&&’
/usr/include/c++/4.9/bits/unique_ptr.h:269:2: note: template<class _Up, class _Ep> typename std::enable_if<std::__and_<std::is_convertible<typename std::unique_ptr<_Up, _Ep>::pointer, typename std::unique_ptr<_Tp, _Dp>::_Pointer::type>, std::__not_<std::is_array<_Up> > >::value, std::unique_ptr<_Tp, _Dp>&>::type std::unique_ptr<_Tp, _Dp>::operator=(std::unique_ptr<_Up, _Ep>&&) [with _Up = _Up; _Ep = _Ep; _Tp = char; _Dp = std::default_delete<char>]
  operator=(unique_ptr<_Up, _Ep>&& __u) noexcept
  ^
/usr/include/c++/4.9/bits/unique_ptr.h:269:2: note:   template argument deduction/substitution failed:
bord.c:7:19: note:   mismatched types ‘std::unique_ptr<_Tp, _Dp>’ and ‘std::unique_ptr<char>*’
       char_bord[i]=new std::unique_ptr<char>[](new char[10]); 
                   ^
In file included from /usr/include/c++/4.9/memory:81:0,
                 from bord.h:19,
                 from bord.c:1:
/usr/include/c++/4.9/bits/unique_ptr.h:278:7: note: std::unique_ptr<_Tp, _Dp>& std::unique_ptr<_Tp, _Dp>::operator=(std::nullptr_t) [with _Tp = char; _Dp = std::default_delete<char>; std::nullptr_t = std::nullptr_t]
       operator=(nullptr_t) noexcept
       ^
/usr/include/c++/4.9/bits/unique_ptr.h:278:7: note:   no known conversion for argument 1 from ‘std::unique_ptr<char>*’ to ‘std::nullptr_t’

What am I doing wrong, assuming I am doing something wrong.

why so many copying while transforming/copying vector

Why so many calls to copy cons, i would expect only last nine of them? Or even not at all duy to return value optimization.

struct C
{
    int _i;
    C(int i) : _i(i) {}
    C(const C& other) { cout << "copy cons from " << other._i << " to " << _i << endl; _i = other._i; }
};
int _tmain(int argc, _TCHAR* argv[])
{
    vector<int> vi{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    vector<C> vc;
    transform(vi.begin(), vi.end(), back_inserter(vc), 
        [](int i) 
    { 
        return C(i); 
    });
}

Output:

copy cons from 1 to - 842150451
copy cons from 1 to - 842150451
copy cons from 2 to - 842150451
copy cons from 1 to - 842150451
copy cons from 2 to - 842150451
copy cons from 3 to - 842150451
copy cons from 1 to - 842150451
copy cons from 2 to - 842150451
copy cons from 3 to - 842150451
copy cons from 4 to - 842150451
copy cons from 1 to - 842150451
copy cons from 2 to - 842150451
copy cons from 3 to - 842150451
copy cons from 4 to - 842150451
copy cons from 5 to - 842150451
copy cons from 6 to - 842150451
copy cons from 1 to - 842150451
copy cons from 2 to - 842150451
copy cons from 3 to - 842150451
copy cons from 4 to - 842150451
copy cons from 5 to - 842150451
copy cons from 6 to - 842150451
copy cons from 7 to - 842150451
copy cons from 8 to - 842150451
copy cons from 9 to - 842150451

lundi 29 juin 2015

c++11 chrono unreferenced local variable

When I use the following code to perform some action for 1 second, I get a C4101 warning from Visual Studio: warning C4101: 'highResClock' : unreferenced local variable. I don't understand why I get this warning when I use highResClock twice after declaring it.

chrono::high_resolution_clock highResClock;
chrono::duration<int, ratio<1, 1> > dur(1);
chrono::time_point<chrono::high_resolution_clock> end = highResClock.now() + dur;

while (highResClock.now() < end)
{
    // do something repeatedly for 1 second
}

global declarations/initializations using static, const, constexpr

In C++ or C++11, for the following declarations//initializations,

// global scope
const int a = 1; // line 1
static const int b = 2; // line 2
constexpr int c = 3;  // line 3
static constexpr int d = 4; // line 4
constexpr int e = a + b + c*d; // line 5
static cosntexpr int f = a - b - c*d; // line 6

This question says at file scope there is no difference between line 1 and 2 in C++. How about line 3 and 4?

Are there differences between line 4 and 5?

Are there differences between line 5 and 6?

C++: new[] operator

#include <bits/stdc++.h>
#define _ ios::sync_with_stdio(0); cin.tie(0);
using namespace std;

int main(){_
    auto arr = new int[5];
    // int arr[5] = {1, 2, 3, 4, 5};
    for (auto i: arr){
        cout << i << ' ';
    }
}

Why isn't this working? I am getting a compile time error saying this.

C.cpp: In function 'int main()':
C.cpp:8:15: error: 'begin' was not declared in this scope
  for (auto i: arr){
               ^
C.cpp:8:15: note: suggested alternatives:
In file included from /usr/lib/gcc/x86_64-pc-cygwin/4.9.2/include/c++/x86_64-pc-cygwin/bits/stdc++.h:94:0,
                 from C.cpp:1:
/usr/lib/gcc/x86_64-pc-cygwin/4.9.2/include/c++/valarray:1206:5: note:   'std::begin'
     begin(const valarray<_Tp>& __va)
     ^
/usr/lib/gcc/x86_64-pc-cygwin/4.9.2/include/c++/valarray:1206:5: note:   'std::begin'
C.cpp:8:15: error: 'end' was not declared in this scope
  for (auto i: arr){
               ^
C.cpp:8:15: note: suggested alternatives:
In file included from /usr/lib/gcc/x86_64-pc-cygwin/4.9.2/include/c++/x86_64-pc-cygwin/bits/stdc++.h:94:0,
                 from C.cpp:1:
/usr/lib/gcc/x86_64-pc-cygwin/4.9.2/include/c++/valarray:1226:5: note:   'std::end'
     end(const valarray<_Tp>& __va)
     ^
/usr/lib/gcc/x86_64-pc-cygwin/4.9.2/include/c++/valarray:1226:5: note:   'std::end'

When I initialized array in commented way, it works fine. (obviously) So, I think problem is with new operator. But I don't understand what it is.

End of recursion specialization of inner template class

Consider this working code:

#include <typeinfo>

template <typename ...> struct A;

template <typename First, typename... Rest>
struct A<First, Rest...> {
    static void execute() {
        std::cout << typeid(First).name() << ' ';
        A<Rest...>::execute();
    }
};

template <>
struct A<> {
    static void execute() {}  // End of recursion.
};

int main() {
    A<char, bool, int>::execute();  // char bool int
}

So why does the end of recursion below not compile (error statements provided in comments):

#include <typeinfo>

template <typename ...> struct A;

template <typename... Ts>
struct A {
    template <typename...> struct B;
    template <typename...> static void execute();
};

template <typename... Ts>
template <typename First, typename... Rest>
struct A<Ts...>::B<First, Rest...> {
    static void execute() {
        std::cout << typeid(First).name() << ' ';
        B<Rest...>::execute();
    }
};

template <typename... Ts>
template <> // invalid explicit specialization before '>' token
struct A<Ts...>::B<> {  // template parameters not used in partial specialization: Ts
    static void execute() {}  // End of recursion
};

template <typename... Ts>
template <typename... Us>
void A<Ts...>::execute() {
    B<Us...>::execute();
}

int main() {
    A<char, bool, int>::execute<double, short, float>();
}

It does work when I use this end of recursion instead of above:

template <typename... Ts>
template <typename Last>
struct A<Ts...>::B<Last> {
    static void execute() {std::cout << typeid(Last).name();}
};

But I just want to know what's wrong with the original attempt.

C++ Regex from Visual Studio 2013 compatibility

This is a follow-up on a long journey where I've pulled my hair out extracting text from parsing GLSL shader files using regex in C++11 with VS 2013 rc5.

Here is the intendant result:

Real time work editor here!

The C++ equivalent looks like this, which is a copycat of the PHP version:

std::smatch u;
std::string s = l_shader->GetData();
std::smatch u;
std::regex_search(s.cbegin(), s.cend(), u, std::regex("<(\\S+)[!]>([.*\\s*\\S*]*?)<[!]\\S+>"));

Unfortunately, std::regex_search doesn't return any results. I've been banging my head trying to figure it out. What am I missing?

Wrapping std::async in a functor

I've been experimenting with modern C++ lately, and it lead me to wonder if I could use a functor to wrap an asynchronous operation in a function-like object.

I first found that std::async can be easily placed in a wrapper function, like so:

#include <iostream>
#include <functional>
#include <future>

template< typename Fn, typename... Args >
std::future< typename std::result_of< Fn( Args... ) >::type >
LaunchAsync( Fn&& fn, Args&&... args )
{
    return std::async( std::launch::async, fn, args... );
} 

using namespace std;

int main()
{
    auto addResult = LaunchAsync( []( int a, int b ) { return a + b; }, 1, 2 );   
    cout << addResult.get() << endl;
    return 0;
}

That gave me an idea to instead wrap it in a class, like this:

template< typename Fn >
class AsyncFunction
{
    Fn _fn;
public:
    AsyncFunction( Fn fn ) : _fn( fn ) { }
    template< typename... Args >
    std::future< typename std::result_of< Fn( Args... ) >::type >
    operator()( Args&&... args )
    {
        return std::async( std::launch::async, _fn, args... );
    }
};

I thought I could use this code to create global functions that always run async. My thinking was that it would look like this:

auto SubtractAsync = AsyncFunction( []( int a, int b ) { // does not work
    return a - b;
} );

Instead, I have to specify the function signature in the template brackets:

auto SubtractAsync = AsyncFunction< std::function< int( int, int ) > >( []( int a, int b ) {
    return a - b;
} );

int main()
{
    auto subtractResult = SubtractAsync( 7, 3 ); // works
    cout << subtractResult.get() << endl;
    return 0;
}

I guess it isn't really a big deal, but it's been bothering me. If the LaunchAsync() function doesn't require me to specify the function signature, then why does the AsyncFunction class require it?

Is there any kind of work-around to this?

Matrix c++ implementation

I tried to code matrix class in c++11. I am going to use it Berlekamp factorization; I got few errors while compilation. Please look at my code;

matrix.h

template <class T>
class Matrix {
private:
    T** m_table;
    size_t m_size;
public:
    Matrix(int size);
    Matrix(int size, const std::function<T(int, int)> & generator);
    Matrix(const Matrix & m);

    void set(int i, int j, T t);

    void resize(size_t size);

    T get(int i, int j) const;

    ~Matrix();
};

matrix.cpp

#include "matrix.h"


template <class T>
Matrix<T>::Matrix(int size): m_size(size) {
    m_table = new T*[size];
    for (size_t i = 0; i <size; i++) {
        m_table[i] = new T[size];
    }
}


template <class T>
Matrix<T>::Matrix(int size, const std::function<T(int i, int j)> & generator):
    Matrix(size) {
    for (size_t i = 0; i < size; i++) {
        for (size_t j = 0; j < size; j++)
            m_table[i][j] = generator(i, j);
    }
}



template <class T>
Matrix<T>::~Matrix() {
   if (m_size > 0)
       for (T* t : m_table)
           delete [] t;
}

template <class T>
T Matrix<T>::get(int i, int j) const {
    return m_table[i][j];
}

template <class T>
void Matrix<T>::set(int i, int j, T t) {
    m_table[i][j] = t;
}

template <class T>
Matrix<T>::Matrix(const Matrix & m) {
    resize(m.m_size);
    for (size_t i = 0; i < m_size; i++) {
        for (size_t j = 0; j < m_size; j++)
            m_table[i][j] = m.get(i, j);
    }
}


template <class T>
void Matrix<T>::resize(size_t size) {
    if (m_size > 0)
        for (T* t : m_table)
            delete [] t;
    m_size = size;
    m_table = new T*[size];
    for (size_t i = 0; i <size; i++) {
        m_table[i] = new T[size];
    }
}

In main.cpp

error: undefined reference to Matrix::~Matrix()

Matrix<GaloisFieldElement> Q = buildQ(p);

in buildQ.cpp

    ...
    auto generator = [&] (int i, int j) -> GaloisFieldElement {
        return get(p, i, j);
    };

error: undefined reference to Matrix::Matrix(int, std::function&)

    return Matrix<GaloisFieldElement>(deg, generator);
}

Where I made mistake?

Why use std::next instead of adding an integer to the pointer?

I just have a quick question. I can't figure out the benefits of using std::next over just adding the desired number of advancements to the pointer. A simple example:

 int main()
 {
     int arr [] = {1, 2, 3, 4, 5};
     cout << *(arr + 2) << ", ";    //example 1
     cout << *std::next(arr, 2) << endl;    //example 2
     return 0;
 }

Output: 3, 3

Logically, example 1 should be quicker, since no function is called, etc. Also, in the instance in which I ran this code, if I added a number that would cause the pointer to be out of bounds (e.g. 7), the compiler would throw an error in example 1, but would happily go ahead and give me a memory address in example 2. This contradicted what I thought at first: that std::next would give some kind of warning or something if the pointer was out of bounds.

Any enlightenment would be appreciated.

Overloading on valueness (rvalue/lvalue) of a function type

A little quiz:

#include <iostream>    

void foo(void(&f)(int))
{
    std::cout << "YOU LOSE" << std::endl;
}

void foo(void(&&f)(int))
{
     std::cout << "YOU WIN" << std::endl;
}

int main()
{
    //write winning code here!
    //(try to write something that will call the second overload of foo)
    return 0;
}

Is it possible to win? :)

I have to write something here, because stackoverflow wouldn't let me post something that is "mostly code". So here: blahblahblah.

How to declare unique_ptr of vector?

I am trying to declare a global vector of MyClass using unique_ptr.

*glo.h

extern std::unique_ptr<std::vector<MyClass>> gl_vec;

*glo.cpp

std::unique_ptr<std::vector<MyClass>> gl_vec;

And in the file where I initialize and use it for the first time in a different *.cpp file:

#include "glo.h"

gl_vec = std::unique_ptr<std::vector<MyClass>> ();

cout << "gl_vec size = " << (*gl_vec).size() << endl; // crashes here

Things keep crashing when I use the pointer. Anyone see what I'm doing wrong?

Passing a reference-to-function as a universal reference

I'm struggling to understand what exactly happens when passing a reference-to-function to a function as a universal reference (what type is being deduced). Let's suppose we have a function foo that takes a param as a universal reference:

template<typename T>
void foo(T&& param)
{
    std::cout << __PRETTY_FUNCTION__ << std::endl;
}

And then let's do the following:

void(&f)(int) = someFunction;
foo(f);

The result will be:

void foo(T&&) [with T = void (&)int]

This is perfectly understandable: we are passing lvalue to our function foo, so the deduced type is void(&)int, and the type of the param will be "void(&& &)int" which under reference collapsing rules becomes void(&)int. Param will be just an lvalue reference to a function.

But when I do the following:

void(&f)(int) = someFunction;
foo(std::move(f));

foo will print:

void foo(T&&) [with T = void (&)int]

which is exactly the same as before! What is happening here? Why the result is the same as when passing lvalue? I would expect that since we are passing rvalue to foo, the deduced type should be T = void(int), and param should become void(&&)int. This always happen with all other "normal" types (like classes, primitive types, etc.) Why is it different when dealing with function references?

What is the use for buckets interface in std::unordered_map?

I've been watching this video from CppCon 2014 and discovered that there is an interface to access buckets underneath std::unordered_map. Now I have a couple of questions:

  • Are there any reasonable examples of the usage of this interface?
  • Why did the committee decide to define this interface, why typical STL container interface wasn't enough?

How to fix error: LNK2019 in c++?

I have 3 header file and 4 source file:

calculator.h

#ifndef CALCULATOR_H
#define CALCULATOR_H

#include <QMainWindow>


namespace Ui {
class Calculator;
}

class Calculator : public QMainWindow
{
    Q_OBJECT

public:
    explicit Calculator(QWidget *parent = 0);
    ~Calculator();





private slots:
    //numbers

    void ClickZero();
    void ClickOne();
    void ClickTwo();
    void ClickThree();
    void ClickFour();
    void ClickFive();
    void ClickSix();
    void ClickSeven();
    void ClickEight();
    void ClickNine();



    void ClickDot();
    void ClickEquel();

    void showMessage(std::string msg);



private:
    Ui::Calculator *ui;
};

#endif // CALCULATOR_H

parser.h

#include "calculator.h"
#include "ui_calculator.h"
#include <iostream>
#include <sstream>
#include <string>



using namespace std;
class ParserFormula{

    public:
         void showMessage(string msg);
          string* stringToArray(string str);

};

task.h

#include "calculator.h"
#include "ui_calculator.h"
#include <iostream>
#include <sstream>
#include <string>



using namespace std;
class Task{

    public:
         void showMessage(string msg);
          string* stringToArray(string str);

};

calculator.cpp

#include "calculator.h"
#include "ui_calculator.h"
#include <iostream>
#include <sstream>
#include <string>
#include <parser.h>
#include <task.h>


#include <QMessageBox>

using namespace std;

Calculator::Calculator(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Calculator)
{
    ui->setupUi(this);





     connect(ui->btn0, SIGNAL(clicked()), this, SLOT( ClickZero()));
     connect(ui->btn1, SIGNAL(clicked()), this, SLOT( ClickOne()));
     connect(ui->btn2, SIGNAL(clicked()), this, SLOT( ClickTwo()));
     connect(ui->btn3, SIGNAL(clicked()), this, SLOT( ClickThree()));
     connect(ui->btn4, SIGNAL(clicked()), this, SLOT( ClickFour()));
     connect(ui->btn5, SIGNAL(clicked()), this, SLOT( ClickFive()));
     connect(ui->btn6, SIGNAL(clicked()), this, SLOT( ClickSix()));
     connect(ui->btn7, SIGNAL(clicked()), this, SLOT( ClickSeven()));
     connect(ui->btn8, SIGNAL(clicked()), this, SLOT( ClickEight()));
     connect(ui->btn9, SIGNAL(clicked()), this, SLOT( ClickNine()));



     connect(ui->btnDot, SIGNAL(clicked()), this, SLOT( ClickDot()));
     connect(ui->btnEql, SIGNAL(clicked()), this, SLOT( ClickEquel()));
}

Calculator::~Calculator()
{
    delete ui;
}


void Calculator::ClickZero(){

    ui->mainTextBox->setText( ui->mainTextBox->text() + "0");

}

void Calculator::ClickOne(){
    ui->mainTextBox->setText( ui->mainTextBox->text() + "1");
}
void Calculator::ClickTwo(){
    ui->mainTextBox->setText( ui->mainTextBox->text() + "2");
}
void Calculator::ClickThree(){
    ui->mainTextBox->setText( ui->mainTextBox->text() + "3");
}
void Calculator::ClickFour(){
    ui->mainTextBox->setText( ui->mainTextBox->text() + "4");
}
void Calculator::ClickFive(){
    ui->mainTextBox->setText( ui->mainTextBox->text() + "5");
}
void Calculator::ClickSix(){
    ui->mainTextBox->setText( ui->mainTextBox->text() + "6");
}
void Calculator::ClickSeven(){
    ui->mainTextBox->setText( ui->mainTextBox->text() + "7");
}
void Calculator::ClickEight(){
    ui->mainTextBox->setText( ui->mainTextBox->text() + "8");
}
void Calculator::ClickNine(){
    ui->mainTextBox->setText( ui->mainTextBox->text() + "9");
}


void Calculator::ClickDot(){
    ui->mainTextBox->setText( ui->mainTextBox->text() + ".");
}

void Calculator::ClickEquel(){

        ParserFormula Parser;




   string CurentText = ui->mainTextBox->text().toStdString();

   Parser.showMessage("ss");



  //string* charArray = Parser.stringToArray(CurentText);


//    size_t num = 0;
//    string val = "";




//    for(;num<CurentText.length();num++){

//        val += charArray[num];


//    }

//    this->showMessage(val);





//    for(int c = 0;c<sizeof(charArray);c++){

//        //
//        cout<<charArray[c];
//        cout<<"|";
//        cout<<c;
//        cout<<"\n";

//    }





}


void Calculator::showMessage(string msg){

    QMessageBox msgBox;
    msgBox.setText(QString::fromStdString(msg));
    msgBox.exec();

}



**main.cpp**

    #include "calculator.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Calculator w;
    w.show();

    return a.exec();
}

parser.cpp

 #include "Parser.h"
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <QMessageBox>




void ParserFormula::showMessage(string msg){

    QMessageBox msgBox;
    msgBox.setText(QString::fromStdString(msg));
    msgBox.exec();

}

string* ParserFormula::stringToArray(string str){


size_t size = str.size();
string *returnArray = new string[size];



for(size_t  c = 0;  str.length()>c;    c++){

    returnArray[c] = str.substr(c,1);



}

return returnArray;

}

task.cpp

#include "task.h"
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <QMessageBox>




void Task::showMessage(string msg){

    QMessageBox msgBox;
    msgBox.setText(QString::fromStdString(msg));
    msgBox.exec();

}

string* Task::stringToArray(string str){


    size_t size = str.size();
    string *returnArray = new string[size];



    for(size_t  c = 0;  str.length()>c;    c++){

        returnArray[c] = str.substr(c,1);



    }

    return returnArray;

}

and when i compile it getting this error

calculator.obj:-1: error: LNK2019: unresolved external symbol "public: void __thiscall ParserFormula::test(class std::basic_string,class std::allocator >)" (?test@ParserFormula@@QAEXV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) referenced

Task and ParserFormula class are both same, only difference their names. So when write Task Parser; instead of ParserFormula Parser; it run perfect. what am I doing wrong ?

Print to stdin, in hex or decimal, a std::string as a sequence of bytes

The API I am working with returns a sequence of bytes as a std::string.

How do I print this to stdin, formatted as a sequence, either in hex or decimal.

This is the code I am using:

        int8_t i8Array[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f };
        std::string i8InList(reinterpret_cast<const char*>(i8Array), 16);
        std::string i8ReturnList;

        client.GetBytes(i8ReturnList, i8InList);

        cout << "GetBytes returned ";
        std::copy(i8ReturnList.begin(), i8ReturnList.end(),   std::ostream_iterator<int8_t>(std::cout << " " ));

I am expecting to receive the same input, but in reverse order. What this code prints however is:

GetBytes returned   ☺☻♥♦♣
♫☼

NOTE: The sequence of bytes is an arbitrary sequence of bytes, it is not a representation of written language.

c++ Map- Not finding keys that are present in a set

int createAcronymMap() {
string line;
string temp;
ifstream myfile("Q:\\USER\\acronymsList.txt");
if (myfile.is_open())
{
    while (getline(myfile, line))
    {
        char sep = ':';
        for (size_t p = 0, q = 0; p != line.npos; p = q)
        {
            v.push_back(line.substr(p + (p != 0), (q = line.find(sep, p + 1)) - p - (p != 0)));
        }
    }
    for (int i = 0;i < v.size() - 2;i = i + 2)
    {
        m[v[i]] = v[i + 1];
    }

    myfile.close();
    for (auto elem : m)
    {
        std::cout << elem.first << " " << elem.second.first << " " << elem.second.second << "\n";
    }
}

else cout << "Unable to open file";

return 0;
}
void write_document(string x)
{
istringstream buf(x);
istream_iterator<string> beg(buf), end;
vector<string> tokens(beg, end); // done!

for (auto& s : tokens)      cout << '"' << s << '"' << '\n';
ofstream myfile;

myfile.open("Q:\\USER\\acronyms.txt");
while (tokens.size() > 0)
{
    s.insert(tokens[0]);
    tokens.erase(tokens.begin());
}
for (auto f : s) {
    cout << m.count(f) << endl;
    if (m.count(f))
    {
        cout << "worked";
        myfile << f << ": " << m[f] << "\n";
    }
}

myfile.close();
}
vector<string>v;
map<string, string> m;
set<string> s;

This code reads a vector of strings, called tokens, that was created from the clipboard's contents(which are a word file's contents in this case), into a set of strings. It then creates a map from a .txt file that holds a list of acronyms and their definitions. The set is then checked against the map, and if an acronym is found in the map, writes the acronym and its definition to a new .txt file, such that a user can then copy/paste the list of acronyms. However, the map never returns a key as being found, and thus never writes anything to the output .txt file.

Effect of std::memory_order_acq_rel on non-atomic variable read in other thread

I think I mostly understand the semantics of the various memory_order flags in the C++ atomic library.

However, I'm confused about the following situation:

Suppose we have two threads - Thread A, which is a "main execution" thread, and Thread B, which is some arbitrary thread that is part of a thread pool where tasks can be scheduled and run.

If I perform a "read-write-update" atomic operation using std::memory_order_acq_rel, then perform a non-atomic write on a boolean variable, is the non-atomic write immediately visible to other threads? I would think the answer is no, unless the other threads also access the atomic variable that did the "read-write-update" operation.

So, for example, given a global std::atomic_flag variable X, a global bool value B, and a thread pool object THREADPOOL that has a member function dispatch, which will execute arbitrary function handlers in another thread:

if (!X.test_and_set(std::memory_order_acq_rel)
{
   if (SOME_CONDITION) B = true;
   THREADPOOL.dispatch([]() { 
      // This executes in Thread B
      if (B) { /* do something */ } // are we guaranteed to see changes to B?
   });
}

So in this example, the code inside the lambda function will be executed in a different thread. Is that thread necessarily going to see the (non-atomic) update to B made in the first thread? Note that the second thread does not access the atomic_flag, so my understanding is that changes to B will not necessarily be seen in the second thread.

Is my understanding correct here? And if so, would using std::memory_order_seq_cst change that?

std::iostream read or write with count zero and invalid buffer

The following code reads a file containing some value that represents the length of more following data.

auto file = std::ifstream(filename, std::ios::in | std::ios::binary);
// dataLen = Read some header field containing a length of following data.
std::vector<unsigned char> data;
data.resize(dataLen);
file.read((char*)data.data(), dataLen);

It fails with the MSVC 2013 compiler if dataLen = 0. It causes an abort with the message Expression: invalid null pointer, because data.data() returns a null pointer.

This question suggests that a count of 0 is valid for std::basic_istream::read, but the third comment on the question seems to point out my issue.

Is it valid C++ to pass an invalid pointer to std::basic_istream::read (or std::basic_ostream::write) with a size of 0? It would seem logical to me, because the call should not touch the buffer anyway.

The obvious solution is to deal with this special case with an if clause, but I am wondering if MSVC is wrong once again.

Here is a compiled example of clang running the program fine: http://ift.tt/1FKD7lm

map.count not working properly

for (auto f : s) {
    cout << m.count(f) << endl;
    if (m.count(f))
    {
        cout << "worked";
        myfile << f << ": " << m[f] << "\n";
    }
}

This code checks to see if a word's in the map, then outputs the word and the definition to a text file, called myfile. However, it never shows as finding the words in the map! The map appears to be populated correctly, as I've tested with outputting the map's contents. Any ideas?

Overloading of << operator using iterator as a parameter

I`d like to print enum values as text and use for it overloading. Suppose I have the following code:

#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <unordered_set>

enum enm{
    One,
    Two
};

class Complex{
public:
friend std::ostream& operator<<(std::ostream& out, std::unordered_multiset<int>::const_iterator i){
    switch (*i){
        case One:{
            return out<<"One";
        }
        case Two:{
            return out << "Two";
        }
    }
}
void func(std::unordered_multiset<int> _v);
};

void Complex:: func(std::unordered_multiset<int> _v){
    _v.insert(One);
    _v.insert(Two);
    for (std::unordered_multiset<int>::const_iterator i(_v.begin()), end(_v.end()); i != end; ++i){
        std::cout <<"Num: " << *i <<std::endl; //need to get here "One", "Two" instead of 0, 1
    }
}

int main(){
    Complex c;
    std::unordered_multiset<int> ms;
    c.func(ms);
    return 0;   
}

The problem is this variant doesn`t work. So, I get 0, 1 instead of One, Two. Have no ideas how to do it properly. Thank you for help!

Why is compiler not able to infer template arguments? [duplicate]

This question already has an answer here:

I tried to implement a map operator based on the C++ operator ->*. The purpose of this operator was to elegantly map/transform zero terminated char* strings and wchar_t* strings inplace.

template<typename T>
T* operator->*(T* iteratee, std::function<T(T)> mapFun)  {
    for(T* it = iteratee; *it; ++it)
      *it = mapFun(*it);
    return iteratee;
}

using namespace std;

int main()
{
   char msg[] = "Hello World!";

   cout << msg << endl;
   cout << msg->*([](char c ) { return c+1; }) << endl;   
}

Desired output is:

Hello World!
Ifmmp!Xpsme"

But instead I only get the following error:

21:15: error: no match for 'operator->*' (operand types are 'char*' and 'main()::<lambda(char)>')
21:15: note: candidate is:
10:4: note: template<class T> T* operator->*(T*, std::function<T(T)>)
10:4: note:   template argument deduction/substitution failed:
21:46: note:   'main()::<lambda(char)>' is not derived from 'std::function<T(T)>'

Why is this happening?


I know, I can fix the Problem by either calling the operator explicitly, which makes the operator pretty inconvenient

cout << operator->*<char>(msg, [](char c ) { return c+1; }) << endl;

or by adding a second template argument to the operator:

template<typename T, typename F>
T* operator->*(T* iteratee, F mapFun)  {
for(T* it = iteratee; *it; ++it)
      *it = mapFun(*it);
    return iteratee;
}

But this it not optimal, because the compiler doesn't complain, when I pass a function of the wrong type like the following usage, which compiles without warning:

cout << msg->*([](int i) { return 'a'+i; }) << endl;


So, how can I use the std::function-version of the operator without explicitly mentioning the template arguments?

Want to build latest g++ for Raspberry Pi - worth it?

It's irritating to have a C++ compiler that partially supports C++11 standards, so I'm mulling over building the latest stable g++ for my Raspberry Pi. This is for work, but some people over here are reluctant to upgrade OS versions (not me) which might give me latest and greatest stuff. So, having said that, it is wise, worth my time, etc. to build the latest g++? Any pitfalls, gotchas, etc?

Just a snapshot of my system particulars:

uname -a
Linux rpi3 3.12.22+ #691 PREEMPT Wed Jun 18 18:29:58 BST 2014 armv6l GNU/Linux

g++ --version
g++ (Debian 4.6.3-14+rpi1) 4.6.3

I've downloaded 4.8.5.

to_string and convert.str() not declared in scope

I am having an issue trying to convert a number into a string. The purpose is for error checking to make sure the number is of a specific length. I have tried using both to_string() and convert.str() functions but get the same error back when trying to compile. I am using MinGw g++ to compile and realize I need to tell it I want the C++11 standard, which I believe I have done. My compiler code is as follows:

NPP_SAVE
CD $(CURRENT_DIRECTORY)
C:\MinGW\bin\g++ -std=c++11 "$(FULL_CURRENT_PATH)" -o "$(NAME_PART).exe"
cmd /c $(NAME_PART).exe

Now assuming that is correct, my code for using to_string() is as follows:

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

int main() {
  int book_code = 0;

  cout << "Please enter the four digit book code: ";
  cin >> book_code;
  string code = to_string(book_code);

  while (!(cin >> book_code) || code.length() != 4){
    cin.clear();
    cin.ignore(10000, '\n');
    cout << "That is not a valid code." << endl;
    cout << "Please enter the four digit book code: ";
  }
} 

And my code for using convert.str() is as follows:

int main() {
  int book_code = 0;

  cout << "Please enter the four digit book code: ";
  cin >> book_code;
  ostringstream Convert;
  convert << book_code;
  string code = convert.str();

  while (!(cin >> book_code) || code.length() != 4){
    cin.clear();
    cin.ignore(10000, '\n');
    cout << "That is not a valid code." << endl;
    cout << "Please enter the four digit book code: ";
  }
} 

Neither of these was successful and both returned "error: 'to_string' was not declared in this scope"

Am I missing something obvious?

Select enum type based on template parameter

I have a class:

template <class type>
class sysbase : public base
{
 public:
  static type* Spawn(int Config = 0) { … }
  … 
};

And about 50 enums in the global namespace:

enum a_config { A1, A2, … };
enum b_config { B1, B2, … };
etc.

Classes a, b, etc. (derived from sysbase) will be passed as the type template argument to sysbase.

Now I would like to change the Config parameter to be of one of those enum types instead of just a plain int to improve type safety, so that:

  • when type is class a, then the type of Config would be a_config
  • when type is class b, then the type of Config would be b_config
  • etc.

The enums should preferably stay in the global namespace to not break the existing code which uses e.g. a::Spawn(A1).

Is there a way to accomplish this?

Function overloading with std::function argument: why is the const method never called?

#include <functional>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

class A
{
    public:
    void doStuff(function<void (const string *)> func) const
    {
        cout << "Const method called" << endl;
        for(const auto& i_string : m_vec)
            func(i_string);
    }

    void doStuff(function<void (string *)> func)
    {
        cout << "Non-const method called" << endl;
        doStuff([&func](const string *str)
        {
            auto mutableString = const_cast<string *>(str);
            func(mutableString);
        });
    }

private:
    vector<string *> m_vec;
};

int main()
{
    auto a = A{};

    a.doStuff([](string *str){
        *str = "I modified this string";
    });
}

In this example, the const method is never called.If the code looks weird, here's what I'm trying to do:

Instead of a getter method, I let clients iterate objects by passing a function. To enable both const and non-const access, I want to provide const and non-const overloads. Further, to avoid copy & paste, I want to implement the non-const method in terms of the const method: the const method in my code is actually more complicated than the one I use here.

Now, my questions is this: If you run this code, it will recursively call the non-const function until the stack overflows. I don't understand why the line doStuff([&func](const string *str) in the non-const method calls itself and not the const method.

Thanks in advance!

Wt versus CppCMS

How does CppCMS compare to Wt in matter of performance? I did some reading on the topic and it seems that Wt just maintains WApplication (basically tab in the browser) running in memory as long user (browser) uses it (keeps connection alive).

I tried to read on how CppCMS works but must admit I am a little bit confused how it exactly works.

Does anyone here have experience with both therefore being able to compare them in environment with high concurrent number of user?

Other thing, is CppCMS still alive? Wt has last comit 3 days back, CppCMS on 20th of april, that's more than 2 months, which seems like a quite ago.

Add const when accessing member variable

I need a transparent wrapper around a data structure to add some properties. Easiest is something like this:

template<typename T>
struct Wrapper{
    T values;
}

Now I want to pass this to an accessor and keep constness. Base would be:

template<class T>
T& accVal(usigned idx, T* vals){ return vals[idx]; }
template<class T>
const T& accVal(usigned idx, const T* vals){ return vals[idx]; }

template<class T>
auto
acc(unsigned idx, T& data) -> decltype(accVal(idx, data.values))
{
    return accVal(idx, data.values);
}

//Example:
Wrapper<int*> intsWrapped;
cout << acc(1, intsWrapped);

This works only for non-pointers, say replace "T*" with a struct as the access to data.values discards the constness of data and I'd be able to manipulate it like:

void foo(const Wrapper<int*>& bar){ acc(1, bar) = 5; }

That is dangerous in my application.

So how can I preserve the constness? I tried something like this:

template< class T_Base, typename T_Mem >
struct GetConstCorrect
{
    template< typename T >
    struct AddConstVal: std::add_const<T>{};

    template< typename T >
    struct AddConstVal<T&>
    {
        using type = std::add_const_t<T> &;
    };

    template< typename T >
    struct AddConstVal<T*>
    {
        using type = std::add_const_t<T>*;
    };

    template< typename T >
    struct AddConstVal<T* const>
    {
        using type = std::add_const_t<T>* const;
    };

    template< typename T >
    struct AddConstVal<T*&>
    {
        using type = std::add_const_t<T>*&;
    };

    template< typename T >
    struct AddConstVal<T*const &>
    {
        using type = std::add_const_t<T>* const &;
    };

    using Base = T_Base;
    using Mem = T_Mem;

    static constexpr bool isConst = std::is_const<Base>::value;
    using type = std::conditional_t< isConst,
            typename AddConstVal<Mem>::type,
            Mem
            >;
};

template< class T_Base, typename T_Mem >
using GetConstCorrect_t = typename GetConstCorrect< T_Base, T_Mem >::type;

template< class T_Base, typename T_Mem >
GetConstCorrect_t< T_Base, T_Mem& >
getConstCorrect(T_Mem& mem)
{
    return const_cast<GetConstCorrect_t< T_Base, T_Mem& >>(mem);
}

And access data.values by getConstCorrect(data.values), but this still seems error prone. (E.g. a multipointer like int** would become intconst not int const**)

Is there a better way to achieve this?

move constructor along copy constructor [duplicate]

This question already has an answer here:

ist is possible to have a copy constructor implemented along with a move constructor? If I would have the following abstract class structure:

template<typename T>
class A
{
  public:
    A<T>();
    A<T>(const& T);
    A<T>(T&&);
  // ...
}

  1. Is it possible to have both, copy - and move constructor
  2. How would a call of both of them look like? Is there a special syntax?
  3. How is the compiler differing between both calls?

Aliasing Structs in C++11

I am writing a C++11 program that involves events and callbacks. I have a base class called Event, it's then derived by concrete event classes.

template <typename EventArgs>
class Event {
public:
    using EventHandler = std::function<void(EventArgs)>;
    void operator +=(EventHandler handlerDelegate);
    void fire(EventArgs e);
private:
    std::vector<EventHandler> subscribers;
};
  std::vector<EventHandler> subscribers;
};

struct TouchEventArgs { int x, int y }
struct TouchEvent : public Event<TouchEventArgs> { }
...

I was wondering if something like this was possible:

template <typename EventArgs>
using event = struct : public Event<EventName> {  };

So that i could declare events like

event<TouchEventArgs> TouchEvent;

regex_search in c++11 only selecting biggest subtring that matches .Also type mismatch in regex_search

The regex_search here selects only the longest substring in this program as the output is the whole string data. Is that the default behaviour?

Additionally if i pass the string without declaring it as a string first like this

      regex_search("<html><body>some data</body></html",m,samepattern) 

It throws an error of type mismatch .

Additionally if i only use without the additional 2nd parameter

      regex_search("some string",pattern);

it works.

The whole code is shown below

 #include<string>
 #include<regex>
 #include<iostream>
 #include<iomanip>
 using namespace std;

 int main()
 {
    smatch m;
    string data{"<html><body>some data</body></html"};
    bool found = regex_search(data,m,regex("<.*>.*</.*>"));
    //If regex_seacrh("<html><body>some data</body></html",same as above)
    //it throws type mismatch error for this string in regex header
    cout<<(found?m.str():"not found");
    return 0;
 }

Why memset is not working with array container in c++11?

#include <iostream>
#include <array>
#include <cstring>

using namespace std;

int main ()
{
  array<int,5> A ;
  memset(A,0,sizeof A);
  for(int i=0;i < 5;i++){
        cout<<A[i]<<" ";
}

   return 0;
}

When I run the program, compilation error occured.

But memset works well when I use int A[5] instead of array<int,5> A. Why memset is not working with container array as either way is used to define fixed size array?

How std::unordered_map is implemented in c++ compilers

I have not read the standard and I am a bit surprised that this question has never been specifically asked before in stack overflow.

c++ unordered_map collision handling , resize and rehash

This is a previous question opened by me and I have seen that I was having a confusion about how unordered_map is implemented. I am sure many other people shares that confusion with me. It has been mentioned that:

Every unordered_map implementation stores a linked list to external nodes in the array of buckets... No, that is not at all the most efficient way to implement a hash map for most common uses. Unfortunately, a small "oversight" in the specification of unordered_map all but requires this behavior. The required behavior is that iterators to elements must stay valid when inserting or deleting other elements

I was hoping that someone might explain the implementation and how it corresponds to the c++ standard definition (in terms of performance requirements ) and maybe even how it can be improved.

regex not working as expected in c++11

I m studying regular expressions in c++11 and this regex search is returning false anybody knows what i m doing wrong here. The search works if i use the pattern "<. * >" . I know that .* stands for amy number of characters except newline

#include<regex>
#include<iostream>

using namespace std;

int main()
{
    bool found = regex_match("<html>",regex("h.*l"));// works for "<.*>"
    cout<<(found?"found":"not found");
    return 0;
}

why we cant get the address of pointer in C++

I want to get the address of constructor, but able to get it.

Compiler throws an error.

I am finding the reason , why we can't get the address. But not able to figure it out with perfect reasoning

dimanche 28 juin 2015

How to map C++ standart concurrency features to Windows API?

How to map C++ standard concurrency features to Windows API? Not exactly but according to idea. For example: condition variables <-> events. Which features have no correspondence in both C++ and Win API? For example, I think completion IO ports have no correspondence in C++.

How to clean up C++ compiler commands?

I tried searching for a question like this as best as I could, but I simply don't know how exactly to ask the question. I apologize if this has been answered before, or if it is a trivial question. I am new to the large (and quite intimidating!) world of C++. I will try my best in the future.

Let me try to explain what I mean:

I am on Linux Ubuntu 14.04. On Ubuntu, to compile a C++ program I wrote, for example, let's say some file myProgram.cpp, I cd to its directory and type the following into the terminal:

g++ myProgram.cpp -o myProgram

This way, I can then type:

./myProgram

To run myProgram. This was simple and satisfactory -- and I learned this from reading the C++ Primer. After finding myself comfortable coding in C++, I decided to move onto giving myself a project, which involved using Image Magick, specifically, its C++ API: Magick++. However, now, if I wish to compile something, I have to type this ugly mess:

g++ `Magick++-config --cxxflags --cppflags` -o testMagick testMagick.cpp `Magick++-config --ldflags --libs`

To make my code compile and execute. This seems very messy, and when I was trying to see if CImg was any better, it turned out that it needed its own set of arguments like -lm, -lpthread and -lX11. It also turned out that to compile with C++11, I had to write -std=c++0x. So my question is:

Is there a way to simplify/clean up my compile statements in the terminal, or do I have to find out and use a specific set of arguments whenever I compile a different kind of program using a different API?

std::thread missing type specifier

I am trying to use an c++11 thread with lambda functions. I already use it on another class, but for some reason on my LogManager static class i have some weird problems.

My "minimal" class is:

#include <iostream>
#include <fstream>
#include <map>
#include <vector>
#include <algorithm>
#include <thread>

using namespace std;
namespace Debug {
    enum LogLevel{
        ERROR, /*!< Mensagens de erro. */
        WARNING, /*!< Mensagens de alerta. */
        MESSAGE, /*!< Mensagens gerais, normalmente utilizadas para propositos de debug. */
        UNKNOWN /*!< Mensagems de de origem desconhecidas, normalmente utilizadas em exceptions */
    };
    class LogManager{

    public:
        template<typename T, typename... Args>
        static void log(LogLevel logLevel, const char *string, T value = "", Args... args){

            std::thread t([=](){
                std::cout << "thread function\n";
            });


        }
    };
}

When i try to compile i get some:

Error 2 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int - Errors

It dont seems to be a compiler problem, i have the "same" code on another class, it seems to be something i forgot, i dont know if an static class can be a problem.

Thanks

Template class optimizations during compiling

I was curious to know the internals of template class compilation in specific circumstances. I ask this because I'd like to extend some existing classes.

For example, let's assume a starting

template<typename T>
class LargeClass {
  private:
    std::unique_ptr<T> data;
    // many other fields

  public:
    const std::unique_ptr<T>& getData() { return data; }
    void setData(T* value) { data = std::unique_ptr<T>(value); }
    // many other methods that don't depend on T
}

This example makes me think that, since sizeof(std::unique_ptr<T>) == sizeof(T*) (without a custom deleter) then sizeof(LargeClass<T1>) == sizeof(LargeClass<T2>) for any T1 and T2. Which implies that all offsetof(field, LargeClass<T>) are the same for any field and T.

So why the compiler would create a copy of each LargeClass method if they don't depend on T?

A different approach, like

class LargeClass {
  private:
    T data
    ...

  private
    ...
}

instead should force the compiler to create multiple definitions of the methods for different types since sizeof(T) could change, but using an std::aligned_storage with a static_assert (to avoid storing too large data) could make this fallback to the first case. Would a compiler be smart enough to realise it?

In general I was wondering if a compiler is smart enough to avoid generating multiple definition of a template class method if the type variable is not used and the class structure doesn't change (or at least doesn't change for accessing the fields accessed in the method) or not. Does the standard enforce anything about it?

C++ Vector iterator error

Hey :) I've only been learning C++ for a week, and here is some code I wrote. I get an error saying the vector iterator is out of range. The error happens when the value of k and nZeros are both 5, possibleGrid[i][j].size()=4.

int nZeros = 0;
        for (int k = 0; k < Size; k++)
        {

            if (possibleGrid[i][j][k - nZeros] == 0)
            {
                nZeros++;
                possibleGrid[i][j].erase(possibleGrid[i][j].begin() + k - nZeros); //something here is wrong!!
            }

        }

Any help would be much appreciated :)

It seems that is_copy_constructible<T&&> is false even when is_copy_constructible<T> is true for identical types T. I've tested this with gcc and with clang and get the same results. Is this expected behaviour? Where does the standard define this? What is the reasoning for this behaviour?

Sample code which compiles with the error "int&& doesn't work":

#include <type_traits>

int main() {
    static_assert(std::is_copy_constructible<int>::value, "int doesn't work");
    static_assert(std::is_copy_constructible<int&>::value, "int& doesn't work");
    static_assert(std::is_copy_constructible<int&&>::value, "int&& doesn't work");

    return 0;
}

I encountered this situation when I was trying to create a constraint on a template parameter to ensure that the template only works on copy constructible types. Will I need to create a special case for r-value reference types in order to get my template to work with r-value references to copy constructible types?

If this is a duplicate I appologize. I couldn't find anything in my searches though.

I can use any of the newest features c++11/c++14. I can upgrade to VS2015 if necessary.

I'm trying to write a class that will auto cast into a std::function with a specific signature when assigned. I have code that works with GCC, but it failed on MSVC2013. The code is a snippet that recreates the error. WTF MSVC?!

Also I know this is risky code, automatically casting function pointers and such, but it's for the private implementation of a plugin library and I only want to define the function signature once.

GCC c++11 works fine - Demo

class FunctionPointer
{
    void* fp;
public:
    FunctionPointer(void* ptr)
        : fp(ptr)
    {}

    // Overload casting operator to 
    // a certain function signiture
    template<class R, class... ARGS>
    operator std::function<R(ARGS...)>(){
        typedef R(*func_ptr)(ARGS...);
        return std::function<R(ARGS...)>((func_ptr)fp);
    }
};

void hello(string msg){
    cout << "Hello " << msg << endl;
}

int main() {

    FunctionPointer f((void*)hello);

    function<void(string)> func_hello = f;

    func_hello("World!");

    return 0;
}

MSVC works when I change the line to this...

function<void(string)> func_hello = f.operator std::function<void(string)>();

MSVC fails with the same error when I have this...

function<void(string)> func_hello = (std::function<void(string)>)f;

MSVC fails with the following error in a file that is hard to read to say the least. It seems to be deducing the wrong function signature.

xrefwrap.h:283 - error C2064: term does not evaluate to a function taking 1 arguments


1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\xrefwrap(283): error C2064: term does not evaluate to a function taking 1 arguments
1>          c:\program files (x86)\microsoft visual studio 12.0\vc\include\functional(228) : see reference to function template instantiation '_Ret std::_Callable_obj<FunctionPointer,false>::_ApplyX<_Rx,_Ty>(_Ty &&)' being compiled
1>          with
1>          [
1>              _Ret=void
1>  ,            _Rx=void
1>  ,            _Ty=std::basic_string<char,std::char_traits<char>,std::allocator<char>>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 12.0\vc\include\functional(228) : see reference to function template instantiation '_Ret std::_Callable_obj<FunctionPointer,false>::_ApplyX<_Rx,_Ty>(_Ty &&)' being compiled
1>          with
1>          [
1>              _Ret=void
1>  ,            _Rx=void
1>  ,            _Ty=std::basic_string<char,std::char_traits<char>,std::allocator<char>>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 12.0\vc\include\functional(226) : while compiling class template member function 'void std::_Func_impl<_MyWrapper,_Alloc,_Ret,std::string>::_Do_call(std::string &&)'
1>          with
1>          [
1>              _Alloc=std::allocator<std::_Func_class<void,std::string>>
1>  ,            _Ret=void
1>          ]
1>          c:\program files (x86)\microsoft visual studio 12.0\vc\include\functional(495) : see reference to class template instantiation 'std::_Func_impl<_MyWrapper,_Alloc,_Ret,std::string>' being compiled
1>          with
1>          [
1>              _Alloc=std::allocator<std::_Func_class<void,std::string>>
1>  ,            _Ret=void
1>          ]
1>          c:\program files (x86)\microsoft visual studio 12.0\vc\include\functional(396) : see reference to function template instantiation 'void std::_Func_class<_Ret,std::string>::_Do_alloc<_Myimpl,FunctionPointer&,_Alloc>(_Fty,_Alloc)' being compiled
1>          with
1>          [
1>              _Ret=void
1>  ,            _Alloc=std::allocator<std::_Func_class<void,std::string>>
1>  ,            _Fty=FunctionPointer &
1>          ]
1>          c:\program files (x86)\microsoft visual studio 12.0\vc\include\functional(396) : see reference to function template instantiation 'void std::_Func_class<_Ret,std::string>::_Do_alloc<_Myimpl,FunctionPointer&,_Alloc>(_Fty,_Alloc)' being compiled
1>          with
1>          [
1>              _Ret=void
1>  ,            _Alloc=std::allocator<std::_Func_class<void,std::string>>
1>  ,            _Fty=FunctionPointer &
1>          ]
1>          c:\program files (x86)\microsoft visual studio 12.0\vc\include\functional(385) : see reference to function template instantiation 'void std::_Func_class<_Ret,std::string>::_Reset_alloc<FunctionPointer&,std::allocator<std::_Func_class<_Ret,std::string>>>(_Fty,_Alloc)' being compiled
1>          with
1>          [
1>              _Ret=void
1>  ,            _Fty=FunctionPointer &
1>  ,            _Alloc=std::allocator<std::_Func_class<void,std::string>>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 12.0\vc\include\functional(385) : see reference to function template instantiation 'void std::_Func_class<_Ret,std::string>::_Reset_alloc<FunctionPointer&,std::allocator<std::_Func_class<_Ret,std::string>>>(_Fty,_Alloc)' being compiled
1>          with
1>          [
1>              _Ret=void
1>  ,            _Fty=FunctionPointer &
1>  ,            _Alloc=std::allocator<std::_Func_class<void,std::string>>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 12.0\vc\include\functional(671) : see reference to function template instantiation 'void std::_Func_class<_Ret,std::string>::_Reset<FunctionPointer&>(_Fty)' being compiled
1>          with
1>          [
1>              _Ret=void
1>  ,            _Fty=FunctionPointer &
1>          ]
1>          c:\program files (x86)\microsoft visual studio 12.0\vc\include\functional(671) : see reference to function template instantiation 'void std::_Func_class<_Ret,std::string>::_Reset<FunctionPointer&>(_Fty)' being compiled
1>          with
1>          [
1>              _Ret=void
1>  ,            _Fty=FunctionPointer &
1>          ]
1>          c:\users\cameron\desktop\desktop\programming\projects\c++ projects\garbage\templatetest\main.cpp(32) : see reference to function template instantiation 'std::function<void (std::string)>::function<FunctionPointer&>(_Fx)' being compiled
1>          with
1>          [
1>              _Fx=FunctionPointer &
1>          ]
1>          c:\users\cameron\desktop\desktop\programming\projects\c++ projects\garbage\templatetest\main.cpp(32) : see reference to function template instantiation 'std::function<void (std::string)>::function<FunctionPointer&>(_Fx)' being compiled
1>          with
1>          [
1>              _Fx=FunctionPointer &
1>          ]