jeudi 31 mars 2016

Ensures() - guideline support library

I am trying to understand how to use Ensures() in code. As given in the example, if I tried using Ensures() as follows...

int main(void)
{
    int result = 0;
    // Some calculation
    Ensures(result == 255);
    return 0;
}

If the result variable is not equal to 255, the program crashes with the following output "terminate called without an active exception". My question is how to use Ensures() properly?

Merging vectors without extra memory

I came across this code segment where two vectors are merged where elements from one vector is favored in case of duplication:

std::vector<String> fields1 = fieldSource1.get();
std::vector<String> fields2 = fieldSource2.get();
// original
fields1.insert(std::end(fields1), std::begin(fields2), std::end(fields2));
std::stable_sort(std::begin(fields1), std::end(fields1));
fields.erase(std::unique(std::begin(fields), std::end(fields)), std::end(fields));
return fields1;

Given that Strings are unique in their respective vector, and that order of Strings in output vector is irrelevent, I think that I can make this algorithm more efficient.

I would like to avoid extra memory allocation of std::set_union() and std::set_diff().

(Directly inserting std::set_diff to an original vector is not an option due to iterator invalidation during resizing)

I ended up with this, which is std::set_diff with one iterator replaced with an index:

std::sort(std::begin(fields1), std::end(fields1));
std::sort(std::begin(fields2), std::end(fields2));
// Initialize iterators by index in case of resizing
size_t index = 0;
size_t end = std::size(fields1);
std::remove_copy_if(std::begin(fields2), std::end(fields2), std::back_inserter(fields1),
[&fields1, &index, end](String field)->bool{
    auto begin = std::begin(fields1);
    found = std::lower_bound(begin+index, begin+end, field);
    index = std::distance(begin, found);
    return (*found) == field;
});
return fields1;

My question is: can I make this merge operation more efficient? If not, can I make it more readable?

How to address the next iterator in a loop and insert an element at a same address?

1) I have got an error while I tried to access next iterator of the inner loop by using next(). I was wondering where this error comes from. To be specific I have a vector of lists and I want to check connection feasibility with the next element, that's what feas[it2][(next(it2))] does.

2) After the if condition satisfies, I would like to insert an element, lets say 3, at the same address. If you could correct the insert function I will be so grateful.

To sum up, I want to know how can I have access to next element within the list?, and also how to insert a value at the same address?

Many thanks

vector<list<int>>temp;
for (const auto& it1 : temp)
{

    for (const auto& it2 : it1)
    {

        if (feas[it2][(next(it2))] == 1)
        {
            temp[it1].insert (it2,3);
        }

    }
}

Argument forwarding for emplace() makes constructor arguments const

I'm trying to use emplace() to construct in-place a map&lt;K,V&gt; entry (using Boost). The key object constructor arg gets forwarded through the template magic correctly, but the V object constructor arg becomes const, so it doesn't work.

#include <boost/container/map.hpp>

class A {
  public:
    /**/     A( int n ) { }
    friend bool operator<( const A &a1, const A &a2 ) { return false; }
} ;

class B {
  public:
    /**/     B( const char *str ) { }
} ;

class C {
  public:
    /**/     C( B &b ) { }
} ;

int
main( int, char ** )
{
    boost::container::map<A,B>   m1;
    boost::container::map<A,C>   m2;
    B                            b( "Foo" );
    C                            c( b ); // <--- this works OK.

    m1.emplace( 1, "Hello" );
    m2.emplace( 2, b ); // <----- this fails!
}

The Error is:

Error: /usr/local/include/boost/container/detail/pair.hpp:128:38: error: no matching function for call to C::C(**const** B&), second(::boost::forward<V>(v))

Something about the emplace argument-forwarding turns *b* into *const b* in the last line. I know there must be a boost::bla_bla_bla that I can apply to make it work, but I haven't been able to find it.

Can anybody help?

How to execute a function on first call in a recursive template function?

Question title says it all, so how do you execute a function on a first call in a recursive template function?


I thought of using default variables in the function signature, but there isn't a place where the variable doesn't interfere with the rest of the function signature. Here's what I mean:
template<typename T, typename... Ts>
void print(T first, Ts... params) { ... }

Note: I'm using a bool (b) to determine if the function wasn't called from itself.

  1. void print(bool b = true, T first, Ts... params);. Doesn't work if called with only 1 argument (i.e. print("hello");), because the compiler initializes b with "hello".
  2. void print(T first, bool b = true, Ts... params);. Doesn't work with multiple arguments (i.e. print("hello", "world", "again");), because the compiler initializes b with the second parameter in the parameter pack..
  3. void print(T first, Ts... params, bool = true);. Same as 2, except that b is initialized with the last parameter in the parameter pack.

What I would like is something like this (or something else involving template arguments if you want (or something completely different))

template<typename T, typename... Ts>
void print(T first, Ts... params)
{
    if (...) // Magic!
        foo();
    std::cout << first << '\n';

    print(params...);
}

Any ideas?

undefined reference to static const member

I'm stumbling across an unexpeceted behavior and can't get my head around it. Let's take this snippet

/********** Object.h *************/
#define GL_GLEXT_PROTOTYPES 1
#include <glm/glm.hpp>
#include <GL/gl.h>

class Object
{
putlic:
    Object();

private:
    static const initVAO
}



/********** Objet.cpp *************/

Object::Object()
{
    glBindVertexArray( initVAO );
}

For some reasons during linking it throws me an error "undefined reference to `Object::initVAO'" . But as soon as I remove "static const" from initVAO declaration it works fine. Why ?

ps : pretty sure it's a stupid mistake, I'm lacking several hours of sleep.

std::numeric_limits

I was just trying few things on std::numeric_limits. And observed some interesting behaviour. cout << "Min = " << (std::numeric_limits::has_infinity) ? "TRUE" : "FALSE";

outputs "0"

cout << "Min = " << (std::numeric_limits::has_infinity ? "TRUE" : "FALSE"); outputs "FALSE"

Please notice the position of start and end () braces around std::numeric_limits.

In the first case ternary operator didn't had any meaning. Where as when I shift the brace to the end then only ternary operator (?:) is found to be meaningful.

Any inputs on why this behaviour?

Clang warning in dubious case: function 'foo' could be declared with attribute 'noreturn'?

I have been playing around a bit with the [[noreturn]] attribute, which I'm trying to get a handle of and make use of (I understand [[noreturn]] is a C++11 standard attribute and __attribute__((noreturn)) is a GCC/Clang extension). As part of this, I enabled the Clang warning -Wmissing-noreturn.

> clang++ -v
Ubuntu clang version 3.7.1-svn253742-1~exp1 (branches/release_37) (based on LLVM 3.7.1)
Target: x86_64-pc-linux-gnu
Thread model: posix

foo.cpp:

enum bar
{
  A = 1,
  B,
  C
};

void foo()
{
  switch (bar())
  {
    case A:
    case B:
    case C:
    default:
      break;
  }
}

int main()
{
  foo();
  return 0;
}

Then compile:

> clang++ foo.cpp -o foo -Wmissing-noreturn -std=c++14
foo.cpp:9:1: warning: function 'foo' could be declared with attribute 'noreturn'
      [-Wmissing-noreturn]
{
^
1 warning generated.

It appears to me that it would return! What's going on here? Is this a compiler bug?

If you remove the "= 1" from A, then it compiles fine without a warning.

If I do make the foo() function [[noreturn]] void foo(), then it does crash with a segmentation fault.

boost::variant visitor return error (most vexing parse?)

I have an std::array of boost::variant object, and I'm trying to create a boost::static_visitor which visits an element in the array, returning a reference to something in each of the variant member types. That's a mouthful, so here's a code snippet mimicking my implementation:

#include <boost/variant.hpp>
#include <array>

struct SomeType {};

struct A {
  SomeType something;
  SomeType& someMethod() { return something; }
};

struct B {
  SomeType something;
  SomeType& someMethod() { return something; }
};

struct C {
  SomeType something;
  SomeType& someMethod() { return something; }
};

typedef boost::variant<A, B, C> MyVariant;

class SomeVisitor : public boost::static_visitor<> {
public:
  template<typename T>
  SomeType& operator()(T& operand) const {
    return operand.someMethod();
  }
};

class MyVariants {
public:
  SomeType* getSomething(unsigned index);

private:
  static const size_t count = 100;
  std::array<MyVariant, count> variants_;
};

SomeType* MyVariants::getSomething(unsigned index) {
  if(index < count) {
    MyVariant& variant = variants_[index];
    SomeType& something = boost::apply_visitor(SomeVisitor(), variant);
    return &something;
  }
  else {
    return nullptr;
  }
}

This snippet compiles with clang 3.6.2, but gcc 5.3.1 spits out the following (followed by a few dozen errors from the boost variant headers)

test.cpp:43:47: error: invalid initialization of non-const reference of type 'SomeType&' from an rvalue of type 'boost::static_visitor<>::result_type {aka void}'
     SomeType& something = boost::apply_visitor(SomeVisitor(), variant);

All the errors seem to say the same thing - the visitor's return type is void, and I can't bind that to a SomeType&. I don't think there are any syntax errors with my implementation of SomeVisitor since this compiles fine with clang.

This question and this question show similar errors generated by a boost::static_visitor, and both were explained by C++'s most-vexing-parse. In both those questions, the issue was something like this (using types from my snippet above):

MyVariant variant(A());
SomeType& something = boost::apply_visitor(SomeVisitor(), variant);

In this context, I can understand how the most vexing parse applies. MyVariant variant(A()); might be ambiguous to the compiler. I don't know how this applies to my snippet though, since MyVariant& variant = variants_[index] seems pretty explicit. I don't know if these questions are even related to my issues.

Any advice/help would be appreciated

Delete elements from a vector in C++11 while iterating over it [duplicate]

This question already has an answer here:

My applications requires to iterate over a vector and delete certain elements which doesnt satisfy the requirements. Which is the most correct way? I believe the following way is incorrect.Reason: I am getting segmentation fault.

std::vector<ObjectX> vec1;
//Fill in vec1
std::vector<ObjectX>::iterator itVec1 = vec1.begin();

for(;itVec1 != vec1.end(); ++itVec1) {
   if (Oracle(*itVec1)) vec1.erase(itVec1);
}

Howto use on bcc32 an static lib built with bcc32c

I need to use a C++11 library on a bcc32 project. The library doesn't compile with bcc32, but does with bcc32c.

I would like to prevent exposing this library on a DLL. The project compiles with bcc32c, but I wasn't able to use bcc32c static libs on bcc32 projects.

Unable to write date to file

I came across an idea where I wanted to log what my program is doing with date and time. So I wrote a small function, and upon compilation no error, and no runtime error except that it doesn't open log.txt and it won't even display the date.

#include <chrono>
#include <ctime>
#include <fstream>
#pragma warning(disable:4996)

void log(const char*& text)
{
    std::fstream fs;
    fs.open("log.txt", std::fstream::in | std::fstream::out | std::fstream::app);

    auto now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());

    fs << ctime(&now) << text << std::endl;
}

int main()
{
    const char* log("Testin codenz stuff");
}

remove repetition when switching enum class

When I switch on an enum class I have to restate the enum class in every case. This bugs me since outside of constexpr-constructs it is hard to imagine what else I could mean. Is there away to inform the compiler that everything inside a block should be resolved to an enum class of my choice if there is a match?

consider the following example that contains a compiling snippet and for comparisson a non compiling snippet (commented out) that I would like to write.

#include <iostream>

enum class State : std::uint8_t;
void writeline(const char * msg);
void Compiles(State some);

enum class State : std::uint8_t
{
    zero = 0,
    one = 1
};

int main()
{
    Compiles(State::zero);
    return 0;
}

void Compiles(State some)
{
    switch (some)
    {
    case State::zero: //State::
        writeline("0");
        break;
    case State::one: //State::
        writeline("1");
        break;
    default:
        writeline("d");
        break;
    }
}


//void WhatIWant(State some)
//{
//  using State{ //this makes no sense to the compiler but it expresses what I want to write
//      switch (some)
//      {
//      case zero: //I want the compiler to figure out State::zero
//          writeline("0");
//          break;
//      case one: //I want the compiler to figure out State::one
//          writeline("1");
//          break;
//      default:
//          writeline("d");
//          break;
//      }
//  }
//}

void writeline(const char * msg)
{
    std::cout << msg << std::endl;
}

Is there a way to use a switch statement and have the compiler figure out the enum class, maybe after giving a hint once?

How can std::chrono::duration::duration() be constexpr?

The default constructor of std::chrono::duration is defined as follows:

constexpr duration() = default;

(For example, see cppreference.com or the libstdc++ source.)

However, cppreference.com also says this about constexpr constructors:

A constexpr constructor must satisfy the following requirements:

...

every base class and every non-static member must be initialized, either in the constructors initialization list or by a member brace-or-equal initializer. In addition, every constructor involved must be a constexpr constructor and every clause of every brace-or-equal initializer must be a constant expression

And in case I was confused about default constructors, cppreference.com seems to say that default constructors brought into being with = default aren't defined differently than implicit default constructors.

Yet, the rep type for (most) durations is a bare integer type. So, shouldn't the explicit = default default constructor for duration be equivalent to

constexpr duration() {}

which of course would leave the integer duration::rep member variable uninitialized? And, in fact, isn't the standard behaviour of duration such that default-constructed values are uninitialized? (But I can't find a reference that explicitly says this.)

So how can the = default constructor for duration be constexpr if it leaves a non-static member variable uninitialized? What am I missing?

C++ Thread taking reference argument failed compile

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

void f1(double& ret) {
   ret=5.;
}

int main() {
   double ret=0.;
   thread t1(f1, ret);
   t1.join();
   cout << "ret=" << ret << endl;
}

The above code fails compilation with the following error message:

g++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
In file included from /usr/local/include/c++/5.3.0/thread:39:0,
                 from main.cpp:2:
/usr/local/include/c++/5.3.0/functional: In instantiation of 'struct std::_Bind_simple<void (*(double))(double&)>':
/usr/local/include/c++/5.3.0/thread:137:59:   required from 'std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (&)(double&); _Args = {double&}]'
main.cpp:11:21:   required from here
/usr/local/include/c++/5.3.0/functional:1505:61: error: no type named 'type' in 'class std::result_of<void (*(double))(double&)>'
       typedef typename result_of<_Callable(_Args...)>::type result_type;
                                                             ^
/usr/local/include/c++/5.3.0/functional:1526:9: error: no type named 'type' in 'class std::result_of<void (*(double))(double&)>'
         _M_invoke(_Index_tuple<_Indices...>)
         ^

I understand that I can use std::ref() to pass the argument. But if I pass by value, why is it an error since thread should just copy the argument by value and pass some object stored inside thread to bind with the reference argument of function f1.

I feel that if I can understand what this result_of is doing and why it is giving error, I can better understand the reason. So could anyone walk me through the error msg? Especially the meanings of std::_Bind_simple<void (*(double))(double&)> and std::result_of<void (*(double))(double&)>.

EDIT: I know if I pass a value, the thread will only work on the copy and has no effect after the thread returns. That is not my concern. I want to know why it is giving error now, but it was not giving error to other posts on SO like the following:Difference between pointer and reference as thread parameter

How to allow a program to create new objects [on hold]

Thanks so much for taking the time to look at my question!

Right now I am working with classes and objects. I am trying to write a program that stores information about visitors to a hotel. A user will input the name of the visitor and some information about them. The program will then store that information in an object and be able to calculate how much to charge for the users stay.

The problem that I am running into is that I don't know how to let the program create new objects for the visitors. For example, if Sally came in I would like to create a new object for her within the program that could store her information.

I have looked at dynamic object creation and done a fair amount of Googling on the subject but can't seem to find any answers. Here is a simplified version of what I would like to do:

#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;

class visitor {
public:
    string name;
    int age;
};

int main()
{
//a new person comes to the hotel, the person at the desk gives the program his/her name
//and age and it is put into a class so it can be used later.
}

If there is a better way to accomplish this I would love suggestions, I am but a fledgling programmer and it is very possible that I am approaching this incorrectly.

Thanks in advance!

A class with an array member of generic rank

Consider the following code sample:

#include <iostream>
#include <tuple>

template<typename T, std::size_t Rank, std::size_t... In>
struct help;

template<typename T, std::size_t... In>
struct help<T, 1, In...> 
{
    static constexpr auto a = std::make_tuple(In...);
    T data[std::get<0>(a)];
};

template<typename T, std::size_t... In>
struct help<T, 2, In...>
{
    static constexpr auto a = std::make_tuple(In...);
    T data[std::get<0>(a)][std::get<1>(a)];
};

template<typename T, std::size_t... In>
class foo : public help<T, sizeof...(In), In...>
{
private:
    using base = help<T, sizeof...(In), In...>;

public:
    template<typename... Tn>
    constexpr foo(Tn&&... args)
        : base{ { args... } } // constructor would only work if rank == 1
    {}
              T operator[](std::size_t i)       noexcept { return base::data[i]; }
    constexpr T operator[](std::size_t i) const noexcept { return base::data[i]; }
};

int main() 
{   
    foo<int, 6> a = {  1, 2, 3, 4, 5, 6  };

    for (std::size_t i = 0; i < 6; ++i) {
        std::cout << a[i] << " ";
    }
}  

This is as far as I got.

I'm trying to make a class, objects of which shall be constructed as foo<int, 2>; foo<int, 3, 4>; foo<int, 1, 2, 3, 4>; These objects will hold an array member respectively of type int[2]; int[3][4]; int[1][2][3][4].

My initial thinking was to make a helper template class which would specialize quite a lot (at least until an array of rank 20). That is obviously verbose, and after I get to an array of rank 2, I have no idea what the constructor for foo should be.

The constructor problem can be solved by making the class a POD (no access specifiers, etc) and construct via aggregate initialization (much like std::array does), but that goes against my work so far with the "proper inherited specialization".

I would appreciate some ideas. How would you go about doing something like this?

Stanford C++ coursework. Gauss' childhood

Here I am doing Standford C++ coursework.

Exercise 03 from reader exercises. Here is the given question:

Exercise 03 Compute the sum of the numbers between 1 and 100.

/*
    As mathematical historians have told the story, the German mathematician
    Karl Friedrich Gauss (1777-1855) began to show his mathematical talent 
    at a very early age. When he was in elementary school, Gauss was asked by
    his teacher to compute the sum of the numbers between 1 and 100. Gauss is
    said to have given the answer instantly: 5050. Write a program that computes
    the answer to the question Gauss’s teacher posed.
 */   

The error I am getting when executing this program is this => Guassian.cpp: In function ‘int main()’: Guassian.cpp:29:12: error: invalid use of non-static member function ob1.sumodds;

What's wrong?

#include<iostream>
using namespace std;

class Guassian
{


public:

int sumodds ( int  last )
{
    int result =    0;
    int odd = 1;
    for ( int i =    0; i < last; i++ ) 
    {
        result +=   odd;
        odd += 2;
    }
    return            result ;

}

};

int main()
{
Guassian ob1;
ob1.sumodds;
//return 0;
}

Parallel optimization - multithreading performance hit

I want to run several runs of simulated annealing with different parameters many times to tune the parameters. It seemed like this would be an obvious use case for multiple threads since each run might take several seconds for a large number of iterations and can do its work independently of the others. A sketch of the relevant portion of the code is:

// I have some vector 'results' with 4 elements that will hold the
// optimization results (call this result_t) and a vector 'probs' of 
// 4 functors of type 'prob_t'. 'cost_t' is some integral type.

auto driver = [=] (result_t& r, prob_t p) 
{ r = genericSimulatedAnneal<result_t, cost_t, prob_t> 
        (guess, params, p); };

std::vector<std::thread> threads;
for (int t_num = 0; t_num < 4; ++t_num) {
    threads.push_back(std::thread(driver, std::ref(results[t_num]),
                                  probs[t_num]));
}

for (auto& t: threads) t.join();

The signature of genericSimulatedAnneal is

template<class solution_t, class cost_t, class acceptance_p>
genericSimulatedAnneal(const solution_t&, 
                       const GenSimAnnealParams<solution_t,cost_t>&,
                       const acceptance_p&);

The problem is that when I run the 4 cases in parallel this way, it actually ends up taking twice as much CPU time per iteration as running them sequentially. My question is, where is the performance hit coming from? The driver lambda copies the guess and parameters, so threads should each be getting their own copy, and each thread's work is done entirely internally and only returned when the annealing finishes. I can't see why this wouldn't be (almost) a 4 times speedup since the vast majority of the program's work should be private to each thread.

How to generate vector like list comprehension

In C++11,

vector<string> blockPathList;
for(int i = 0; i < blockNum; i++)
{
    blockPathList.push_back(desPath + "part" + to_string(i));
}

Is it possible to re-write the code above like list comprehension, or shorter and more concise?

Checking objects before adding C++

I need to update Inventory::add_item() function definition so that before adding a new object to the items array, it first checks whether the identical object already is present and add new item only if it isn’t. I cannot understand how to make comparison between new_item and objects which are already exist using Inventory::find_item function.

#include "Inventory.h"

void Inventory::add_item(std::string modelName, float screenSize, int capacity, iPhone::Colour colour)
{

    if (_count < Inventory::MAX_SIZE)
    {
        iPhone new_item;
        new_item.init( modelName, screenSize,  capacity, colour);
        _items[_count] = new_item;
        _count++;

    }
}

iPhone Inventory::find_item(iPhone &query)
{
    for (size_t i = 0U; i < _count; i++)
    {
        iPhone& item = _items[i];

        //for string type property
        if (query.get_modelName()!= ""
            && query.get_modelName() != item.get_modelName())
            continue;

        // for number type property
        if (query.get_screenSize() != 0
            && query.get_screenSize() != item.get_screenSize())
            continue;
        // for number type property
        if (query.get_capacity() != 0
            && query.get_capacity() != item.get_capacity())
            continue;
        //for string type property
        if (query.get_colour() != iPhone::Colour::ANY
            && query.get_colour()!= item.get_colour())
            continue;
        return item;

    }
    return iPhone{};    // return the default value object (or null object)
}

Here are the other parts of code: Displaying objects which are found in C++

Compare all elements of a std::vector with every other element in the same vector efficiently

I'm new to C++.

I'm trying to find how to iterate through a vector to compare every element with every other element, where the comparison order is irrelevant where;

(a 'compared to' b) = (b 'compared to' a)

So checking one means you don't need to compare every value to EVERY other value, just the remaining ones.

I have something that's like this TOY algorithm;

#include <vector>

typedef std::vector<double> vector_t;

int countTheFoo(const vector_t &v)
{
  int fooFound {0};
  for (auto it1 = v.begin(); (it1 != v.end()); it1++)
  {
    for (auto it2 = it1.next(); (it2 != v.end()); it2++)
    {
      if testForFoo(*it1, *it2)
      {
        // Woot! Found some...
        fooFound++;
      }
    }
  }
  return fooFound;
}

vector_t foo { 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0 };

int numFoo {countTheFoo(foo)};

I'm actually comparing lines to find ones which intersect not simple doubles but the technique would be the same.

It's the;

for (auto it2 = it1.next(); (it2 != v.end()); it2++)

part that I think could be done more efficiently using lambdas.

This approach works, but;

  • Is it the most efficient way of doing this sort of iteration?

  • Can it be done as a lambda using std::for_all()?

Thank you.

How to declare template template parameter

Suppose I have two classes Foo1<T> and Foo2<T>.

I then want to create a function bar that takes a reference to a std::vector<Foo1<T>> or to a std::vector<Foo2<T>> but always returns a std::vector<Foo1<T>>:

template<class T, class Y> std::vector<Foo1<T>> bar(std::vector<Y<T>>&)

Sadly but the compiler doesn't like the <Y<T>> bit. One way round this is to provide two overloads but is there a way I can arrange the above so it's correct?

C++ REST SDK: asynchronous tasks vs. C++11 multithreading

This is a conceptual question on the asynchronous task feature of the C++ REST SDK (and maybe also a bit of a noob question).

In a basic application, I have a client and perform several requests, e.g. like

http_client client(U("whatever"));

for(int i=0; i<100; ++i)
{
    http_request request;
    //fill the request
    client.request(request).then([](http_response response) { /* do something*/});
}

(The foor-loop is just to indicate that the request is sent often, I don't really use it in my code).

Questions:

  • As far I understand, the asynchronous task library then handles those incoming requests in a parallel way -- meaning that not the main thread handles all tasks in an event-like fashion, but rather the library assigns the tasks to an underlying thread pool in some (--to me intransparent--) way. Did I get that correct?

  • If the previous view is correct, then is there any reason to combine the REST SDK with the multithreading capabilities of C++. For example, taking again the above loop, start 10 threads and in each one process 10 loop iterations. Does this makes sense or is it unnecessary?

  • Moreover, in general, are there any common patterns where one should combine the ppl-capabilities by the C++11 multithreading feature? Or is it safe to rely that the REST SDK and ppl under the hood get the job done better?

(Info: I've asked this question also on the cpprest discussion page. However, this forum seems to be not maintained anymore.)

Lambda-specific variable

Is there any way to create variable that will be unique for some lambda function and will last between launches of lambda?
More careful description: I want lambda with variable initialized to some value, and that variable should last between launches:

std::function<void(void)> a=[]()
{
    /*here we declare variable X and initialize it to 0*/;
    std::cout<<X++;
};
a();a();

So this should print out 01

But also I need to be sure that "X" is unique for "a", so after previous part this

std::function<void(void)> b=a;
b();b();

should print out 01.

I tried using static variables, but they are shared between copies(so these two parts print out 0123).

So, is there any way to do it?

Is 0-initialization of atomics guaranteed to set the value member to 0?

What does 0-initialization of std::atomic<integral_type> variable mean?

Origins of the question. I have a function-static std::array of std::atomic<std::int>, which I want to be set to 0 before the first use (goes without saying, function where the array resides is called in unpredictable manner from multiple threads).

This piece of code is good-looking, but not compiling due to atomics being non-copy constructable:

#include <array>
#include <atomic>

void foo() {
    using t = std::atomic<int>;
    static std::array<t, 2> arr = {0, 0}; // <-- explicit, but errors out (see below)
    static std::array<t, 2> arr2; // <-- implicit?, works
}

error: use of deleted function ‘std::atomic::atomic(const std::atomic&)’ std::array arr = {0, 0};

Now, I understand that static std::array is going to 0-initialize all it's members, and std::atomic<> is going to be 0-initialized. But do we have an explicit or implicit gurantee that it will actually set all values to 0? Common sense says 'yes' - after all, we assume the class would have a member of type int, and this member will be 0-initialized. But is that assumption based on solid grounds of standard?

compilation error while using constexpr

#include <stdio.h>
#include <iostream>

using namespace std;

template <typename T, int N>
int ReturnArraySize(T (&arg1)[N]) {
    return N;
}

constexpr int ReturnTheSum(int arg1, int arg2) {
    return arg1 + arg2;
}

int main(int argc, char **argv)
{
    int arr1[20];
    int arr2[ReturnArraySize(arr1)];
    int arr3[ReturnTheSum(ReturnArraySize(arr1), ReturnArraySize(arr2))];

    return 0;
}

When i compile the code i get the following error.

/root/Documents/C++11_Fundamentals/ConstExprRelatedFunc/main.cpp:19:67: error: no matching function for call to 'ReturnArraySize(int [( + 1)])'

Issues with Multiple Declarations gcc

I am attempting to use Nanovg in my OpenGL project and am getting repeated multiple definition errors such as

CMakeFiles\http://ift.tt/1oov50l: multiple definition of `nvgCreateGL3'
CMakeFiles\http://ift.tt/1q5SdT2: first defined here

Game.h

  class Game {

    public:
      void Run();
      Game(std::string Title, ScreenMode ScreenMode, int Width, int MSAASamples, bool VSync);
    private:
      GLFWwindow* Window;
      NVGcontext* VGContext;
      std::string Title;
      ScreenMode Mode;
      int Width, Height;
      int WWidth, WHeight;
      int FBWidth, FBHeight;
      int MSAASamples;
      bool VSync;
      bool Exit;
      float PixRatio;
      void Process();
      void Render();
      void KeyCallback(GLFWwindow* Window, int Key, int Scancode, int Action, int Mode);
      void SaveScreenShot(const std::string* Path);

  };

Game.cpp

//various #includes .. (STL GlaD, GLFW)

#ifndef NANOVG_INCLUDED
#define NANOVG_INCLUDED
#include <nanovg.h>
#define NANOVG_GL3_IMPLEMENTATION
#include <nanovg_gl.h>
#endif

// More #includes ...
#include <Game.h>


Game::Game(std::string Title, ScreenMode ScreenMode, int Width, int MSAASamples, bool VSync)
{
  // constructor here
}

void Game::Run(){
  // Initialise openGl and NanoVG, then into main game loop calling `Render();`
}

Render.cpp

//various #includes .. (STL GlaD, GLFW)

#ifndef NANOVG_INCLUDED
#define NANOVG_INCLUDED
#include <nanovg.h>
#define NANOVG_GL3_IMPLEMENTATION
#include <nanovg_gl.h>
#endif

// More #includes ...
#include <Game.h>

void Game::Render() {
  //Definition using Nanovg
}

Here are some other things that may be useful CMakeLists Available Here
Full Console output Available Here

What I have tried

  • Putting the line #define NANOVG_GL3_IMPLEMENTATION in Game.h
  • Putting the Nanovg includes AND the #define ... in Game.h
  • tried changing the location WHERE Game.h and the nanovg libs are placed with #includes ... (causes unknown type errors)

Many thanks in advance for the help with this issue

numeric_limits only in the first input he wait for second input

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>

using namespace std;

int main() 
{   
    int num, num2;  
    do  
    {       
        cout << "Enter number:";
        cin.clear();        
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cin.clear();        
        cin >> num;     
    }
    while (!(num > 1000 && num < 9999));
    cout << num << endl;    
    return 0; 
}

how to calculate epsilon of mpf_class

I try to improve a c++ programm by using the GMP (GNU Multiple Precision Arithmetic Library).

There is a counter variable that periodically will be increased by a result of a calculation of type double. The addition happens inside a ISR (interrupt service routine) because of this it should be fast.

Until now the counter variable is of type double which causes a problem. Some devices (running since years) reach a point where each addition fall under absorbtion so nothing happens anymore. Other devices already start to discard smaller additions.

Because this it is time to improve it by using mpf_class instead double. But in order to set the size of the mpf_class properly i need to know the ε (epsilon).

My question is: How can i calculate the epsilon of a mpf_class object?

An example(c++) of this calculation would be great.

Why does std::extent applied to auto& yield zero?

I was experimenting with constexpr auto and string literals to get character arrays I could use with std::begin in a generic way, when I ran into something I couldn't explain: the expression std::extent<decltype(foo)>::value, where foo is declared using auto reference, yields zero.

 #include <iostream>
 #include <type_traits>

 namespace {
   auto& ARRAY_REFERENCE = "foo";

   template<typename T, std::size_t N>
   std::size_t numberOfElementsIn(T (&)[N]) { return N; }
 }

 int main() {
   std::cerr <<
     "std::extent applied to ARRAY_REFERENCE: " << std::extent<decltype(ARRAY_REFERENCE)>::value << "\n"
     "Number of elements in ARRAY_REFERENCE: " << numberOfElementsIn(ARRAY_REFERENCE) << "\n"
     ;
   return 0;
 }

The code above gives me the output

std::extent applied to ARRAY_REFERENCE: 0
Number of elements in ARRAY_REFERENCE: 4

Why doesn't the expression involving std::extent evaluate to 4?

how can I deduce template parameter without using decltype [on hold]

For a given the template function

template <int N, typename T> 
std::array<double, N> array_creator ( const T &b )
{
    std::array<double, N> arr;
    for ( int i = 0; i < N; ++i )
        arr[i] = b ( i ); 
    return arr;
}

I don't want to write down T type. That is, I can now write something like this:

Eigen::ArrayXXd m(4,4);
int sz = 1;
auto b = array_creator<2, decltype(m.block<1, 1> ( 1,sz ))>
       ( m.block<1, 1> ( 1,sz ) );

I don't want to write type T as a template parameter, since it can be quite complex, i.e. Eigen::Block<Eigen::ArrayXXd, 1, 2, false>> . Besides, it seems that decltype works, but then I have to copy the expression from function argument. I'd like to write something like this:

auto b = array_creator<2>( m.block<1, 1> ( 1, sz ) );

Any thoughts how this could be done?

Overall configuration object for a god object and late initialisation

There are two main parts to this question: storing configuration values in a single file/place and delaying initialisation of a contained object.

I have an embedded program which controls a PCB test fixture for a semi-automated test. I would like to store all of the limits/test parameters in a single place (preferably as read only/constants) so that they can be easily located and tweaked in the future. The problem is that some of the values are within nested structs and the only way that I know of initialising these objects is using the dreaded initialiser list where all traceability is lost (or a constructor which is almost as bad).

e.g.

class Configuration {

public:
  struct NestedStruct {
    float value1;
    float value2;
    float value3;
  };

  struct ContainerStruct {
    int value1;
    float value2;
    NestedStruct nested1;
    NestedStruct nested2;
    NestedStruct nested3;
    float value3;
  };

  // Initialise struct data member.
  // Not obvious which value is which?
  constexpr static const ContainerStruct containerStruct {5, 2.3, 1.4, 4.2, 0.7, 3.5, 2.5, 3.5, 0.2, 0.2, 0.1, 4.6};

};

How can I store read only configuration values made up of complex/nested struct values in one place while maintaining readability?

I've decided to wrap the core functionality into a single controller object that instantiates multiple contained objects. One of these objects is passed to some of the other objects via a pointer. I use the configuration values mentioned above (for which there are lots!) to initialise these objects.

Using an initialiser list makes the constructor of the Controller class long and untidy. One way I could get around this is by creating a default initialiser for the contained objects that which a separate initialiser function which I can call in the body of the Controller's constructor.

I've always read that two step/ lazy initialisation is bad as the object isn't immediately usable. Is there another way around this?

Maybe there is a better way than wrapping it in a god object?

Example parameters that I want to store in one place:
Adc object parameters:

float voltageReference;
uint8_t slaveSelectPin;

NavigationButtons object parameters:

struct AdcValues {
  uint_fast16_t buttonUp;
  uint_fast16_t buttonDown;
  uint_fast16_t buttonLeft;
  uint_fast16_t buttonRight;
  uint_fast16_t buttonCentre;
  uint_fast8_t tolerance;
};

UutPower object parameters:

struct CurrentCompensation {
  float LowX;
  float LowC;
  float MidX;
  float MidC;
  float HighX;
  float HighC;
};

VoltageTests object parameters:

struct TestParameter {
  float scalingFactor; // Potential divider scaling for voltages >voltageRef.
  float limitLower;
  float limitUpper;
  const char *signalName;
};

// Lots of nested structs.
struct TestParameters {
  TestParameter tb1_1;
  TestParameter tp15;
  TestParameter tp4;
  TestParameter tp1;
  TestParameter tp3;
  TestParameter tp20;
  TestParameter tp12;
  TestParameter tp29;
  TestParameter tp28;
  TestParameter con3_6;
  TestParameter con3_2;
}

Other parameters:

float currentLimitLow;
float currentLimitHigh;
const char *version; 

Any help appreciated.

"undefined reference to" linker error while working with templates [duplicate]

This question already has an answer here:

I have a class Array

template <typename T>
class Array : public SequentialContainer<T>{
public:
    Array(Int size){local_vector.reserve(size);}
    Array(std::initializer_list<T> initializer_list){
        local_vector.assign(initializer_list);
    }
    virtual Boolean contains(T &object) const;
    virtual Boolean contains(Container<T> &container) const;
    virtual Int size() const;
    virtual T &operator[](Int idx);
    virtual T &get(Int idx);
    virtual void set(Int idx, const T &object);
    virtual Int indexOf(T &object);
    virtual Iterator<T> iterator() const;
};

All the methods are implemented like this in the Array.cpp file:

template <typename T>
Boolean Array<T>::contains(T &object) const {
//code
}

If i try to use this Array class in a main.cpp file:

Array<int> c = {1, 2, 3, 4, 5, 6};
std::cout << c.[4] <<std::endl;

I am getting these linker errors:

undefined reference to `Array<int>::iterator() const'
undefined reference to `Array<int>::contains(int&) const'
undefined reference to `Array<int>::contains(Container<int>&) const'
etc...

for every single method of the Array class. All the files are in my cmake file and should be compiled. Why I am getting this linker error? could someone explain me this please?

Access same value with one of multiple keys in c++?

I need a way to access a value by passing in any key that the value could have. For example, a player object that can be accessed by either their ip address or name?

To illustrate.

Player1 has ["a", "1.2.3.4"] Player2 has ["b", "3.4.5.6"] Player3 has ["c", "2.2.9.3"]

So, to access Player2 I could use players["b"], or players["3.4.5.6"]

Should I just iterate over a vector for that? But I plan to have anywhere around 100 elements, so would a tree-like container be better than an array list?

Could you use std::multimap for that? Or even in std::map?

Advantage and disadvantage of nested class

When I prefer to store members in struct inside a class and when I prefer to create a nested class in a class and store members?

For example:

class SkypeProtocol
{
public:
    SkypeProtocol();
    virtual ~SkypeProtocol(){}

private:

    class SkypeProtocolDateTime
    {
    private:
        UI32 uDate;
        ERROR GetDateString(PUCHAR pcBuffer,PUI32 uBufLen);
    };

};

or

class SkypeProtocol
{
private:
    SkypeProtocol();
    virtual ~SkypeProtocol(){}

    typedef struct SkypeProtocolDateTime
    {
    private:
        UI32 uDate;
        ERROR GetDateString(PUCHAR pcBuffer,PUI32 uBufLen);
    }SSKYPE_STRUCT;

};

Find the specific cubic root that solves the constraint using binary search

I am trying to find a cubic root(t) for the following equation, constraints

F(t)=A(t^3)+B(t^2)+C*(t)+D, F(t)<=10^18.
Help find t such that F(t+1) > K, and F(t) <= K

I have tried the following approach;

What I did is followed binary search approach.Intially put t value as k/2 in the equation. If the result value is greater than k, I will try with t value k/4.Else if result less than k, I will check wit t value k/4. The program seems works with smaller values of k but the problem is the values exceeding the range for larger k. I guess I should pickup a better pivot value(intiall value) or change some equation

    int a,b,c,d;
    long long int k,x,y;
    long long int i,f,temp1;
    int def;

    def=0;
    cin>>a>>b>>c>>d>>k;
    i=1;
    f=k;
    temp1=(1+k)/2;
    while((temp1>=1)&&(temp1<=k))
    {
        x=a*(temp1+1)*(temp1+1)*(temp1+1)+b*(temp1+1)*(temp1+1)+c*(temp1+1)+d;
        y=a*(temp1)*(temp1)*(temp1)+b*temp1*temp1+c*temp1+d;
        if((x>k)&&(y<=k))
        {
            cout<<temp1<<endl;
            def=1;
            break;
    }
    else if(x<k)
    {
        i=temp1;
        temp1=(f+temp1)/2;

    }
    else if(x>k)
    {
        f=temp1;
        temp1=(i+temp1)/2;
    }

}
        if(def==0)
         cout<<def<<endl;
       return 0;
}

How to increment a variable from lambda-functor's body?

I tried to increment a local variable from lambda expression:

#include <iostream>

template<typename T>
T foo(T t){
    T temp{};
    [temp]() -> void { 
        temp++; 
    }();
    return temp;
}

int main()
{
    std::cout<< foo(10) << std::endl;
}

DEMO

But got the following error:

main.cpp: In instantiation of 'foo(T)::<lambda()> [with T = int]':

main.cpp:6:6:   required from 'struct foo(T) [with T = int]::<lambda()>'

main.cpp:8:6:   required from 'T foo(T) [with T = int]'

main.cpp:14:23:   required from here

main.cpp:7:13: error: increment of read-only variable 'temp'

         temp++; 

             ^

Is there some workaround about that in c++11/14?

Iterate over first N elements of c++11 std::array

I am using a std::array (c++11). I am choosing to use a std::array because I want the size to be fixed at compile time (as opposed to runtime). Is there anyway I can iterate over the first N elements ONLY. i.e. something like:

std::array<int,6> myArray = {0,0,0,0,0,0};
std::find_if(myArray.begin(), myArray.begin() + 4, [](int x){return (x%2==1);});

This is not the best example because find_if returns an iterator marking the FIRST odd number, but you get the idea (I only want to consider the first N, in this case N=4, elements of my std::array).

Note: There are questions similar to this one, but the answer always involves using a different container (vector or valarray, which is not what I want. As I described early, I want to size of the container to be fixed at compile time).

Thank you in advance!!

Metaprogramming for optimizing storage, C++

I'd like to generalize bitwise operators in C++ without thinking that the underlying structure is an array.

As instance... if I want to represent 86 bits i would use a structure structure/class like:

typedef struct {
 uint64_t x[1];
 uint16_t y[1];
 uint8_t z[1];
} sampleStruct;

Instead if i would like to allocate 160 bits I would use a structure like:

typedef struct {
 uint64_t x[2];
 uint32_t y[1];
} sampleStruct;

I guess a trivial, but not optimal solution for the storage would be to assume all chunks are uniform and allocate the minimum of those s.t. it covers the size I'm implementing, however even for a matter of exercise I prefer the way I exposed.

To me it sounds clear that I should use metaprogramming to solve the problem, so I have to properly define

template <int I>
typedef sampleStruct {
  //something
}

However I'm not a big expert on C++ template metaprogramming so i would like to understand what would be the best way to implement the different kind of sample struct varing I. I know how to decide the best "cover" for my length it would be something like:

N64 = I/64;
RemN = I%64;
if(0 < RemN <= 8) {
  add uint8_t var;
} else if (8 < RemN <= 16) {
  add uint16_t var;
} else if (16 < RemN <= 24) {
  add uint16_t var;
  add uint8_t var;
} else {
  //Similarly handle the other cases from 24 < RemN < 64
}

What can I do to achieve what I want to do?

Hoping it is clear enough... (Assume C++11 or more recent versions).

How to pass char array to other function c++ [on hold]

Im doing a school c++ assignment and can't seem to pass an array to another function. Here is my source code. How do I pass the arrays to the displayinfo function?

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

void setCourseName(string);
void InputValue();


int main()
{
    InputValue();    
}

void InputValue()
{
    char semester;
    string courseTitle;
    string courseType;
    int credits;
    string lettergrade;
    double gpa;

    array<char, 7> sem1array;
    array<string, 7> sem1coursetitles;
    array<string, 7> sem1courseTypes;
    array<int, 7> sem1credits;
    array<string, 7> sem1lettergrades;


    for (int counter = 0; counter < sem1array.size(); counter++)
    {
        bool valid1 = false;
        bool validCredits = false;
        bool valid3 = false;
        bool valid4 = false;
        while (valid1 == false)
        {
            cout << "Enter Semester Number" << endl;
            cin >> semester;
            if (semester == '1' || semester == '2')
            {
                cout << "valid input" << endl;
                sem1array[counter] = semester;
                valid1 = true;
            }
            else
            {

                cout << "Invalid Input! RE ENTER SEMESTER NUMBER EITHER 1 OR 2!" << endl;
            }
        }
            cout << "Enter Course Title: " << endl;
            cin.ignore();
            getline(cin, courseTitle);
            if(courseTitle.size() <= 25)
                sem1coursetitles[counter] = courseTitle;
            else
            {
                cout << "Course Name Cannot Be More Than 25 Characters; Course name limited to first 25 characters!" << endl;
                courseTitle = courseTitle.substr(0, 25);
                sem1coursetitles[counter] = courseTitle;
            }

        while (valid3 == false)
        {
            cout << "Enter Course Type: Regular, AP, or Honors" << endl;

            getline(cin, courseType);
            if (courseType == "Regular" || courseType == "AP" || courseType == "Honors")
            {
                sem1courseTypes[counter] = courseType;
                valid3 = true;
            }
            else
            {
                cout << "Invalid Input! RE ENTER COURSE TYPE EXACTLY HOW IT APPEARS EITHER Regular, AP, or Honors!" << endl;
            }
        }
        while(validCredits == false)
        {
            cout << "Enter Credits Earned For Course: **Can Either Be 1-4 Credits**" << endl;
            cin >> credits;
            if (credits == 1 || credits == 2 || credits == 3 || credits == 4)
            {
                sem1credits[counter] = credits;
                validCredits = true;
            }
            else
            {
                cout << "Invalid Output! Must Enter Number 1-4 For Credits Earned!" << endl;
            }
        }
        while (valid4 == false)
        {
            cout << "Enter Letter Grade; Capital Letter Followed By A Plus + or Minus - If There Is One!Example: A+, A-, A, B+..." << endl;
            cin.ignore();
            getline(cin, lettergrade);
            if (lettergrade == "A+")
            {
                gpa = 4.0;
                sem1lettergrades[counter] = lettergrade;
                valid4 = true;
            }
            else if (lettergrade == "A")
            {
                gpa = 4.0;
                sem1lettergrades[counter] = lettergrade;
                valid4 = true;
            }
            else if (lettergrade == "A-")
            {
                gpa = 3.7;
                sem1lettergrades[counter] = lettergrade;
                valid4 = true;
            }
            else if (lettergrade == "B+")
            {
                gpa = 3.3;
                sem1lettergrades[counter] = lettergrade;
                valid4 = true;
            }
            else if (lettergrade == "B")
            {
                gpa = 3.0;
                sem1lettergrades[counter] = lettergrade;
                valid4 = true;
            }
            else if (lettergrade == "B-")
            {
                gpa = 2.7;
                sem1lettergrades[counter] = lettergrade;
                valid4 = true;
            }
            else if (lettergrade == "C+")
            {
                gpa = 2.3;
                sem1lettergrades[counter] = lettergrade;
                valid4 = true;
            }
            else if (lettergrade == "C")
            {
                gpa = 2.0;
                sem1lettergrades[counter] = lettergrade;
                valid4 = true;
            }
            else if (lettergrade == "C-")
            {
                gpa = 1.7;
                sem1lettergrades[counter] = lettergrade;
                valid4 = true;
            }
            else if (lettergrade == "D+")
            {
                gpa = 1.3;
                sem1lettergrades[counter] = lettergrade;
                valid4 = true;
            }
            else if (lettergrade == "D")
            {
                gpa = 1.0;
                sem1lettergrades[counter] = lettergrade;
                valid4 = true;
            }
            else if (lettergrade == "F")
            {
                gpa = 0.0;
                sem1lettergrades[counter] = lettergrade;
                valid4 = true;
            }

            else
            {
                cout << "Invalid Input! Please Re-Enter Letter Grade! Example: A+, A-, A, B+..." << endl;
            }
        }
    }

    displayinfo(sem1array);

}
void displayinfo(char b[])
{
    for (int k = 0; k < sem1array.size(); k++)
    {
        cout << "Semester: " << sem1array[k] << "           " << "Course: " << sem1coursetitles[k] << endl;

    }

}

will vectors stay contiguous after swapping?

Will vectors stay contiguous after swapping two elements?

PS: Regardless of the answer what might be, How can we really be sure? if that's possible.

`#define` a very large number in c++ source code

Well, the question is not as silly as it sound.

I am using C++11 <array> and want to declare an array like this:

array<int, MAX_ARR_SIZE> myArr;

The MAX_ARR_SIZE is to be defined in a header file and could be very large i.e. 10^15. Currently I am typing it like a pre-school kid

 #define MAX_ARR_SIZE 1000000000000000

I can live with it if there is no alternative. I can't use pow(10, 15) here since it can not be evaluated at compile time; array initialization will fail. I am not aware of any shorthand to type this.

Copying x-value by value returned by a function

I stumbled upon a code similar to this while debugging a crash due to de-referencing a dangling piece of memory.

template<typename RaiiObject, typename HandleType>
const HandleType& ExtractHandle(const RaiiObject &value){

    const HandleType* val = value.get(); // get underlying managed object
    return static_cast<const HandleType&>(*val);
}

On the caller side the code looked like this:

const auto &x = ExtractHandle(GetAHandle()); 

This is a definitely a problem because the reference to the underlying object that we will be getting from ExtractHandle will be dangling since the Raii object managing it would have expired.

Now the dev fixing this issue replaced the capture by reference to capture by value.

auto x = ExtractHandle(GetAHandle());

His claim is that since we are making a copy, we are safe since the x-value returned by GetAHandle will not die till the copy constructor for Handle is invoked. Is this assumption correct? Is it well defined by standard that the above proposed fix is not UB?

Note: While the correctness and utility of this design can definitely be questioned, the point is more around whether copying by value guarantees a well defined behavior

Binary filestream to byte std::vector skips spaces

When I use this code

std::string filename = "tmp.bin";
std::ifstream fileStream;
std::vector<unsigned char> fileBuffer;

fileStream = std::ifstream(filename.c_str(), std::ios::binary | std::ios::ate);     
fileBuffer.reserve(fileStream.tellg());
fileStream.seekg(0, std::ios::beg);
fileBuffer.insert(fileBuffer.begin(), std::istream_iterator<BYTE>(fileStream), std::istream_iterator<BYTE>());

all original spaces in my binary file are skipped -> fileBuffer contains no spaces, but need all tokens for Base64 encoding.

What is wrong here?

Is there a shorter way to initialize a QByteArray?

In my program I work a lot with serial communication so QByteArray is used very often.

I was wondering if there was a shorter way to initialize a QByteArray with specific bytes than:

const char test_data[] = {
    static_cast<char>(0xB1), static_cast<char>(0xB2),
    0x5, static_cast<char>(0xFF),
    static_cast<char>(0xEE), static_cast<char>(0xEE),
    static_cast<char>(0xB3)};
const QCanBusFrame frame = QCanBusFrame(0xA1, QByteArray(test_data));

The static_cast<char> is necessary because otherwise C++11 gives an error about narrowing, because the range 0x7F to 0xFF is bigger than a char could fit--but a char is what the QByteArray constructor asks for.

This is the QByteArray constructor being used:

QByteArray::QByteArray(const char *data, int size = -1)

Confusion about the return type of std::get() on std::tuple objects

Please see the following code (see it live here):

#include <iostream>
#include <tuple>
#include <type_traits>
#include <utility>

struct S {
  int&& v;  
};

int main() {
  std::tuple<int&&> t(1);
  std::cout << std::is_same<int, decltype(std::get<0>(t))>{} << std::endl;
  std::cout << std::is_same<int&, decltype(std::get<0>(t))>{} << std::endl;
  std::cout << std::is_same<int&&, decltype(std::get<0>(t))>{} << std::endl;
  S s{1};
  std::cout << std::is_same<int&&, decltype(s.v)>{} << std::endl;
}

I'm expecting to see the output 0 0 1 1, but both GCC and clang give the output 0 1 0 1 instead. Really confused. Could someone give me an explanation?

How to call a created functor object as found in another stackoverflow?

In the stackoverflow question Template function that can take lambda or function pointer and deduce arguments for passing to another template there is a functor object created through the CreateFunctor call. How can I use it to invoke doSomething?

int main(){
    auto f1 = CreateFunctor([](int a, int b){doSomething(a, b);}, 1, 2);
    f1(1,2);
}

Does not work.

See http://ift.tt/1PH7nCC as example.

mercredi 30 mars 2016

Starting c++11 thread with a lambda capturing local variable

I have a rather basic problem and not sure where it originates from: lambda capture evaluation in a concurrent environment or misuse of boost filesystem library.
This is sample code:

#include <iostream>
#include <vector>
#include <thread>
#include <boost/filesystem.hpp>

using namespace std;
using namespace boost::filesystem;

void query(const string filename)
{
    cout << filename << " ";
}

int main() {
    path p("./");
    vector<thread> thrs;

    for(auto file = directory_iterator(p); file != directory_iterator(); ++file)
    {
        thread th( [file] {query(file->path().string());} );
        thrs.push_back(move(th));
    }

    for (auto& t : thrs)
        t.join();

    return 0;
}

which at runtime gives:

:~/workspace/sandbox/Release$ l
main.o  makefile  objects.mk  sandbox*  sources.mk  subdir.mk
:~/workspace/sandbox/Release$ LD_LIBRARY_PATH=$http://LD_LIBRARY_PATH:/home/a/custom-libs/boost-1_59/lib/ ./sandbox 
./subdir.mk ./sources.mk ./sandbox ./objects.mk ./main.o ./main.o

Notice the race condition - not all files end up being passed to thread function (at this run makefile is missing).
I am able to find a workaround by extracting the argument in a local var, rewriting the loop body as:

    auto fn = file->path().string();
    thread th( [fn] {query(fn);} );
    thrs.push_back(move(th));

Where is the race condition coming from?
Isn't file->path().string() evaluated right at the time of thread creation?

What is the standard mandated behavior of std::promise's destructor after calling set_value_at_thread_exit?

If you destroy an std::promise whose shared state is not yet ready, but for which someone has called set_value_at_thread_exit (and that thread has not yet exited), what is the expected result?

As best I can tell, the destructor for the promise should store a future_error exception (with code broken_promise) into the shared state. However, this does not appear to be the behavior for GNU/libstdc++, which will yield the stored value (and not throw an exception) on a call to the future's get().

I've come to my conclusion based on my reading of cppreference's descriptions for std::promise::set_value_at_thread_exit:

Stores the value into the shared state without making the state ready immediately. The state is made ready when the current thread exits, after all variables with thread-local storage duration have been destroyed.

and for std::promise::~promise

Abandons the shared state:

  • if the shared state is ready, releases it.
  • if the shared state is not ready, stores an exception object of type std::future_error with an error condition std::future_errc::broken_promise, makes the shared state ready and releases it.

For example code:

#include <future>

void foo(std::promise<int> p)
{
  p.set_value_at_thread_exit(42);
  // p is destroyed here
}

int main()
{       
  std::promise<int> p;
  std::future<int>  f = p.get_future();
  std::thread t(foo, std::move(p));
  t.join();
  (void)f.get(); // Throw future_error or return 42 ?
}

std::aligned_union not working as I would expect

I am trying to simulate having a union with an int and a double as follows

int main() {

    union U { double d; int a; };
    std::aligned_union<8, int, double> buffer;
    cout << "Size of the union is " << sizeof(U) << endl;
    cout << "size of the buffer is " << sizeof(buffer) << endl;

    return 0;
}

But the output of the program is always that the size of the union is an 8 and the sizeof the aligned union is 1. Could someone explain how I am using this wrong?

Thanks!

MultiThreading C++ MacOSX error: using deleted function

So sorry for any errors in formatting. I had a difficult time trying to paste the code.

I'm trying to do multithreading and I'm having these errors from Xcode. The ServerSocket uses socket.h. And I used thread.h from C++11 for this. The file the error message refers to is #include

void start_thread(ServerSocket& sock){
try{
    string data; string command;
    while(true){
        sock >> data;
        cout << "Client reply: " << data << endl;
        cout << ">" ;
        getline(cin, datasend);
        sock << datasend;
    }
    }catch(SocketException&){}
}



void start(){
    try {
        ServerSocket server (PORT); 
        while (true){
            Client new_cli(++cli_id);
            server.accept(new_cli.socket());
            thread start_thread(start_thread,new_cli.socket());
        }
    }catch (SocketException& e){
        cout << "Socket Exception: " << e.description() << endl;
    }
}
int main(){start()}

g++ ServerSocket.cpp Client.cpp server.cpp -std=c++14 -pthread In file included from server.cpp:4: /Applications/http://ift.tt/1PGGPRK: error: attempt to use a deleted function __invoke(_VSTD::move(_VSTD::get<0>(__t)), _VSTD::move(_VSTD::get<_Indices>(__t))...); ^ /Applications/http://ift.tt/1MCHFEE: note: in instantiation of function template specialization 'std::__1::__thread_execute' requested here __thread_execute(*__p, _Index()); ^ /Applications/http://ift.tt/1PGGPRM: note: in instantiation of function template specialization 'std::__1::__thread_proxy >' requested here int __ec = pthread_create(&__t_, 0, &__thread_proxy<_Gp>, __p.get()); ^ server.cpp:55:11: note: in instantiation of function template specialization 'std::__1::thread::thread' requested here start_thread(start_thread,new_cli.socket()); ^ /Applications/http://ift.tt/1MCHFEG: note: '~__nat' has been explicitly marked deleted here ~__nat() = delete; ^ 1 error generated.

rational approximation of square root of std::ratio at compile-time

I'm trying to find a rational approximation of the square root of a std::ratio at compile time. It would be extremely useful to derive ellipsoid parameters from defined parameters for coordinate conversions, which are themselves defined as std::ratio.

There is a question about finding powers/roots of std::ratio, but as a condition of that question, it was OK to fail if the ratio had no integral root, which is the opposite of what I want. I would instead like to find the closest reasonable approximation I can.

I've come up with the following meta-program that calculates the roots based on the Newton-Raphson Method, which is known to produce (relatively) accurate results with only a few iterations:

namespace detail
{
    /// implementation of ratio_sqrt
    template<class N, class K = std::ratio<4>, std::intmax_t RecursionDepth = 5>
    struct ratio_sqrt_impl
    {
        // Recursive Newton-Raphson
        // EQUATION: K_{n+1} = (K_{n} - N / K_{n}) / 2
        // WHERE:
        // K_{n+1} : square root approximation
        // K_{n}   : previous square root approximation
        // N       : ratio whose square root we are finding
        using type = typename ratio_sqrt_impl<N, std::ratio_subtract<K,
          std::ratio_divide<std::ratio_subtract<std::ratio_multiply<K, K>, N>, 
          std::ratio_multiply<std::ratio<2>, K>>>, RecursionDepth - 1>::type;
    };
    template<class N, class K>
    struct ratio_sqrt_impl<N, K, 1>
    {
        using type = K;
    };
}

template<class Ratio>
using ratio_sqrt = typename detail::ratio_sqrt_impl<Ratio>::type;

With the example usage:

// Error calculations
using rt2 = ratio_sqrt<std::ratio<2>>;
std::cout << (sqrt(2) - ((double)rt2::num / rt2::den))/sqrt(2) << std::endl;

scalar_t result = pow<2>(scalar_t((double)rt2::num / rt2::den));
std::cout << (2 - result.toDouble()) / 2 << std::endl;

using rt4 = ratio_sqrt<std::ratio<4>>;
std::cout << (sqrt(4) - ((double)rt4::num / rt4::den)) / sqrt(4) << std::endl;

using rt10 = ratio_sqrt<std::ratio<10>>;
std::cout << (sqrt(10) - ((double)rt10::num / rt10::den)) / sqrt(10) << std::endl;

Producing the results:

1.46538e-05 // sqrt(2)

4.64611e-08 // sqrt(4)

2.38737e-15 // sqrt(10)

which could certainly be decent for some applications.

The Problems

  1. The biggest problem here is the fixed Recursion depth. These ratios get BIG, very quickly, and so for roots > 100, this overflows like crazy. However, too small of a recursion depth, and you lose all the accuracy.

Is there a good way that the recursion could be adapted to the overflow depth limit, and then have the type set to be an iteration or two before that? (I say a few iterations because it might be nice to keep headroom in the integer sizes to do further calculations later)

  1. The initial condition of 4 seemed to be pretty magical in terms of producing the lowest error for roots < 100, but is there a more methodical way to set that?

C++11 making variadic constructor understand an initialization list of initialization lists

Let's say I have a class of Point and and an array of Points, where the number of points is given by a template parameter. How do I get initialization to work using braces? If I use:

class Point {
public:
    float x, y;
    Point(float x, float y) : x(x), y(y) {}
};

template <size_t N>
class Array {
private:
    std::array<Point, N> _points;

public:
    template <typename... Points>
    Array(const Points& ... points) : _points({ points... }) {
    }
};

Then this works:

Array<2> a{Point{1,1}, Point{2, 2}};

But If I don't provide explicit Point objects, I get an error in Xcode:

Array<2> c{{1,1}, {2, 2}};

The error is: "No matching Constructor for initialization of Array<2>". For the particular constructor it says "Candidate constructor not viable: requires 0 arguments, but 2 were provided".

How do I get this to work?

Other ways of checking if a class has a certain member function

Let's check if

struct Thing {
    int foo(double, bool) {return 0;}
};

has the int foo(double, bool) member function during compile time. There are many ways of doing this, and most are just variations of others. Can someone think of a way that is vastly different (or at least fairly creative) than the 5 ways I mention here? I'm just trying to learn some new techniques with templates and SFINAE.

#include <iostream>
#include <type_traits>

// Using void_t (this includes using std::is_detected).
template <typename T>
using void_t = void;

template <typename T, typename = void>
struct has_foo : std::false_type {};

template <typename T>
struct has_foo<T,
        void_t<decltype(static_cast<int>(std::declval<T>().foo(double{}, bool{})))>
    > : std::true_type {};

// Using the ... default argument.
template <typename T>
struct hasfoo {
    template <typename U>
    static std::true_type test (decltype(static_cast<int(T::*)(double, bool)>(&T::foo))*);  // or 'decltype(static_cast<int>(std::declval<U>().foo(double{}, bool{})))*' works fine too.

    template <typename>
    static std::false_type test (...);

    static constexpr bool value = decltype(test<T>(nullptr))::value;
};

// Overloads and trailing return types.
template <typename>
struct Helper : std::true_type {};

template <typename T>
auto helper(int) -> Helper<decltype(static_cast<int>(std::declval<T>().foo(double{}, bool{})))>;

template <typename>
std::false_type helper(long);

template <typename T>
constexpr bool hasFoo() {return decltype(helper<T>(0))::value;}

// Comma operator (basically the same as the above).
template <typename T>
auto check(int) -> decltype(static_cast<int>(std::declval<T>().foo(double{}, bool{})), std::true_type{});

template <typename T>
std::false_type check(...);

template <typename T>
using HasFoo = decltype(check<T>(0));

// Member function pointer template parameter.
template <typename T>
struct Hasfoo {
    template <typename U, int(U::*)(double, bool)>
    struct Tag;

    template <typename U>
    static constexpr bool test (Tag<U, U::foo>*) {return true;}

    template <typename>
    static constexpr bool test (...) {return false;}

    static constexpr bool value = test<T>(nullptr);
};

// Tests
struct Thing {
    int foo(double, bool) {return 0;}
};

int main() {
    static_assert (has_foo<Thing>::value, "");
    static_assert (hasfoo<Thing>::value, "");
    static_assert (hasFoo<Thing>(), "");
    static_assert (HasFoo<Thing>::value, "");
}

Edit: I just remembered an elegant and general solution that Yakk gave to a different question quite a while ago (here is his actual typing, modified only to match the foo function):

namespace meta {
  namespace details {
    template<template<class...>class Z, class=void, class...Ts>
    struct can_apply : std::false_type {};
    template<template<class...>class Z, class...Ts>
    struct can_apply<Z, decltype((void)(std::declval<Z<Ts...>>())), Ts...>:
      std::true_type
    {};
  }
  template<template<class...>class Z, class...Ts>
  using can_apply = details::can_apply<Z,void,Ts...>;
}

template<class T>
using member_foo = decltype( std::declval<T>().foo(double{}, bool{}) );

template<class T>
using has_member_foo = meta::can_apply<member_foo, T>;

What's the default value for a std::atomic?

I find that in practice, with a variety of C++11/C++14 compilers, a std::atomic has an undefined initial value just as it would if it were a "raw" type. That is, we expect that for the expression

int a;

a may have any value. It also turns out to be true that for the expression

std::atomic< int > b;

b may also have any value. To say it another way,

std::atomic< int > b;         // b is undefined

is not equivalent to

std::atomic< int > b{ 0 };    // b == 0

or to

std::atomic< int > b{};       // b == 0

because in the latter two cases b is initialized to a known value.

My question is simple: where in the C++11 or C++14 spec is this behavior documented?

Using braces with parameter packs in c++11

I'm trying to determine the rules for passing a template argument as a parameter or single argument. Depending on how the brackets are specified seems to determine whether the ... is required when passing the templated type to std::forward.

void test(int)
{

}

template<class... Args>
void foobar(Args&&... args)
{
  test(std::forward<Args...>(args)...);
  test(std::forward<Args>(args)...);
  test(std::forward<Args...>((args)...));
  test(std::forward<Args>((args)...)); // doesn't compile
}

int main()
{
  int x = 5;
  foobar(x);
}  

clang gives the following when trying to compile error: parameter packs not expanded with ‘...’: test(std::forward((args)...));

Efficient way of determining whether one vector is a subset of another or not?

Given two sorted vectors consisting of unique values between 0 and some known 'n'. And size of one vector (set1) will always be greater than that of candidate vector set2.

Query: Is to determine whether given set2 is a subset of set1 or not?

Is their any better and efficient way of doing this apart from the following implementation in C++11?

#include <iostream>
#include <vector>


bool subSetCheck(std::vector<int> set1, std::vector<int> set2) {

    //Set1 & 2 are always sorted and contain only unique integers from 0 to some known 'n'
    //Set1 is always larger than Set2 in size

    std::vector<int>::iterator it1 = set1.begin();
    std::vector<int>::iterator it2 = set2.begin();
    bool subSet = true;
    for (; (it1 != set1.end()) && (it2 !=set2.end()) ;) {

        if ( *it1 == *it2) {++it1; ++it2;}
        else if( *it1 > *it2) ++it2;
        else ++it1;
    }

    if (it1 ==set1.end()) subSet = false;

    return subSet;
}

int main () {

    std::vector<int> set1{0,1,2,3,4};
    std::vector<int> set2{0,1,5};

    if (subSetCheck(set1,set2)) std::cout << "Yes, set2 is subset of set1." << std::endl;
    else std::cout << "No! set2 is not a subset of set1." << std::endl;

    return 0;
}

parallel loop over pairs

What is the best way in C++11 to perform a pairwise computation in multiple threads? What I mean is, I have a vector of elements, and I want to compute a function for each pair of distinct elements. The caveat is that I cannot use the same element in multiple threads at the same time, e.g. the elements have states that evolve during the computation, and the computation relies on that.

Using range based for loops on own container [duplicate]

This question already has an answer here:

I am writing my own container, just for fun and practice. I wanna be able to use a range based for loop on my container. How can i achieve this? is there a abstract class i have to derive from or something like this?

Valgrind error(invalid read) operator delete(void*) when freeing objects from map

Unfortunately I'm facing this problem inside one of my classes

==4442== Invalid read of size 4
==4442==    at 0x806EC34: std::_Rb_tree_increment(std::_Rb_tree_node_base*) (in /home/blabla/projects/test proj)
==4442==    by 0x804C634: std::_Rb_tree_iterator<std::pair<std::string const, Order*> >::operator++(int) (stl_tree.h:197)
==4442==    by 0x804B98C: Play::~Play() (Play.cpp:46)
==4442==    by 0x80501AF: main (main.cpp:121)
==4442==  Address 0x421c5c4 is 12 bytes inside a block of size 24 free'd
==4442==    at 0x402B3D8: free (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==4442==    by 0x8050D4E: operator delete(void*) (in /home/blabla/projects/test proj)
==4442==    by 0x804E1E6: __gnu_cxx::new_allocator<std::_Rb_tree_node<std::pair<std::string const, Order*> > >::deallocate(std::_Rb_tree_node<std::pair<std::string const, Order*> >*, unsigned int) (new_allocator.h:110)
==4442==    by 0x804DC59: std::_Rb_tree<std::string, std::pair<std::string const, Order*>, std::_Select1st<std::pair<std::string const, Order*> >, std::less<std::string>, std::allocator<std::pair<std::string const, Order*> > >::_M_put_node(std::_Rb_tree_node<std::pair<std::string const, Order*> >*) (stl_tree.h:374)
==4442==    by 0x804D2D7: std::_Rb_tree<std::string, std::pair<std::string const, Order*>, std::_Select1st<std::pair<std::string const, Order*> >, std::less<std::string>, std::allocator<std::pair<std::string const, Order*> > >::_M_destroy_node(std::_Rb_tree_node<std::pair<std::string const, Order*> >*) (stl_tree.h:422)
==4442==    by 0x804D3BB: std::_Rb_tree<std::string, std::pair<std::string const, Order*>, std::_Select1st<std::pair<std::string const, Order*> >, std::less<std::string>, std::allocator<std::pair<std::string const, Order*> > >::_M_erase_aux(std::_Rb_tree_const_iterator<std::pair<std::string const, Order*> >) (stl_tree.h:1746)
==4442==    by 0x804CB9A: std::_Rb_tree<std::string, std::pair<std::string const, Order*>, std::_Select1st<std::pair<std::string const, Order*> >, std::less<std::string>, std::allocator<std::pair<std::string const, Order*> > >::erase[abi:cxx11](std::_Rb_tree_iterator<std::pair<std::string const, Order*> >) (stl_tree.h:820)
==4442==    by 0x804C678: std::map<std::string, Order*, std::less<std::string>, std::allocator<std::pair<std::string const, Order*> > >::erase[abi:cxx11](std::_Rb_tree_iterator<std::pair<std::string const, Order*> >) (stl_map.h:697)
==4442==    by 0x804B96F: Play::~Play() (Play.cpp:50)
==4442==    by 0x80501AF: main (main.cpp:121)
==4442== 
==4442== Invalid read of size 4
==4442==    at 0x806EC4B: std::_Rb_tree_increment(std::_Rb_tree_node_base*) (in /home/blabla/projects/test proj)
==4442==    by 0x804C634: std::_Rb_tree_iterator<std::pair<std::string const, Order*> >::operator++(int) (stl_tree.h:197)
==4442==    by 0x804B98C: Play::~Play() (Play.cpp:46)
==4442==    by 0x80501AF: main (main.cpp:121)
==4442==  Address 0x421c5bc is 4 bytes inside a block of size 24 free'd
==4442==    at 0x402B3D8: free (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==4442==    by 0x8050D4E: operator delete(void*) (in /home/blabla/projects/test proj)
==4442==    by 0x804E1E6: __gnu_cxx::new_allocator<std::_Rb_tree_node<std::pair<std::string const, Order*> > >::deallocate(std::_Rb_tree_node<std::pair<std::string const, Order*> >*, unsigned int) (new_allocator.h:110)
==4442==    by 0x804DC59: std::_Rb_tree<std::string, std::pair<std::string const, Order*>, std::_Select1st<std::pair<std::string const, Order*> >, std::less<std::string>, std::allocator<std::pair<std::string const, Order*> > >::_M_put_node(std::_Rb_tree_node<std::pair<std::string const, Order*> >*) (stl_tree.h:374)
==4442==    by 0x804D2D7: std::_Rb_tree<std::string, std::pair<std::string const, Order*>, std::_Select1st<std::pair<std::string const, Order*> >, std::less<std::string>, std::allocator<std::pair<std::string const, Order*> > >::_M_destroy_node(std::_Rb_tree_node<std::pair<std::string const, Order*> >*) (stl_tree.h:422)
==4442==    by 0x804D3BB: std::_Rb_tree<std::string, std::pair<std::string const, Order*>, std::_Select1st<std::pair<std::string const, Order*> >, std::less<std::string>, std::allocator<std::pair<std::string const, Order*> > >::_M_erase_aux(std::_Rb_tree_const_iterator<std::pair<std::string const, Order*> >) (stl_tree.h:1746)
==4442==    by 0x804CB9A: std::_Rb_tree<std::string, std::pair<std::string const, Order*>, std::_Select1st<std::pair<std::string const, Order*> >, std::less<std::string>, std::allocator<std::pair<std::string const, Order*> > >::erase[abi:cxx11](std::_Rb_tree_iterator<std::pair<std::string const, Order*> >) (stl_tree.h:820)
==4442==    by 0x804C678: std::map<std::string, Order*, std::less<std::string>, std::allocator<std::pair<std::string const, Order*> > >::erase[abi:cxx11](std::_Rb_tree_iterator<std::pair<std::string const, Order*> >) (stl_map.h:697)
==4442==    by 0x804B96F: Play::~Play() (Play.cpp:50)
==4442==    by 0x80501AF: main (main.cpp:121)
==4442== 
==4442== 
==4442== HEAP SUMMARY:
==4442==     in use at exit: 0 bytes in 0 blocks
==4442==   total heap usage: 34 allocs, 34 frees, 580 bytes allocated
==4442== 
==4442== All heap blocks were freed -- no leaks are possible
==4442== 
==4442== For counts of detected and suppressed errors, rerun with: -v
==4442== ERROR SUMMARY: 11 errors from 2 contexts (suppressed: 0 from 0)

And the place where I'm facing this problem is when freeing the allocated memory in Destructor

std::map<std::string, Order*>::iterator order_itr;
for(ord_itr = order_.begin(); ord_itr != order_.end(); ord_itr++)
{
  //if(ord_itr->second != nullptr)
    delete ord_itr->second;
  order_.erase(ord_itr);
}

From the above iterator you can see with what kind of std::map I'm dealing with. As you can see I even tried to check if it's a null pointer not to free it(what makes no sense, because all of them should get allocated)

And for the end, this is my Constructor where I allocate the memory

order_["test1"] = new Test1Order();
order_["test2"] = new Test2Order();
order_["test3"] = new Test3Order();
order_["test4"] = new Test4Order();
order_["test5"] = new Test5Order();
order_["test6"] = new Test6Order();
order_["test7"] = new Test7Order();

Thanks

C++ thread: how to send message to other long-live thread?

I have a server listening to some port, and I create several detached threads.

Not only the server it self will run forever, but also the detached threads will run forever.

//pseudocode
void t1_func()
{
   for(;;)
   {
     if(notified from server)
         dosomething();
   }
}
thread t1(t1_func);
thread t2(...);
for(;;)
{
  // read from accepted socket
  string msg = socket.read_some(...);
  //notify thread 1 and thread 2;
}

Since I am new to multithreading, I don't know how to implement such nofity in server, and check the nofity in detached threads.

Any helpful tips will be appreciated.

C++11: How to determine (virtual) inheritance traits?

More specifically, is it possible in C++11 (or later) to write compile-time type traits for a given type T to determine

  1. whether T is abstract, i.e. has any pure virtual methods?
  2. whether T is a final class?
  3. whether a given member F of T (including T's destructor) can be overridden, i.e. can a subclass S of T declare S::F with override?

How can I get input edges of a given vertex on a directed graph?

I have a directed graph and I want to fetch the parent of a given vertex.

Say I have the graph 1 -> 2 -> 3, I hold the vertex 2 and I want to get vertex 1.

My vertex and graph definitions:

struct TreeVertex   {  int id = -1;  };

typedef boost::adjacency_list<
    boost::vecS,
    boost::vecS,
    boost::directedS,
    TreeVertex
    > tree_t;

An MVCE showing what I want to achieve (see online here):

int main() {
    tree_t tree;
    auto v1 = boost::add_vertex( tree );    
    auto v2 = boost::add_vertex( tree );    
    auto v3 = boost::add_vertex( tree );    
    boost::add_edge( v1, v2, tree );
    boost::add_edge( v2, v3, tree );

// attempt to get the input edge of v2
    auto pair_it_edge = boost::in_edges( v2, tree ); // FAILS TO BUILD  
    auto v = boost::source( *pair_it_edge.first ); // should be v1
}

Another answer suggests transforming the graph into a BidirectionalGraph but I need to keep it directed.

Question: Is this possible ? How can I get the incoming edge of v2, so that I can extract v1 ?

What is the difference between initializing with = and initializing with {}?

You can initialize a variable using = . For example:

int a = 1000;

C++ 11 introduced an extra notation {} . For example:

int a {1000};

According to Programming: Principles and Practices by Bjarne Stroustrup:

C++11 introduced an initialization notation that outlaws narrowing conversions.

I wanted to check out this cool feature. And I typed a piece of code twice:

#include "std_lib_facilities.h"     |     #include "std_lib_facilities.h" 
                                    |
int main()                          |     int main()
                                    |
{                                   |     {
    int x = 254;                    |         int x {254};
    char y = x;                     |         char y {x};
    int z = y;                      |         int z {y};
                                    |
    cout << "x = " << x << '\n'     |         cout << "x = " << x << '\n'
         << "y = " << y << '\n'     |              << "y = " << y << '\n'
         << "z = " << z << '\n';    |              << "z = " << z << '\n';
                                    |
}                                   |     }

The code on the left uses = whereas the code on the right uses {}

But the code on the right hand side loses some information even after using {}. Thus the output is same in both pieces of code:

x = 254

y = ■

z = -2

So, what's the difference between initializing with = and initializing with {} ?

Correct way to implement Singleton in Cocos2Dx

Currently I'm using this approach:

class Singleton {
public:
  static Singleton &getInstance()   {
    static Singleton *instance = new Singleton();
    return *instance;
  }
void getData();

private:
  Singleton() {}
};

In this way I can use a method from Singleton writing:

Singleton::getInstance.getData();

And this seems the right way reading a lot of tutorials for C++11. But reading through cocos Director singleton code (also FileUtils etc..), I have seen that Cocos uses this other approach:

class Singleton {
public:
  static Singleton *getInstance()   {
    instance = new Singleton();
    return instance;
  }
void getData();

private:
  Singleton() {}
  static Singleton *instance;
};

With this approach I have to write:

Singleton::getInstance->getData();

Because of the pointer *getInstance instead of reference &getInstance.

I think the difference is big, but I don't know if one way is correct and the other don't.

Please help me to sorting out this concept.

cannot convert ‘void (myClass::*)() to void (*)()

So, I know this question exists in so many places. But none of the examples helped me solve my issue.

I'm trying to create a method pointer (within a class), so it will address one of several methods of the class according to specific conditions.

I tried, unsuccessfully to use a static function (guess I misunderstood the instructions how to do so...).

here is the header file:

class myClass
{
public:
    myClass(int value);

    void methodA(const string &msg);
    void methodB(const string &msg);

    void (*send_msg)(const string &msg);
};

and the cpp:

myClass::myClass(int value){
    if(value > 0){
        send_msg = &methodA
    }
    else{
        send_msg = &methodB
    }
}

and the errors, as some of you already know:

error: ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function. Say ‘&myClass::methodA’ [-fpermissive]

error: cannot convert ‘void (myClass::)(const string&) {aka void (myClass::)(const std::basic_string&)}’ to ‘void ()(const string&) {aka void ()(const std::basic_string&)}’ in assignment

any help will be much appreciated.

Why would the param_type constructor be explicit for a random distribution?

I'm trying to compile this program (see it live here):

int main() {
  std::random_device engine;
  std::uniform_int_distribution<size_t> dis;
  std::cout << dis(engine, {0, 5}) << std::endl;
}

But it fails with the error message:

error: converting to 'const std::uniform_int_distribution<long unsigned int>::param_type' from initializer list would use explicit constructor 'std::uniform_int_distribution<_IntType>::param_type::param_type(_IntType, _IntType) [with _IntType = long unsigned int]'
   std::cout << dis(engine, {0, 5}) << std::endl;

Obviously, it is the explicit constructor of param_type that prevents us from doing this. But why specifying it as explicit in the first place? It's verbose and silly if one has to write

std::cout << dis(engine, decltype(dis)::param_type(0, 5)) << std::endl;

Any explanations on this? And also, how could I achieve what I want in a succinct and elegant way, given that the param_type constructor is explicit in the standard? Note that, in practice, the range may be different each time I invoke dis. So, supplying a range at the construction time of dis does not help.

Calling a class member function from another class member function in C++

Here is a code in which I called a class member function using another class member function. The basic purpose is to accept 3 numbers from the user and arrange them in the ascending order. While I haven't come up with a way to code the ascending order part, I decided to do comparison of each successive number in the sequence first and then do the swapping if a number occurs greater than the other. I thought it would be cool to call a class member function from another class member function, but unfortunately, that part ain't working out. What should I do?

/*Whats wrong with the swap function here?*/    
// i think there is some logical fallacy in this code. Please point out?
#include<iostream>
using namespace std;

class Trial
{
private:
int roll[10];
int i,m,n,temp;

public:

void intake()
{
std::cout<<"\n Enter any number sequence "<<"\n";
for(i=1;i<=3;i++)
{
 std::cin>>roll[i];
}
}

void ascend()
{
for(i=1;i<=3;i++)
 {
  if(roll[i]>roll[i+1])
   {
    swap(roll[i],roll[i+1]);// Thought it would be cool to call another
    // member function from a member function
   }
 }              // Take two counters i and j
}

void swap(int m, int n)  // Write simple swap function here.
{
//int m,n,temp; // Think this member function ain't working
temp=m;
m=n;
n=temp;
}

};

int main()
{
Trial ob1;
ob1.intake();
ob1.ascend();
return 0;
}

How to Compile boost with GCC 5 using old ABI?

I have downloaded a library that was compiled with a gcc 4.8 before the ABI change in GCC.

On my laptop (latest kubuntu) I have GCC 5.2. And When I installed boost, it seems that it used the new ABI but then I get the following link errors

undefined symbol.....__cxx11....

How can I install boost using old ABI with GCC5 ?

Error: multiple definition of `fprint' - while using SDL_ttf

I have a custom library that utilises this code (http://ift.tt/1RKrd13). The linked code was written for Visual Studio; I am using CodeLite on Windows.

Its has a SpriteFont.cpp that uses fprintf.

The static library that has SpriteFont as part of it compiles fine on its own and produces a *.a quite happily.

However when I use SpriteFont via other code, I get a linker error (if I am not mistaken):

D:/Coding/TDM-GCC-32/bin/g++.exe -o ./Debug/tmp @"tmp.txt" -L. -L../deps/lib/ -L../bengine/lib/  -lbengine -lSDL2_ttf -lSDL2main -lSDL2 -lopengl32 -lglew32
D:/Coding/TDM-GCC-32/bin/../lib/gcc/mingw32/5.1.0/../../../libmsvcrt.a(dsnos00619.o):(.text+0x0): multiple definition of `fprintf'
../bengine/lib//libbengine.a(SpriteFont.cpp.o):D:/Coding/TDM-GCC-32/include/stdio.h:243: first defined here

I have read all over and found some similar situations but nothing that I have managed to use to resolve this.

It sounds like there is an issue with the way TDM-GCC redefines fprint in its' stdio.h, but I can't see how. Upon further examination, I believe the problem may lie with SDL_ttf, which is used by SpriteFont.

Also, I have tried using other functions from stdio.h and they compile fine; problem only seems to be fprintf

I have tried to create a barebones program to illustrate the problem. Hope it helps. Hopefully the fact it is a CodeLite project won't be a source of irritation. If I can provide more info or code please ask.