lundi 29 février 2016

Move std::unique_ptr to new position inside std::vector

I have std::vector of std::unique_ptr-s. How to move one element to another place without changing relative order of other elements?

How much of C++11 is usable in Windows Kernel

The latest WDK is delivered to be used with Visual Studio 15, which supports C++11.

However, I have not seen documentation about how much of the functionality is usable.

Obviously, I wouldn't use std::thread and std::mutex, but less clearly, is the magic statics.

Class * function()
{
     static Class myInstance;

     return &myInstance;
}

That is now thread-safe in user mode, but it is unclear whether this construction may work in kernel.

More concerning, is pre C++11 code would have been acceptable in kernel (assuming destructor was trivial).

C++ void method getting an error for being void

I am writing a C++ program that will take 2 lists, L and P, and am trying to write a method that will print the elements in L that are in positions specified in P. Here is the code:

#include <iostream>
#include <list>
#include <iterator>
#include <stdlib.h>
using namespace std;

void printLots( list L, list P );

int main()
{
  list< int > numList = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000};
  list< int > indexList = {2, 4, 6, 8, 10};

  printLots( numList, indexList );

  return 0;
}

void printLots( list L, list P )
{
  int count;
  list::iterator itrIndex;
  list::iterator itrValue;

  for( itrIndex = P.begin(); itrIndex != P.end(); ++itrIndex )
  {
    count = 1;
    for( itrValue = L.begin(); itrValue != L.end(); ++itrValue )
    {
      if( count == *itrIndex )
      {
    cout << "Value in list L at index " << *itrIndex << " = " << *itrValue << endl;
      }
      ++count;
    }
  }
}

For some reason when I try to compile, I am getting an error saying: "error: variable or field 'printLots' declared void void printLots( list L, list P ) I mean, yes the function is void but thats because it is supposed to be. This function doesn't return anything so I have no clue why its giving me an error for this function being void. I have no clue how to fix this. Any help?

Disable file name box in QFileDialog

I used a QFileDialog to open a browser. Here is my code:

QString filePath = QFileDialog::getSaveFileName(this,
                                               "Export Xml", "PluginPythonQt",
                                                "Xml files (*.xml)");

When excute it will show a dialog like this:

enter image description here

I want to disable the "File name:" box in the picture or prevent user to enter a new name. How can i do that ? Thanks.

How can I optimize this code to print in this format?

I want to print a linked list like this:

0       1       2       3       4
12      24      36      85      48

My current code is

void LinkedList::printList()
{
    curr = head; //store head in curr to irerate
    int count = 0; //counter to help uer manipulate list
    while (curr != NULL) //traverse whole list
    {
        cout << count++ <<"\t"; //print index
        curr = curr->next; //move to next 
    }
    curr = head; //make current head again
    cout << endl;//go to next line
    while (curr != NULL) //traverse whole list
    {
        cout << curr->data << "\t"; //print data
        curr = curr->next; //move to next 
    }
    cout << endl;
}

I am pretty sure there's another way to do this is a simpler and faster way. I want to reduce the redundancy on this code.

I am showing the counter to help user add or delete numbers.

Check C++ class publicly inherits from template class with anonymous parameter

Similar to this question, how do I test that a class Impl publicly inherits from a template class BaseTempl (i.e. class Impl : public BaseTempl< ... >{ ... };), without specifying the template arguments?

Different from the aforementioned question, however, I would like the test to still compile (and return false) if the inheritance is not public.

Ideally, the code would allow me to do something like this:

class alpha : public BaseTempl< int >{};

class bravo : BaseTempl< int >{};

class charlie{};

class delta : public BaseTempl< int >, public charlie {};

class echo : public delta {};

int main(){
    publicly_inherits_from < alpha,   BaseTempl > (); // true
    publicly_inherits_from < bravo,   BaseTempl > (); // false
    publicly_inherits_from < charlie, BaseTempl > (); // false
    publicly_inherits_from < delta,   BaseTempl > (); // true
    publicly_inherits_from < echo,    BaseTempl > (); // true
}

The answer from the linked question gives the following error when I attempt to compile the above code:

error: ‘BaseTempl<int>’ is an inaccessible base of ‘bravo’

Reason for `std::bind` being more effective than a lambda

I have this piece of code:

float volume;

// version #1: (bind method)
auto times_vol = std::bind(std::multiplies<float>(),
                           volume, std::placeholders::_1);

// version #2: (lambda method)
auto times_vol = [volume] (float sample) -> float {
    return volume*sample;
};

The times_vol is a function that returns volume*x, where x is its argument. It will be used in a std::transform later.

I have measured some times for these two options. My program runs a lot of std::transform's and std::copy's, making a total of 51200 calls to times_vol. When times_vol is first version (the bind version), the times for the program are usually between 50 ms and 80 ms, with a mean of 76 ms. When I use the second version (lambda version), the times are usually between 40 ms and 60 ms, with a mean of 59 ms. (sometimes it takes 100+ ms).

Anyway, I'm pretty confident that the bind version is better. Are there any reasons for this?

Check a type trait of every class in a nested mixin

I have a collection of mixins that each have a type trait defined. I want to check the value of the boolean AND of each of this trait for each of these mixins. For example, if I have a Mixin1<Mixin2<T> > and Mixin1<T> has is_nice == true while Mixin2<T> has is_nice == false, then the trait of the nested mixins should evaluate to "false".

This line:

static const bool value = is_nice_all< Outer<Inner> >::value && is_nice_all<Inner>::value;

is causing an infinite recursion (because I'm calling is_nice_all on exactly the same template argument that it was called with in the first half of the &&, but I think it shows what I'm trying to accomplish.

#include <iostream>

// A type trait to determine if a type is nice
template <typename T>
struct is_nice
{
  static const bool value = false;
};

// Base case
template <class T>
struct is_nice_all {
    static_assert(is_nice<typename T::FieldsType>::value, "Not nice!");

    static const bool value = is_nice<typename T::FieldsType>::value;
};

template <template <class> class Outer, class Inner>
struct is_nice_all<Outer<Inner> > {
    // AND the result of the niceness of the current mixin and the next mixin, recursively
    static const bool value = is_nice_all< Outer<Inner> >::value && is_nice_all<Inner>::value; // Compiler error - template instantiation depth exceeds maximum
};

// For a base case
class BaseClass
{
public:
    using FieldsType = BaseClass;
};

// For a base case
template <>
struct is_nice<BaseClass>
{
  static const bool value = true;
};

class Mixin1_Fields
{
public:
    int property1;
};

template<class MixinBase>
class Mixin1 : public MixinBase, public Mixin1_Fields
{
public:
    using FieldsType = Mixin1_Fields;
};

template <>
struct is_nice<Mixin1_Fields>
{
  static const bool value = true;
};

class Mixin2_Fields
{
public:
    int property2;
};

template<class MixinBase>
class Mixin2 : public MixinBase, public Mixin2_Fields
{
public:

    using FieldsType = Mixin2_Fields;
};

template <>
struct is_nice<Mixin2_Fields>
{
  static const bool value = true;
};

int main()
{
    std::cout << is_nice_all<Mixin1<Mixin2<BaseClass> > >::value << std::endl;
    return 0;
}

Is there a way to achieve this recursive AND operation on these types? Is there a name for this "do something to every type in a nested template type" pattern?

Performance of std::copy of portion of std::vector

I want to copy part of a vector to itself, e.g.

size_t offset; /* some offset */
std::vector<T> a = { /* blah blah blah */};
std::copy(a.begin() + offset, a.begin() + (offset*2), a.begin());

However, I'm concerned about the performance of this approach. I'd like to have this boil down to a single memmove (or equivalent) when the types in question allow it, but still behave as one would expect when given a non-trivially-copyable type.

When the template type T is trivially copyable (in particular int64_t if it matters), does this result in one memmove of length sizeof(T) * offset, or offset distinct memmoves of length sizeof(T)? I assume the later would give noticeably worse performance because it requires many separate memory reads. Or should I just assume that caching will make the performance in these situations effectively equivalent for relatively small offsets (<100)?

In cases where the template type T is not trivially copyable, is it guaranteed to result in offset distinct calls to the copy assignment operator T::operator=, or will something stranger happen?

If std::copy doesn't yield the result I'm looking for, is there some alternative approach that would satisfy my performance constraints without just writing template-specializations of the copy code for all the types in question?

std::stod is not a member of std

I can't compile the following code

auto test = 42.02;
double right = std::stod(stck.top());

I'm using Code::Blocks and activated the build option to follow c++11 standard. The compiler does not complain about the auto declaration and compiles, when I put the line below in comments.

I included the string header. I'm not using a namespace.

I have no idea why this does not compile. Please help me!

My compiler is Standard MinGW GCC 4.9

C++ Array of Objects Non-member function

I have a class that has a member function getOffset(). I have some non member functions for operating on arrays of my class.

myClass arr[10] = {1,2,3};

doCalc(arr);, doCalc2(arr);, doCalc3(arr);

The first thing I do in each "doCalc" function is loop over the array and for each object I call getOffset() and I bitwise or them together.

uint8_t offset = arr[0].getOffset();
for (int i = 1; i < length; i++) {
  offset |= arr[i].getOffset();
}

Is there a way I can calculate the offset for the array of objects and store it at initialization? Every "doCalc" function recalculates the offset every time and I really only need to do it once upon initializing the array. Thank you.

MinGW boost random_device compile error

I need some random numbers for a simulation and are experimenting with the C++ 11 random library using MinGW Distro from nuwen.net.

As have been discussed in several other threads, e.g. why do I get same sequence for everyrun with std::random_device with mingw gcc4.8.1, random_device do not generate a random seed, i.e. the code below, compiled with GCC, generates the same sequence of numbers for every run.

// test4.cpp
// MinGW Distro - nuwen.net
// Compile with g++ -Wall -std=c++14 test4.cpp -o test4

#include <iostream>
#include <random>

using namespace std;

int main(){
    random_device rd;
    mt19937 mt(rd());
    uniform_int_distribution<int> dist(0,99);
    for (int i = 0; i< 16; ++i){
        cout<<dist(mt)<<" ";
        }
        cout <<endl;
}

Run 1: 56 72 34 91 0 59 87 51 95 97 16 66 31 52 70 78

Run 2: 56 72 34 91 0 59 87 51 95 97 16 66 31 52 70 78

To solve this problem it has been suggested to use the boost library, and the code would then look something like below, adopted from How do I use boost::random_device to generate a cryptographically secure 64 bit integer? and from A way change the seed of boost::random in every different program run,

// test5.cpp
// MinGW Distro - nuwen.net
// Compile with g++ -Wall -std=c++14 test5.cpp -o test5

#include <boost/random.hpp>
#include <boost/random/random_device.hpp>
#include <iostream>
#include <random>

using namespace std;

int main(){
    boost::random_device rd;
    mt19937 mt(rd());
    uniform_int_distribution<int> dist(0,99);
    for (int i = 0; i< 16; ++i){
        cout<<dist(mt)<<" ";
        }
        cout <<endl;
}

But this code wont compile, gives the error “undefined reference to ‘boost::random::random_device::random_device()”. Note that both random.hpp and radndom_device.hpp are available in the include directory. Can anyone suggest what is wrong with the code, or with the compiling?

Sending jobs to a std::thread

I am quite new to std::thread and I quickly realized that creating them is quite costly at least on my computer running W7. So I decided to create my threads and send jobs to it using that piece of sample code: http://ift.tt/1olYwuW

My code runs well no crash however I didn't notice much performance increase so I measured the difference between the time the job finishes and the time the job is detected finished by the main thread ( see WaitUntilJobFinished() ) I noticed that on some rare occasions the time difference was over 2 milliseconds

Does anyone see anything wrong with the code?

Code:

class CJobParameters
{
public:
};

typedef void (*CJobFunc)( const CJobParameters * );

class CThread
{   
public:
    void Start();
    void WaitUntilJobDone();
    void StartJob( CJobFunc inJobFunc, const CJobParameters * inJobParameters );

    std::thread m_stdThread;

    CJobFunc                m_jobFunc       = nullptr;
    const CJobParameters *  m_jobParameters = nullptr;
    //std::atomic<bool>     m_jobDone       = true;
    std::mutex              m_mutex;
    std::condition_variable m_cv;

    __int64 m_jobDoneAt = 0;
    __int64 m_threadJoinedAt = 0;
    __int64 m_lostTime = 0;
};

class CThreads
{
public:
    static void Start();
    static CThread  threadArray[ JOB_COUNT ];
};


void ThreadMain( CThread * inThread )
{
    while ( true )
    {
        std::unique_lock<std::mutex> lk( inThread->m_mutex );
        inThread->m_cv.wait(lk, [ inThread ]{return inThread->m_jobParameters != nullptr;});
        if ( inThread->m_jobFunc )
        {
            (*inThread->m_jobFunc)( inThread->m_jobParameters );
            inThread->m_jobFunc = nullptr;
            inThread->m_jobParameters = nullptr;
            inThread->m_jobDoneAt = COSToolbox::QuerySystemTime2();
        }
        lk.unlock();
        inThread->m_cv.notify_one();
        std::this_thread::sleep_for( std::chrono::nanoseconds(0) );
    }
}

void CThread::StartJob( CJobFunc inJobFunc, const CJobParameters * inJobParameters )
{
    std::lock_guard<std::mutex> lk( m_mutex );
    m_jobFunc           = inJobFunc;
    m_jobParameters     = inJobParameters;
    m_cv.notify_one();
}

void CThread::Start()
{
    m_stdThread = std::thread( ThreadMain, this );
}

void CThread::WaitUntilJobDone()
{
    std::unique_lock<std::mutex> lk( m_mutex );
    m_cv.wait(lk, [ this ]{return this->m_jobParameters == nullptr;});

    m_threadJoinedAt = COSToolbox::QuerySystemTime2();
    m_lostTime = m_threadJoinedAt - m_jobDoneAt;
    LOG_INFO( "Thread joined with %f ms lost", (Float32)m_lostTime / 1000 );
}


CThread CThreads::threadArray[ JOB_COUNT ];
void CThreads::Start()
{
    for ( Int32 i = 0; i < JOB_COUNT; ++i )
    {
        threadArray[i].Start();
    }
}

void MyJobFunc( const CJobParameters  * jobParameters )
{
    // do job here
}
void main()
{
    CThreads::Start();
    CJobParameters jobParametersArray[ JOB_COUNT ];
    for ( Int32 i = 0; i < JOB_COUNT; ++i )
    {
        CThread & thread = CThreads::threadArray[ i ];
        CJobParameters& jobParameters = jobParametersArray[ i ];
        jobParameters.m_ // Fill in params
        thread.StartJob( &MyJobFunc, &jobParameters );
    }
}

Recursive(?) function wrapper based on std::function<>

I want to achieve code looking similar to that

using ProcessCallback = std::function<ProcessCallback (const std::vector<char>&)>

// ...

ProcessCallback callback;
// initialize callback somehow...

while (/* condition */)    {
    auto callback_successor = callback (data);
    if (callback_successor)   {
       callback = std::move (callback_successor);
    }
}

In general I want to have callable callback object (function pointer, whatever) that will process some data and has possibly of replacing itself for successive calls.

The error is obvious - quasi-recursive declaration in first line is invalid, because I try to declare std::function<>-based type using undeclared ProcessCallback.

How can I fix aforementioned code or how can I achieve desired functionality with other construction? Abstract functional class for processing it's not the solution - I don't want to write new class inheriting from the abstract class for each processing function.

I want to stick to pure C++ (no Boos etc.), but I'm not limited to specific C++ version.

Conver BCD Strings to Decimal

I am looking for better ways to optimize this function for better performance, speed its targeted towards embedded device. i welcome any pointers, suggestion thanks

function converts string BCD to Decimal

int ConvertBCDToDecimal(const std::string& str, int splitLength)
{
    int NumSubstrings = str.length() / splitLength;
    std::vector<std::string> ret;
    int newvalue;

    for (auto i = 0; i < NumSubstrings; i++)
    {
        ret.push_back(str.substr(i * splitLength, splitLength));
    }

    // If there are leftover characters, create a shorter item at the end.
    if (str.length() % splitLength != 0)
    {
        ret.push_back(str.substr(splitLength * NumSubstrings));
    }

    string temp;

    for (int i=0; i<(int)ret.size(); i++)
     {
         temp +=ReverseBCDFormat(ret[i]);
     }

    return newvalue =std::stoi(temp);

}

string ReverseBCDFormat(string num)
{

    if( num == "0000")
    {
        return "0";
    }
    else if( num == "0001")
    {
        return "1";
    }
    else if( num == "0010")
    {
        return "2";
    }
    else if( num == "0011")
    {
        return "3";
    }
    else if( num == "0100")
    {
        return "4";
    }
    else if( num == "0101")
    {
        return "5";
    }
    else if( num == "0110")
    {
        return "6";
    }
    else if( num == "0111")
    {
        return "7";
    }
    else if( num == "1000")
    {
        return "8";
    }
    else if( num == "1001")
    {
        return "9";
    }
    else
    {
        return "0";

    }

}

How can I correctly implement this operation with averaging unsigned chars - C++

Consider the following, seemingly simple, problem, that I've come across in solving assignments in CV involving masks and implementing AA in ray tracing.

An color in the RGB format has three channels, each channel represented by an unsigned char, hence 0 <= channel value <= 255. For reasons of symmetry, let's consider a single channel. I want to sum up channel values over a certain set of points, then average and round that (not just truncate) and store back into an unsigned char. Note that in all the problems, the resulting averaged value is guaranteed to be in the range [0, 255], it's an invariant of the algorithm.

This looks like an easy task, but I'm concerned with the following:

p.1. The most important: the type choice, see pseudocode below for which types I need. More precisely, I'm getting a narrowing conversion error, which turns into an error with -pedantic-errors set, and I don't want to simply wave it away.

p.2. The idea of going from a wider type that can accumulate many uchar's, back to the uchar type. I'm confident that the algorithm is guaranteed to produce a value in the uchar range, but is it enough? Should I worry about this?

Pseudocode (cv::Vec3b is a fixed size 3x1 array of unsigned char in OpenCV which iI use for image storing and output):

// this returns a value in the range [0, 255]
cv::Vec3b processing_func(const point&) { ... }

accum_type acc_r = 0, acc_g = 0 , acc_b = 0;
for (point p: point_set) {
    const cv::Vec3b color = processing_func(p);
    acc_r += color[0]; acc_g += color[1]; acc_b += color[2];
}
cv::Vec3b result_color{roundf(acc_r / (floating_type)set_size),
                       roundf(acc_g / (floating_type)set_size),
                       roundf(acc_b / (floating_type)set_size)};
// hello narrowing conversion ^^^

Refer to p.1, what should the accum_type and floating_type be (the latter required to divide correctly without truncation), or would you maybe code it differently?

Edit after the first comment: set_size is an integer above 0, it can be hardcoded if required, but in general is bound to change. It's e.g. AA factor, squared; or mask size, and so on.

Error in constructor receiving two parameters by value

Sometimes I find very useful, for simplicity and efficiency, using this type of iterator:

// Chunk 1
    template <class Itor1, class Itor2 = Itor1>
class Pair_Iterator
{
  Itor1 it1;
  Itor2 it2;

public:

  Pair_Iterator(Itor1 i1, Itor2 i2) : it1(i1), it2(i2) {}

  bool has_curr() const { return it1.has_curr() and it2.has_curr(); }

  auto get_curr() const
  {
    return std::make_pair(it1.get_curr(), it2.get_curr());
  }

  void next()
  {
    it1.next();
    it2.next();
  }
};

The idea is to traverse simultaneously two containers, which may be of different types, through its iterators.

Now, for a reason I do not manage not understand, the next test does not compile:

// previous chunk could be included here
struct It1
{
  It1() {}
  bool has_curr() const { return true; }
  int get_curr() const { return 1; }
  void next() {}
};

int main()
{
  for (Pair_Iterator<It1> it(It1(), It1()); it.has_curr(); it.next())
    ;
}

clang compiler (version 3.8) says:

error: member reference base type 'Pair_Iterator<It1> (It1 (*)(), It1 (*)())'
      is not a structure or union
  for (Pair_Iterator<It1> it(It1(), It1()); it.has_curr(); it.next())
                                            ~~^~~~~~~~~
it.C:57:62: error: member reference base type 'Pair_Iterator<It1> (It1 (*)(), It1 (*)())'
      is not a structure or union
  for (Pair_Iterator<It1> it(It1(), It1()); it.has_curr(); it.next())
                                                       ~~^~~~~

And gnu compiler (version 5.3) says:

error: request for member ‘has_curr’ in ‘it’, which is of non-class type ‘Pair_Iterator<It1>(It1 (*)(), It1 (*)())’
   for (Pair_Iterator<It1> it(It1(), It1()); it.has_curr(); it.next())
                                                ^
it.C:57:63: error: request for member ‘next’ in ‘it’, which is of non-class type ‘Pair_Iterator<It1>(It1 (*)(), It1 (*)())’
   for (Pair_Iterator<It1> it(It1(), It1()); it.has_curr(); it.next())

However, if I change the Pair_Iterator instantiation by:

It1 it1;
for (Pair_Iterator<It1> it(it1, It1()); it.has_curr(); it.next())

then everything compiles perfectly.

So my question would be:

  1. Why the first instantiation is invalid (I presume that because two compilers reject it)
  2. Is there any way to write Pair_Iterator so that the instantiation of interest passes?

variables pre-evaluation in loop range spliting

I would like to multithread a for loop but I have some variable inside my loop what need to know the previous state. Well it's not quite easy to explain.

Here is an exemple :

    double mu1 = 0, q1 = 0;
    double max_sigma = 0, max_val = 0;
    for( i = 0; i < N; i++ )
    {
        double p_i, q2, mu2, sigma;
        p_i = h[i]*scale;
        mu1 *= q1;
        q1 += p_i;
        q2 = 1. - q1;

        if(std::min(q1,q2) < FLT_EPSILON || std::max(q1,q2) > 1. -FLT_EPSILON )
            continue;

        mu1 = (mu1 + i*p_i)/q1;
        mu2 = (mu - q1*mu1)/q2;
        sigma = q1*q2*(mu1 - mu2)*(mu1 - mu2);
        if( sigma > max_sigma )
        {
            max_sigma = sigma;
            max_val = i;
        }
    }

scale is a double scalar value.

h is a std::vector<std::uint64_t>

If I split the range in sevral part for process any sub I can locally (in each thread) compute first p_i.

But I don't see how I could determine the value mu1.

So my question is : Is there any way to determine mu1 at the begining of a thread for a range B without prior of the result of mu1 what have been processed in a thread for a range A? If yes, how?

How to replace c-pointer with shared_ptr?

I am new to C++11 so please be nice.

Could you show me an easy example, how a shared_ptr can replace standard pointer? I also appreciate, an explanation if it does not make sense in that case.

e.g. Could you transform this code?

std::vector <CVariant*>liste;
liste.push_back( new CVariant( (unsigned int) 24, Parameter1", TYPE_UINT) );
std::cout << liste.at(0)->get<int>() <<"\n";
delete liste.at(0);

->

std::vector < std::shared_ptr<CVariant> >liste;

???

C++ runtime error with shared_ptr and builder pattern

I was studying c++ language with shared pointer and builder pattern.

I have written following code that is not working but I don't understand why it emits run-time error.

Could you tell me why it is not working well and how can I solve this problem to work well?

#include <iostream>
#include <memory>
#include <string>

using namespace std;

class Popup
{
public:
    Popup(int value, string str){
        this->v = value;
        this->str = str;
    }
    virtual void print() = 0;
    int v;
    string str;
};
typedef shared_ptr<Popup> PopupPtr;

class PopupA : public Popup
{
public:
    PopupA(int v, string str) : Popup(v, str) { }
    virtual void print() {
        cout << "PopupA" << endl;
    }
};
typedef shared_ptr<PopupA> PopupAPtr;

class PopupB : public Popup
{
public:
    PopupB(int v, string str) : Popup(v, str) { }
    virtual void print() {
        cout << "PopupB" << endl;
    }
};
typedef shared_ptr<PopupB> PopupBPtr;


class Builder
{
public:
    PopupPtr popupPtr;
    Builder() { };
    shared_ptr<Builder> init(int value, string str) {
        shared_ptr<Builder> builder;

        switch (value)
        {
        case 1:
            popupPtr = PopupAPtr(new PopupA(value, str));
            break;
        case 2:
            popupPtr = PopupBPtr(new PopupB(value, str));
            break;
        default:
            cout << "default error" << endl;
            break;
        }

        if (popupPtr) {
            builder = shared_ptr<Builder>(this);
        } 
        else {
            cout << "popup is null" << endl;
        }

        if (!builder) {
            cout << "builder is null" << endl;
        }
        return builder;
    }

    PopupPtr build()
    {
        if (!popupPtr) {
            cout << "popup is null" << endl;
        }
        return PopupPtr(popupPtr);
    }

};
typedef shared_ptr<Builder> BuilderPtr;

int main()
{
    BuilderPtr builderPtr = BuilderPtr(new Builder());

    PopupPtr popupPtr1 = builderPtr->init(1, "111111111111")->build();
    popupPtr1->print();

    PopupPtr popupPtr2 = builderPtr->init(2, "222222222222")->build();
    popupPtr2->print();
    return 0;
}

Thanks in advance for your answers and sorry for my poor english. If you don't understand my question please make a comment.

How can create an instance of class into an other class whithout invoking destructor method in c++

I try to instantiate my class A (its goal is to notify other classes observers by a result ) into class B and after adding the observers the class A call its destructor and delete these observers . What I want is to instantiate my class A into class B without invoking the destructor. I think about a handler class which will be singleton but nothing is clear in my mind. Please help me. I code with c++.

Why c++ parameters packing works differently with different compilers?

C++ parameters pack expansion is reversed by VS2015 compiler.

I have the next code:

#include <iostream>
#include <vector>


template <typename... T>
void f_Swallow(T &&...)
{
}

template <typename... T>
std::vector<int> f(T ...arg)
{
    std::vector<int> result;
    f_Swallow
    (
        [&]()
        {

            result.push_back(arg);
            return true;
        }
        ()...
    ) ;
    return result;
}


using namespace std;
int main()
{
    auto vec = f(1,2,3,4);

    for (size_t i = 0; i < vec.size(); ++i)
        cout << vec[i] << endl;
}

When I'm running this code in XCode (clang-700.1.81), I get the next result:

1
2
3
4

But the same code, running in VS2015 produces the next output:

4
3
2
1

Why are the packing parameters expanded differently depending on the compiler, and if there someway to fix it without checking the platform and compiler version? Doesn't the standard guarantee anything about expanding order? Thank you for help.

MSCV, constructor, destructor and NRVO behaviour

I was wondering if the NRVO was active on the project I was working on (which is Qt, using MSVC 2013 64 bit).

So I wrote this piece of code:

class foo
{
public:
    foo(){qDebug() << "foo::foo";}
    foo(const foo& c){(void)c;qDebug() << "foo::foo( const foo& )\n";}
    ~foo(){qDebug() << "foo::~foo";}
};
foo             bar()
{
    foo local_foo;
    return (local_foo);
}
void                    func()
{
    foo f = bar();
}

and it gave me the following output:

foo::foo

foo::~foo

Where the link I put above expects :

foo::foo()

foo::foo( const foo& )

foo::~foo()

foo::~foo()

But when I replace the bar call by

foo f = foo(bar())

then I get the same output that the links has.

So here's my question: why does "foo f = bar()" not call copy constructor? does it call the operator= instead, and before it is call, f is raw storage? (So why the link, which is from 2004, doesn't behave the same way)? So I must conclude NRVO isn't turned on, right?

Variadic Template for qobject_cast via parent()

gurus and template-experts, I need your help ...

I am currently looking for a solution on checking a QObject's parent hierarchy. I have a custom QDialog with the following hierarchy (parent to child):

QDockWidget
> CustomDockArea
  > QMainWindow
    > QDockWidget
      > CustomDialog

Within the CustomDialog class, I want to check if the hierarchy is correct, so I checked if this is accomplishable with a variadic template, for example:

assert(qobject_cast_parent<QDockWidget*, QMainWindow*, CustomDockArea*, QDockWidget*>(this));

and I have come up with something like this:

template <class T, class... Ts>
inline T qobject_cast_parent(QObject* root)
{
    if (root)
    {
        if (sizeof...(Ts) == 0)
        {
            return qobject_cast<T>(root->parent());
        }
        else
        {
            return qobject_cast_parent<Ts...>(root->parent());
        }
    }
    else
    {
        return nullptr;
    }
}

However, there a few problems: I need the last parameter of the parameter pack as being the return type of the function, in our example QDockWidget*. I could take the first parameter as being the return type, but this would make the template call a little bit cumbersome. However, even if that would be solved, I think there is still a problem with the way the parameter pack is "unrolled" and now I got a little bit unsure if my template-approach is even feasible for the original problem. Maybe you can give me some hints. Thanks in advance!!!

Tiled map Render Crashes. C++ & SDL2

I was trying to make program that renders basic tiled map really small only 6x8 and the tiles are 80x80. But when I built program and tried to launch it, it crashed at startup.

Here is my Source code:

#include <iostream>
#include <fstream>
#include <SDL.h>
#include <SDL_image.h>
#undef main
#pragma once

SDL_Window *window = NULL;
SDL_Renderer *renderTarget = NULL;

const int TILE_WIDTH = 80;
const int TILE_HEIGHT = 80;
const int TOTAL_TILES = 48;

const int LEVEL_WIDTH = 640;
const int LEVEL_HEIGHT = 480;


SDL_Texture *LoadTexture(std::string filePath, SDL_Renderer *renderTarget)
{
    SDL_Texture *texture = NULL;
    SDL_Surface *surface = IMG_Load(filePath.c_str());
    {
         texture = SDL_CreateTextureFromSurface(renderTarget, surface);
    }
    SDL_FreeSurface(surface);
    return texture;
}
class Tile
{
private:
    SDL_Texture *TileTexture;
    SDL_Rect TilePos;
    SDL_Rect Tile_TYPE;
public:
    Tile(int x, int y, int tileType);
    void Show(SDL_Renderer *renderTarget);
};
bool setTiles( Tile *tiles[] );

Tile::Tile(int x, int y, int tileType)
{
    TileTexture = LoadTexture("TileSheet.png", renderTarget);

    TilePos.x = x;
    TilePos.y = y;
    TilePos.w = TILE_WIDTH;
    TilePos.h = TILE_HEIGHT;

    Tile_TYPE.w = 80;
    Tile_TYPE.h = 80;

    if(tileType == 0)
    {
        Tile_TYPE.x = 0;
        Tile_TYPE.y = 80;
    }
    else if(tileType == 1)
    {
        Tile_TYPE.x = 0;
        Tile_TYPE.y = 0;
    }
}
void Tile::Show(SDL_Renderer *renderTarget)
{
    SDL_RenderCopy(renderTarget, TileTexture, &Tile_TYPE, &TilePos);
}
bool SetTiles( Tile *tiles [] )
{
    int x = 0, y = 0;

    std::ifstream map("Map.mcmp");

    {
        for(int i = 0; i < TOTAL_TILES; ++i )
        {
            int tileType = -1;

            map >> tileType;

            tiles[ i ] = new Tile( x, y, tileType );

            x += TILE_WIDTH;

            if( x >= LEVEL_WIDTH )
            {
                x = 0;
                y += TILE_HEIGHT;
            }
        }
    }
    map.close();
    return true;
}

int main(int argc, char *argv[])
{
    window = SDL_CreateWindow("tiledMap", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_SHOWN);
    renderTarget = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
    SDL_Texture *PlayerTexture = LoadTexture("Player.png", renderTarget);

    SDL_Rect PlayerPos;

    Tile* tileSet[ TOTAL_TILES ];

    PlayerPos.x = 0;
    PlayerPos.y = 0;
    PlayerPos.w = 30;
    PlayerPos.h = 30;

    SDL_Event ev;

    bool isRunning = true;

    while(isRunning)
    {
        while(SDL_PollEvent(&ev) != 0)
        {
           if(ev.type == SDL_QUIT)
                isRunning = false;
            else if(ev.type == SDL_KEYDOWN)
            {
                switch(ev.key.keysym.sym)
                {
                case SDLK_DOWN:
                    PlayerPos.y++;
                case SDLK_UP:
                    PlayerPos.y--;
                case SDLK_RIGHT:
                    PlayerPos.x++;
                case SDLK_LEFT:
                    PlayerPos.x--;
                }
            }
        }
        SDL_RenderClear(renderTarget);

        for( int i = 0; i < TOTAL_TILES; ++i )
        {
            tileSet[ i ]->Show( renderTarget );
        }

        SDL_RenderCopy(renderTarget, PlayerTexture, NULL, &PlayerPos);
        SDL_RenderPresent(renderTarget);

    }
    SDL_DestroyTexture(PlayerTexture);
    SDL_DestroyRenderer(renderTarget);
    SDL_DestroyWindow(window);

    return 0;
}

-TileSheet.png is 80x160 sprite

Please tell me how to fix this. thank you.

'AddMatVector' is not a member of 'caffe::MemoryDataLayer'

I am using the Caffe framework for Ubuntu 14.04 and I want to use caffemodel to classify.

At first,I convert the face database into lmdb format and I have trained the caffemodel(lenet_iter_10000.caffemodel).

Next, I try to use my caffemodel to classify.

I read the codefrom google caffe users and rewrite some of the content , but I have some errors.

'AddMatVector' is not a member of 'caffe::MemoryDataLayer'

I asked in some forums, but I did not receive a reply.

Could anyone help me?

If my description is not clear enough, I will make it clearly. Thank you.

Overloading augmented assignment in c++ (return type)

I am making an object that uses += operations. Should it return reference to *this or should it just return *this?

std smart ptrs mixed with raw pointers for Qt

I want to store some QObjects inside smart pointers but Qt classes take only raw pointers as arguments so I'm wondering what does the thing I've done... in class body I have:

QStateMachine states;
std::shared_ptr<QState> some_state = nullptr;

Later I do:

some_state = std::shared_ptr<QState>(new QState());
states.addState(&*some_state);

And how about using std::unique_ptr here? Will it create some ill interaction with raw pointers inside Qt classes?

Is it costly to pass an initializer_list as a list by value?

I want to pass a std::list as a parameter to fn(std::list<int>), so I do fn({10, 21, 30}) and everybody is happy.

However, I've come to learn that one shouldn't pass list by value, cause it's costly. So, I redefine my fn as fn(std::list<int> &). Now, when I do the call fn({10, 21, 30}), I get an error: candidate function not viable: cannot convert initializer list argument to 'std::list<int> &'.

QUESTION TIME

  1. Is the "you shall not pass an costly object by value" rule valid here? We aren't passing a list after all, but an initializer_list, no?
  2. If the rule still applies, what's the easy fix here?

I guess my doubt comes from the fact that I don't know clearly what happens when one passes an initializer_list argument to a function that accepts a list.

  1. Is list generated on the spot and then passed by value? If not, what is it that actually happens?

Should `constexpr` functions also be `noexcept`?

When I define a constexpr function, should I also declare it as noexcept? I imagine in the case where the arguments and usage satisfy the requirements for compile-time evaluation, the meaning of potential exceptions is moot. But it would apply as normal for cases when the function is evaluated at run time.

As a matter of practical concern, if the function is indeed simple, perhaps using built-in arithmetic or a cast, such that I expect the compiler can always inline the function and optimize across it, does it matter to the efficiency of the generated code if I leave off noexcept?

Point of declaration for an enumeration

What is the point of declaration of enumeration types? Is it immediately after the name of an enumeration? I saw Standard C++ 14 (n4296):

The point of declaration for an enumeration is immediately after the identifier (if any) in either its enum-specifier (7.2) or its first opaque-enum-declaration (7.2), whichever comes first

But when I try to reproduce it

template <class T>
struct CL
{
    using UndType = int;
};

enum class E: CL<E>::UndType;  //error: E is undefined

I have got an error on all the compilers, although enum-base for enumeration E is placed after the identifier and must be visible

C++ File System

I am trying to add these functions.

std::string GetDirectory(std::string path_name) {
    boost::filesystem::path path(path_name.c_str());

    path_name = path.string();

    path_name.erase(
        path_name.substr(
            path_name.find_last_of(DIRECTORY_SEPARATOR),
            path_name.length()
        )
    );
    return path_name;
}

std::string GetName(std::string path_name) {
    boost::filesystem::path path(path_name.c_str());

    path_name = path.string();

    path_name.erase(
        path_name.substr(
            0, 
            path_name.find_last_of(DIRECTORY_SEPARATOR)
        )
    );

    path_name.erase(
        path_name.substr(
            path_name.find_last_of("."), 
            path_name.length()
        )
    );
    return path_name;
}

std::string GetExtension(std::string path_name) {
    boost::filesystem::path path(path_name.c_str());

    path_name = path.string();

    path_name.erase(
        path_name.substr(
            0, 
            path_name.find_last_of('.')
        )
    );
    return path_name;
}

I am trying to add:

C:\Windows\Users\Example\Desktop\test.txt

GetDirectory

C:\Windows\Users\Example\Desktop

GetName

test

GetExtension

txt

I get errors though between path_name and erase (the period). Help would be much appreciated, Thank you.

dimanche 28 février 2016

Default constructor implicitly deleted using CRTP on VS2015 but not GCC or Clang

I'm writing a generic short vector class with a union to do type punning so I can swizzle the components. For example, if I declare Vector3 v3. I can access v3.yz as a Vector2. The following code works fine wit GCC 4.8 with -std=c++11 (or c++1y) and whatever version of Clang comes with Xcode 7.1.

However, it does not compile on Visual Studio 2015 with Update 1, using either the msvc or the Clang 3.7 toolkits:

#include <cstdint>
#include <cstdio>

template< int d, typename T, typename Derived >
class VectorBase
{
public:

    VectorBase()
    {
        for( int i = 0; i < d; ++i )
        {
            ( *this )[ i ] = T( 0 );
        }
    }

    const T& operator [] ( int i ) const
    {
        return static_cast< const Derived* >( this )->elements[ i ];
    }

    T& operator [] ( int i )
    {
        return static_cast< Derived* >( this )->elements[ i ];
    }
};

template< typename T >
class Vector2 : public VectorBase< 2, T, Vector2< T > >
{
public:

    typedef VectorBase< 2, T, Vector2 > Base;
    using Base::Base;

    union
    {
        struct
        {
            T x;
            T y;
        };
        T elements[ 2 ];
    };
};

template< typename T >
class Vector3 : public VectorBase< 3, T, Vector3< T > >
{
public:

    typedef VectorBase< 3, T, Vector3 > Base;
    using Base::Base;

    union
    {
        struct
        {
            T x;
            T y;
            T z;
        };
        struct
        {
            Vector2< T > xy;
        };
        struct
        {
            float __padding0;
            Vector2< T > yz;
        };
        T elements[ 3 ];
    };
};

int main( int argc, char* argv[] )
{
    Vector2< float > v2;
    Vector3< float > v3;

    printf( "v2 has size %zu, .x = %f, .y = %f\n", sizeof( v2 ), v2.x, v2.y );
    printf( "v3 has size %zu, .x = %f, .y = %f, .z = %f\n", sizeof( v3 ), v3.x, v3.y, v3.z );
}

VS 2015 complains with the error message:

1>  main.cpp
1>main.cpp(79,22): error : call to implicitly-deleted default constructor of 'Vector3<float>'
1>      Vector3< float > v3;
1>                       ^
1>  main.cpp(63,9) :  note: default constructor of 'Vector3<float>' is implicitly deleted because variant field '' has a non-trivial default constructor
1>          struct
1>          ^
1>  1 error generated.

It makes sense that the compiler thinks the default constructor is nontrivial and implicitly deletes it. What doesn't make sense is why inheriting the constructor with the using declaration fail, and the difference between compilers.

I can make it work by explicitly adding a Vector3 constructor that explicitly calls the VectorBase constructor in the initialization list, but that somewhat defeats the purpose of using the CRTP.

std::chrono::system_clock and duration

I can measure time using:

t1 = system_clock::now();
...
t2 = system_clock::now();

duration<double> d = t2 - t1;

That compiles fine, but how do I do the reverse? I want to move a time point using duration?

example (does not compile):

system_clock::time_point tp1 = system_clock::now();
system_clock::time_point tp2 = tp1 + duration<double>(1.0);

The system_clock::time_point '+' operator does not seem to accept duration<double>.

How can I move a time point by a duration specified using time in seconds (floating point value)? I need to use system_clock because it can convert to time_t.

C++ run time with different loops

Why do both of these loops take the same amount of time, shouldn't the if statement make the first single loop much slower?

// Example program                                                                                     
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
  int counter = 0;
  #ifdef single
  cout << "one for loop\n";
  for(int i =0;i<10000000;i++)
    {
      if(i != 50000) counter+=i;
    }
#else
  cout << "two loops\n";
  for(int i = 0;i<50000;i++)
    {
      counter+=i;
    }
  for(int i = 50001;i<10000000;i++)
    {
      counter+=i;
    }
#endif
  return 0;
}

I get, for time, the following results: time ./test one for loop

real 0m0.004s user 0m0.001s sys 0m0.002s

AND

two loops

real 0m0.004s user 0m0.001s sys 0m0.002s

I did some research and it said it is cause of branching but I'm not sure if that is the only reason, it was compiled as

g++ -std=c++11 -O3 test.cpp -Dsingle -o test

Enable shared ownership support for an object

I enabled a simple shared ownership for a class with the following control block structure

struct Ptr
{
    C* value_ ;
    size_t ref_ ;
    IdType id_ ;
} ;

Ptr* ptr_ ;

value_ is the payload with a shared ownership,

id_ is a database Id that links value to a database row. It can exist with or without a payload, that's why it's not part of the payload but part of the control block,

ref_ is the reference counter.

And the following functions allowing to take ownership and releasing it:

template<class C>
void ptr<C>::free()
{
    if(ptr_)
    {
        ptr_->ref_-- ;
        if(ptr_->ref_==0)
        {
            delete ptr_->value_ ;
            delete ptr_ ;
            ptr_ = nullptr ;
        }
    }
}

template<class C>
void ptr<C>::take()
{
    if(ptr_)
        ptr_->ref_++ ;
}

This works well but I need to go further as it does not cover my needs:

  1. This is not conform to the shared_ptr standard as my control block is not thread safe and my ownership manipulation is not atomic
  2. I need to add weak ownership support. This will be quite easy as I just need to have a second counter and delete the control block only if all counters falls to 0.

My needs for the ownership behavior are already covered by c++11 smart pointers but they are not designed to be inherited and there is no way to customize the control block.

I tried to understand how the atomicity was handled with both boost and standard library but this is relatively cryptic for now.

So the question is simple, is there a way with boost or stl to enable shared ownership support inside object core design, and by this way be compliant with c++ standards?

Why does my user input only get accepted the second time?

I'm having problems with my first input loop. I'm trying to use them to validate input, but I have a problem where entering correct data on the first try still receives an error. Entering that same data a second time will result in true. This happens in my first loop but not my second.

// previous cin ^
// contribution input, checks for numbers only
    cout << "Please enter their contribution amount: ";
    cin.ignore();
    cin >> total[i].contAmount;    // total[i] is a vector of structures
    while (!((total[i].contAmount >= 500) && (total[i].contAmount <= 20000)))
    {
        cout << "Please enter a valid number between 500 and 20000, for example: 14382.53. Only use numerals or periods: ";
        cin.clear();
        cin >> total[i].contAmount;
    }
// telephone number input, checks for 10 numbers
    cout << "Please enter their telephone number in this format: 1234567890: ";
    cin.ignore();
    string tempNum;
    getline(cin, tempNum);
    while (!((checkPhone(tempNum, 10)) && (tempNum.length() == 10))) // checkPhone function uses isdigit to check for only numbers
    {
        cout << "Please enter exactly 10 numbers (ex 1234567890): ";
        cin.ignore();
        cin >> tempNum;
    }
    total[i].teleNum = tempNum;

It probably has something to do with cin >> vs. getline, but I don't know how to use getline with my vector/structure. I know I am also probably using cin.ignore() improperly, but when I don't use it my code jumps to the next cin without letting the user input anything.

Thanks for your help.

user input validation loop only works on second input

I'm having problems with my input loops. I'm trying to use them to validate input, but I have a problem where entering correct data on the first try still receives an error. Entering that same data a second time will result in true.

// previous cin ^
    // contribution input, checks for numbers only
        cout << "Please enter their contribution amount: ";
        cin.ignore();
        cin >> total[i].contAmount;    // total[i] is a vector of structures
        while (!((total[i].contAmount >= 500) && (total[i].contAmount <= 20000)))
        {
            cout << "Please enter a valid number between 500 and 20000, for example: 14382.53. Only use numerals or periods: ";
            cin.ignore();
            cin >> total[i].contAmount;
        }
    // telephone number input, checks for 10 numbers
        cout << "Please enter their telephone number in this format: 1234567890: ";
        cin.ignore();
        string tempNum;
        getline(cin, tempNum);
        while (!((checkPhone(tempNum, 10)) && (tempNum.length() == 10))) // checkPhone function uses isdigit to check for only numbers
        {
            cout << "Please enter exactly 10 numbers (ex 1234567890): ";
            cin.ignore();
            cin >> tempNum;
        }
        total[i].teleNum = tempNum;

I know I am probably using cin.ignore() improperly, but when I don't use it my code jumps to the next cin without letting the user input anything.

Thanks for your help.

Two STL threads wait on a third thread—do with joinable?

I want two threads (let's call them t1 and t2) to wait for one other thread, t0. Let's simplify matters and say t1 and t2 are both worker threads. I don't think the following code will work correctly.

/* ... code both t1 and t2 run ... */
if (t0.joinable()) { 
  /* race condition here */
  t0.join();
}

It's possible for both t1 and t2 to get true for joinable, and then whichever joins first wins and the other one probably segfaults—right? So what is the correct way to have two threads wait on a single third thread?

Is there a way to do this just with joins of the STL, or does t0 need to set some sort of (atomic) done flag or use a condition variable?

What is the fastest way to put 8 bit integer in 16 bit integer array

I am working on a program that processes images. If I could store RGBA values in 16bit integers I could increase performance by using SSE (without the risk of overflow). However the conversion from 8 bit integers to 16 bit integers is the bottleneck. What is the fastest way to put signed 8 bit integers into 16 bit inetger array, an efficient equvalent of

int8_t a[128];
int16_t b[128];

for (int i=0;i<128;i++)
       b[i]=a[i];

Of course I am using openmp and pointers.

for_each function in c++11

I have vector of integers filled with 5 numbers and i'm curious what exactly does [&idx] do in :

int idx = 0;
for_each ( x . begin (), x . end (), [&idx] ( const int & a ) { cout << idx ++ << " " << a << endl; } );`

Why it does not work like this ? :

int idx = 0;
  for_each ( x . begin (), x . end (), ( const int & a, int & idx ) { cout << idx ++ << " " << a << endl; } );

Is it better from perfomance point of view than? :

for ( vector<int>::size_type i = 0; i < x . size (); i ++ )
    cout << x[i] << endl;

How efficient is iterating through an unordered_set?

Does iterating through an unordered_set require looking through each bucket of the hash table? If so, wouldn't that be very inefficient? If I want to frequently iterate over a set but still need remove in O(1) time is unordered_set still the best data structure to use?

How to define member class operator based on the class parameters

Is it possible to define different = operators for different template arguments. Let's assume that I want to use different methods for converting arguments of different types:

template <class T,class U>
class cTest
{
  private:
  public:
    T x;
    U y;

  //typical case
  cTest<T,U>& operator =(const cTest<T,U> &that)
  {
     return *this;
  }

  //operator = based on the LHS type 1
  cTest<uint16_t,U>& operator =(const cTest<int,U> &that)
  {
     cout<<"cTest<uint16_t,U>& operator =(const cTest<int,U> &that)"<<endl;
     return cTest<uint16_t,U>();
   }
  //operator = based on the LHS type 2
   cTest<uint8_t,U>& operator =(const cTest<int,U> &that)
   {
      cout<<"cTest<uint8_t,U>& operator =(const cTest<int,U> &that)"<<endl;
      return cTest<uint16_t,U>();
   }
};

How to sort dice and create new arrays with equal dice in each array, Yahtzee, C++

I'm making an Yahtzee game in C++, my goal is to make an intelligent play field there the game will give examples to the user where he or she can put the result. In order to do that I have to sort the dices from low to high and then make new arrays, one array for those dices equal each other and the size of each array has to be as big as the number of dices in it.

This is my base-class:

The funktion that throws each dice.

void InGame::setDice(int dice){
    if (this->diceCapacity <= this->nrOfDices){
        this->expandDice();
    }
    for (int i = 0; i < nrOfDices; i++){
        die[i]->roll(6);
    }
}

setDice works fine. After this I'm sorting all 5 dices in a sub-class called scoreCalculator.

The sorting funktion:

void ScoreCalculator::sortDie(int arr[], int nrOfDieces){
    int temp = -1;
    int minIndex = 0;
    for (int i = 0; i < nrOfDieces - 1; i++){
        minIndex = i;
        for (int k = (i + 1); k < nrOfDieces; k++){
            if (arr[k] < arr[minIndex]){
                minIndex = k;
            }
        }
        temp = arr[i];
        arr[i] = arr[minIndex];
        arr[minIndex] = temp;
    }
}

And now I'm going to fill each equal die into different arrays that just holds those dices that are equal to each other.

This is what I have done so far

void ScoreCalculator::equalDie(int dice[]){
    dice[5];
    this->sortDie(dice, 5);
    int count = 0;
    int equal[5];
    for (int i = 0; i < 5; i++){
        for (int x = 1; x < 6; x++){
            if (dice[i] == dice[x]){
                for (int y = 0; y < 5; y++){
                    equal[y] = dice[i];
                    equal[y + 1] = dice[x];
                    y++;
                }
            }
        }
    }
}

This last funktion is not working at all

emplace_back takes more time than push_back for a pre constructed object

I understand the reasons why emplace_back is preferred over push_back. I have the following piece of code:

#include <iostream>
#include <vector>
#include <ctime>
#include <ratio>
#include <chrono>

using namespace std;
using namespace std::chrono;

class X 
{
};

void get_timings()
{
    high_resolution_clock::time_point t, t1;
    duration<double> time_span;
    const std::uint64_t M = 999999999;
    std::vector<X> vec;
    vec.reserve(M);
    for (std::uint64_t i = 0; i < M; ++i)
    {
         vec.push_back(X());    
    }
    vec.clear();    
    vec.reserve(M);
    X x;    
    t = high_resolution_clock::now();
    for (std::uint64_t i = 0; i < M; ++i)
    {
         vec.push_back(x);    
    }
    t1 = high_resolution_clock::now();
    time_span = duration_cast<duration<double>>(t1 - t);

    // 1.
    std::cout << "Push back same object " << time_span.count() << std::endl;

    vec.clear();
    vec.reserve(M); 
    t = high_resolution_clock::now();
    for (std::uint64_t i = 0; i < M; ++i)
    {
        vec.emplace_back(x);    
    }
    t1 = high_resolution_clock::now();
    time_span = duration_cast<duration<double>>(t1 - t);

    // 2.
    std::cout << "Emplace back same object " << time_span.count() << std::endl; 
}

Following is the compilation line:

g++ testing_emplace.cpp   (No optimizations)

OS: CentOS7.2
8GB RAM
Compiler : gcc 4.9.2

I tried the experiments with different values of M. As the value of M increased the time difference between emplace and push back increased. As M increased emplace took more amount of time.

Is my experiment wrong ? Is emplace_back supposed to take the same time or less time as push_back always.

Why is the return type of std::reverse_iterator::operator[] unspecified?

I was wondering, why, in C++, the return type of std::reverse_iterator::operator[] is left unspecified. Shouldn't it be a std::reverse_iterator::reference?

CRTP compile detection with template composition

I'm stuck with templates problems since few days and you solve each of my problem at a time so thank you in advance.

So I've a template (tl1) who care about a uml composition, and another template (tl2) wich is the uml composed
So my goal is to not compile if the composed object is not a derived of tl2 and if typename D is not a tl1 derived.

Following this post and the help of this one I've got the following code:

#include <type_traits>
#include <list>
#include <string>

template <typename T, typename C>
class tl2 ;

template <typename D, typename T>
class tl1 {
private:
    static_assert(std::is_base_of<tl2<T, D>, T>::value, "T should     inherit from tl2");
    std::list<T> mTs ;
    tl1() {} ;
    friend D ;
public:
    T & getTbyName() const ;
};

template <typename T, typename C>
class tl2 {
    //static_assert(std::is_base_of<tl1<C, T>, C>::value, "D should inherit from Database");
public:
    std::string getName() { return mName ; }
private:
    C & mC ;
    std::string mName ;
};

class cl1 ;

class cl2 : public tl2<cl2, int>  {

};
class cl1 : public tl1<int, cl2>  {

};

My problem is this compile very well and I would like not.
It doesn't compile if I change cl1 to:

class cl1 : public tl1<int, cl2>  {    
    cl1() {}
};

The fact is tl1 and tl2 will be in library, so I want to perform all checks in the library. I will not have control over derived so I'd like to be sure that implementation is tlX derived.

Thank you for your time again.
Quentin

returning structure cause program to crash or return only first word

I can not figure out for the life of me why when i return pigLatin in the Word piglatin function it keeps crashing or not executing probably outside the function when i call it. here is my code if anyone wants to check it out. -Thank You

#include <iostream>
#include <string>
#include <cstring>
#include <cctype>
using namespace std;

struct Word
{
    string piglatin;
    string english;
};

Word piglatin(string latin, int &size);

int main() {

int sum=1; // how many words

string pig;

cout <<"Enter a sentence in piglatin to decode";
getline(cin,pig); // get user input

Word latinReturn[sum];
*latinReturn = piglatin(pig,sum); // call to function piglatin

 cout << endl << "test out 0:  " << latinReturn[0].piglatin;
cout << endl << "test out 1:  " << latinReturn[1].piglatin;
cout << endl << "test out 2:  " << latinReturn[2].piglatin;
return 0;
}


Word piglatin( string latin, int &size)


for (int i=0; i < latin.length(); i++) // find how many words
{
if(latin[i] == ' ')
    {
    size++;
    }
}
cout<< "size: " <<size <<endl;

    int x=latin.length();
    string temp;
    char ending = latin[x-1];
    int count=0;
    Word pigLatin[size];
    //pigLatin = new Word[size];

    for(int i=0;i < latin.length(); i++)  //lower case
        {
            latin[i] = tolower(latin[i]);
        }

        cout <<endl << "test2:  " << latin;

        for(int i=0; i < latin.length(); i++)  //remove extra
        {
            if(isalpha(latin[i]) || isspace(latin[i]))
            {
                temp += latin[i];
            }
        }

        latin =temp; // make latin into temp
        latin +=ending; //ending char
        cout << "test3: " <<endl << latin;

        for(int i=0; i <latin.length(); i++) //change into struct array
            {
                if(isalpha(latin[i]))
                {
                    pigLatin[count].piglatin += latin[i];
                }
                else if (isspace(latin[i])){
                    count++;
                }
            }
            cout<<endl <<"test final:" <<pigLatin[1].piglatin;
            cout<<endl <<"test final:" <<pigLatin[0].piglatin;
            cout<< endl << " count is: " << count;
        return *(pigLatin);

Why would I use a unique_lock<> wrapper?

Why would I use a unique_lock<> wrapper?

I sometimes see code like this

std::unique_lock<std::mutex> lock(m_active_sessions_guard); // lock() the associated mutex
m_active_sessions[request_id] = session;
lock.unlock();

where a unique_lock<> is created just to lock the associated mutex.

Having searched, I've found that this class is not copyable. Is this the only benefit of using it?

std::thread Unhanded exception accessing this*

I have a Timer class that calls a function passed to create and it loops and sleeps for what ever time given. Problem im having is when trying to kill that timer from withen the passed function i get that exception at pThis->Stop()

Class:

class CTimer
{
public:
    CTimer()
        :_running(false)
    {}

    ~CTimer() {
        if (_running.load(std::memory_order_acquire)) {
            Stop();
        };
    }

    void Stop()
    {
        _running.store(false, std::memory_order_release);
        if (_thread.joinable())
            _thread.join();
    }

    template <typename F, typename... A>
    void Start(int interval, F func, A&&... args)
    {
        if (_running.load(std::memory_order_acquire))
            Stop();

        _running.store(true, std::memory_order_release);
        _thread = std::thread([this, interval, func, &args...]()
        {
            while (_running.load(std::memory_order_acquire))
            {
                func(this, std::forward<A>(args)...);

                std::this_thread::sleep_for(std::chrono::milliseconds(interval));
            }
        });
    }

    bool Running() const noexcept {
        return (_running.load(std::memory_order_acquire) &&
            _thread.joinable());
    }

private:
    std::atomic<bool> _running;
    std::thread _thread;
};

Global:

CTimer Timer;

Thread:

void TimerThread(CTimer* pThis, HWND hwnd)
{
    // my code in side here
    // everything works fine till i try to stop within this thread


    // crash here
    pThis->Stop();
}

Call it like this:

Timer.Start(2000, TimerThread, hwnd);

samedi 27 février 2016

A little hazy about std::ref() and std::bind() with variadic templates

I have read many posts about variadic templates and std::bind but I think I am still not understanding how they work together. I think my concepts are a little hazy when it comes to using variadic templates, what std::bind is used for and how they all tie together.

In the following code my lambda uses the dot operator with objects of type TestClass but even when I pass in objects of type std::ref they still work. How is this exactly? How does the implicit conversion happen?

#include <iostream>
using std::cout;
using std::endl;
#include <functional>
#include <utility>
using std::forward;

class TestClass {
public:
    TestClass(const TestClass& other) {
        this->integer = other.integer;
        cout << "Copy constructed" << endl;
    }
    TestClass() : integer(0) {
        cout << "Default constructed" << endl;
    }
    TestClass(TestClass&& other) {
        cout << "Move constructed" << endl;
        this->integer = other.integer;
    }

    int integer;
};

template <typename FunctionType, typename ...Args>
void my_function(FunctionType function, Args&&... args) {
    cout << "in function" << endl;
    auto bound_function = std::bind(function, args...);
    bound_function();
}

int main() {

    auto my_lambda = [](const auto& one, const auto& two) {
        cout << one.integer << two.integer << endl;
    };

    TestClass test1;
    TestClass test2;
    my_function(my_lambda, std::ref(test1), std::ref(test2));

    return 0;
}

Clion how to deploy project?

I have the following CMakeLists.txt:

cmake_minimum_required(VERSION 3.3)
project(Thesis)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

set(SOURCE_FILES main.cpp Graph.h Graph.cpp)
add_executable(Thesis ${SOURCE_FILES})

I am using Run->Build (as release) on a custom folder ClionProjects\Thesis\exe\Release and I get a single executable Thesis.exe. If I open that, I get the following consecutive errors:

1

What am I missing exactly ?

Automatic move constructor

If I have the following type:

struct Data
{
    std::string str;
    std::vector<int> vec;
    float f;
private:
    Data(){}
};

and I don't define a move constructor, a copy will happen if I do the following?

Data d1;
d1.str = "abc";
d1.vec = {1, 2, 3};
Data d2 = d1;

Why doesn't a constexpr have a unique value or storage?

I'm using Wt::WFormModel, the examples for which represent field names as static const char*'s. I made a bunch of changes to my project at one time, one of which was changing the field representation to be constexpr. After much troubleshooting, I found this statement in the WFormModel documentation:

The Field type is const char *, and instead of string comparisons to identify fields, pointer comparisons are used. Thus you really should use the same field constant throughout your code to refer to a given field, and you cannot use C++11 constexpr for the field constant since that does not have a unique value (since it has no storage).

How does the representation of a constexpr char* compare to the representation of a const char*?

Function Type which Returns Itself

I'm trying to write a very minimal state machine in C++. I'd like the states to be methods of the machine's class, and each state, when run, should return the new state to move to. Naturally, I'm using a few typedef's to help out.

template <typename C, typename E>
using State = State<C, E> (C::*)(Stream<E>&);

A state should be a member function (in class C) which takes a stream object and yields a new state. I'm getting the following error.

fsm.hpp:8:15: error: ‘State’ does not name a type
 using State = State<C, E> (C::*)(Stream<E>&);

Obviously, State is not declared yet on the line that should declare State. As far as I know, there's no way to "forward declare" a typedef, so what is the appropriate way to declare this typename?

Data stucture for large binary data manipulation

Hello fellow programmers,

I am working on a genetic project where the speed efficiency is crucial. I have essentially a lot of binary data to process. I work in c++11. I have two functions that needs to be optimized.

First, I need to be able to use binary operators between four binary strings and then check if all the bits are all zeros.

i.e. (bitV1 & (bitV2^bitV3)| bitV4) == 0..0

Second, I sometimes need to flip certain bits at certain location.

My problem is that bitset need to know the size at compile time, and I don’t know that size at compile time only at execution. And vector doesn’t seem to work with binary operators. I could translate my data in chars/string or int arrays and then use the bitwises operators on those but the code is not going to be pretty.

Does somebody know an efficient and simple way to do this?

Here is an MWE:

#include<iostream>
#include<bitset>
#include<vector>


int main() {
// I dont know the sizes for the sequences at compile time.
//std::bitset<intFromFile> firstBitset ("0011"); // doesnt compile

std::bitset<4> firstBitset ("0011");
std::bitset<4> secondBitset ("0101");
std::bitset<4> resultBitset = firstBitset &secondBitset;
std::cout << resultBitset; //OK

std::vector<bool> firstVector  {0,0,1,1};
std::vector<bool> secondVector {0,1,0,1};
//std::vector<bool> result = firstVector^secondVector; //ERROR
std::vector<bool> result {0,0,0,1}; //  OK

for (unsigned short int i = 0 ; i < result.size(); ++i){
    std::cout << result.at(i);
}
std::cout << std::endl;

return 0;
}

Using auto foo = "bar" vs std::string in C++11

I'm searching for a substring using string::find in C++. When I defined a string using const auto and used the variable later down, eclipse replaced . with ->.

I found this SO thread which concludes that auto foo = "bar" is deduced to a (const char *) foo = "bar". So eclipse is correct converting . to -> even though I was a bit baffled to begin with. I assumed incorrectly auto would become std::string.

Would there be a downside deducing auto foo = "bar" to std::string instead of const char * ? Increased code size, slower performance?

JavaFX interfacing with C++

I have a JavaFX GUI Calculator built and I have a C++ shared library declaring all the functions , such as addition , multiplication etc. What I would like to do is , call the c++ functions on button click on the calculator App. How would I do that ?

Make fails with: fatal error: 'random/uniform.h' file not found

I am having an import issue with <random/uniform.h>.

The issue is because random was introduced in c++11 (Why is the c++ standard library not working?). I can specify support for c++11 with -std=c++11 or -std=c++x0, but it won't work with g++. I tried using clang, but I am not sure if I have the required min clang version (4.2).

    clang++ --version

gives

    Apple LLVM version 7.0.2 (clang-700.1.81)
    Target: x86_64-apple-darwin14.5.0
    Thread model: posix

When I check Xcode for updates, there are none.

C++11 : Why is trying to store a pointer to function ambiguous

Here is my code:

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

    using namespace std;

    // vector iterator
    template <class T> class vit
    {
            private:
            //vector<T>::iterator it;
            vector<T> m_v;
            function<bool (T, T)> m_fptr;
            int len, pos;
            public:
            vit(vector<T> &v) { this->m_v = v; len = v.size(); pos = 0;};
           //       it= v.begin(); };
            bool next(T &i) {
                    //if(it == m_v.end()) return false;
                    if(pos==len) return false;
                    //i = *it;
                    i = m_v[pos];
                    //if(idle) { idle = false ; return true; }
                    //it++;
                    pos++;
                    return true;};
            //bool idle = true;
            void set_same(function<bool (T,T)> fptr) { m_fptr = fptr ;};
            //void set_same(function<bool(int, int)> fun) { return ; }
            bool grp_begin() {
                    return pos == 0 || ! m_fptr(m_v[pos], m_v[pos-1]); };
            bool grp_end() {
                    return pos == len || ! m_fptr(m_v[pos], m_v[pos+1]); };
    };


    bool is_same(int a, int b) { return a == b; }

    main()
    {
            vector<int>  v ={ 1, 1, 2, 2, 2, 3, 1, 1, 1 };
            int total;
            for(auto it = v.begin(); it != v.end(); it++) {
                    if(it == v.begin() || *it != *(it-1)) {
                            total = 0;
                    }

                    total += *it;

                    if(it+1 == v.end() || *it != *(it+1)) {
                            cout << total << endl;
                    }
            }

            cout << "let's gry a group" <<endl;
            vit<int> g(v);
            int i;
            while(g.next(i)) { cout << i << endl; }

            cout << "now let's get really fancy" << endl;
            vit<int> a_vit(v);
            //auto is_same = [](int a, int b) { return a == b; };
            a_vit.set_same(is_same);
            //int total;
            while(a_vit.next(i)) {
                    if(a_vit.grp_begin()) total = 0;
                    total += i;
                    if(a_vit.grp_end()) cout << total << endl ;
            }
    }        

When I compile it with g++ -std=c++11 iter.cc -o iter, I get the result:

    iter.cc: In function 'int main()':
    iter.cc:63:17: error: reference to 'is_same' is ambiguous
      a_vit.set_same(is_same);
             ^
    iter.cc:37:6: note: candidates are: bool is_same(int, int)
     bool is_same(int a, int b) { return a == b; }
          ^
    In file included from /usr/include/c++/5.3.0/bits/move.h:57:0,
                     from /usr/include/c++/5.3.0/bits/stl_pair.h:59,
                     from /usr/include/c++/5.3.0/utility:70,
                     from /usr/include/c++/5.3.0/tuple:38,
                     from /usr/include/c++/5.3.0/functional:55,
                     from iter.cc:1:
    /usr/include/c++/5.3.0/type_traits:958:12: note:                         template<class, class> struct std::is_same
         struct is_same;
                ^

By way of explanation, I have created a class called 'vit'. It does two things: iterate over a vector, and determine if a new group has been reached.

The class function 'set_same' is supposed to store a function provided by the calling class to determine if two adjacent elements of a vector are in the same group. However, I can't seem to store the function in the class for future use by grp_begin() and grp_end() on account of the ostensible ambiguity of is_same.

What gives?

Multiple types on a deque?

This is non-Boost C++11. What's the best option for a single stack-like container for two different types? Something that'd work like this imaginary scenario:

template<typename T>
deque <pair<T, v8::Local<v8::Value>>> my_queue;

uint32_t aUint = ...;
v8::Local<v8::Value> value1 = ...;
v8::Local<v8::String> aString = ...;
v8::Local<v8::Value> value2 = ...;

my_queue.push_back(make_pair(aUint, value1));
my_queue.push_back(make_pair(aString, value2));

Flex tokens not working with char* hashtable

I am making a simple compiler, and I use flex and a hashtable (unordered_set) to check if an input word is an identifier or a keyword.

%{
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <unordered_set>
using std::unordered_set;
void yyerror(char*);
int yyparse(void);

typedef unordered_set<const char*> cstrset;
const cstrset keywords = {"and", "bool", "class"};
%}
%%
[ \t\n\r\f]             ;
[a-z][a-zA-Z0-9_]*      {   if (keywords.count(yytext) > 0)
                                printf("%s", yytext);
                            else
                                printf("object-identifier"); };

%%

void yyerror(char* str) {printf("ERROR: Could not parse!\n");}
int yywrap() {}

int main(int argc, char** argv)
{
    if (argc != 2) {printf("no input file");}
    FILE* file = fopen(argv[1], "r");
    if (file == NULL) {printf("couldn't open file");}
    yyin = file;
    yylex();
    fclose(file);
    return 0;
}

I tried with an input file that has only the word "class" written, and the output is object_identifier, not class. What could be the problem?

How to check if a vector of a vector exists?

I would like to know if a vector of vectors exist

for example

vector<vector<int> > edges;

Now I would like to check if edges[i] existis. I tried

if(edges[i] == NULL)

But it did not seem to work. How this can be resolved?

check function passed to template has class in arguments

This is a little hard to explain, In my class i have a create function that takes a pointer and arguments I want to be able to check if the function im passing to that function has the ClassPointer as its 1st argument if so automaticly add this to the function inside "create" if not just add the normal functions arguments if any,like im doing

       template <typename Function, typename... Arguments>
        void SomeClass::create(HWND hWnd, Function func, Arguments&&... args)
        {
            // check if function's 1st argument = class pointer

            std::function<void()> function = std::function<void()>(std::bind(std::forward<Function>(func), this, std::forward<Arguments>(args)...)); 

            // else

            std::function<void()> function = std::function<void()>(std::bind(std::forward<Function>(func), std::forward<Arguments>(args)...)); 
        }

        void ThreadProc1(SomeClass* pThis, HWND hwnd)
        {
             // do some stuff in here
        }

        void ThreadProc2(HWND hwnd)
        {
             // do some stuff in here
        }

test.Create(hwnd, ThreadProc1, hwnd);
test.Create(hwnd, ThreadProc2, hwnd);

Passing by Reference and Forming References in C++98 and C++11

The following function works in C++11:

/**
* @brief Enqueue a data item in the PQ with given priority.
*
* @param data Data item to insert into PQ
* @param priority Priority level of item
*/
void enqueueWithPriority(const T& data, const PT priority) {

    size_t sizeVec = dataWithPriorityVec.size();

    // push the pair of data parameters to the end of the data vector
    dataWithPriorityVec.push_back(std::make_pair<const T&, const PT&>(data, priority));

    // call bubble up to sort data priorities
    bubbleUpHeap(sizeVec);

}

However it does not work in C++98 as I have to alter the std::make_pair part to: std::make_pair<const T, const PT> due to the inability to "store" references in 98. Similar syntax occurs in several other functions across my template class (where T and PT are generic typenames).

Is there a way I can resolve the issue such that I can use a single form of syntax as the former way works in C++11 but not 98 whereas the latter works in C++98 but not 11 - and I need to test in both environments unfortunately.

std::atomic_flag to stop multiple threads

I'm trying to stop multiple worker threads using a std::atomic_flag. Starting from Issue using std::atomic_flag with worker thread the following works:

#include <iostream>
#include <atomic>
#include <chrono>
#include <thread>

std::atomic_flag continueFlag;
std::thread t;

void work()
{
    while (continueFlag.test_and_set(std::memory_order_relaxed)) {
        std::cout << "work ";
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
}

void start()
{
    continueFlag.test_and_set(std::memory_order_relaxed);
    t = std::thread(&work);
}

void stop()
{
    continueFlag.clear(std::memory_order_relaxed);
    t.join();
}

int main()
{
    std::cout << "Start" << std::endl;
    start();
    std::this_thread::sleep_for(std::chrono::milliseconds(200));
    std::cout << "Stop" << std::endl;
    stop();
    std::cout << "Stopped." << std::endl;

    return 0;
}

Trying to rewrite into multiple worker threads:

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

struct thread_data {
    std::atomic_flag continueFlag;
    std::thread thread;
};

std::vector<thread_data> threads;

void work(int threadNum, std::atomic_flag &continueFlag)
{
    while (continueFlag.test_and_set(std::memory_order_relaxed)) {
        std::cout << "work" << threadNum << " ";
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
}

void start()
{
    const unsigned int numThreads = 2;

    for (int i = 0; i < numThreads; i++) {
        ////////////////////////////////////////////////////////////////////
        //PROBLEM SECTOR
        ////////////////////////////////////////////////////////////////////
        thread_data td;
        td.continueFlag.test_and_set(std::memory_order_relaxed);

        td.thread = std::thread(&work, i, td.continueFlag);

        threads.push_back(std::move(td));
        ////////////////////////////////////////////////////////////////////
        //PROBLEM SECTOR
        ////////////////////////////////////////////////////////////////////
    }
}

void stop()
{
    //Flag stop
    for (auto &data : threads) {
        data.continueFlag.clear(std::memory_order_relaxed);
    }
    //Join
    for (auto &data : threads) {
        data.thread.join();
    }
    threads.clear();
}

int main()
{
    std::cout << "Start" << std::endl;
    start();
    std::this_thread::sleep_for(std::chrono::milliseconds(200));
    std::cout << "Stop" << std::endl;
    stop();
    std::cout << "Stopped." << std::endl;

    return 0;
}

My issue is "Problem Sector" in above. Namely creating the threads. I cannot wrap my head around how to instantiate the threads and passing the variables to the work thread.

The error right now is referencing this line threads.push_back(std::move(td)); with error Error C2280 'thread_data::thread_data(const thread_data &)': attempting to reference a deleted function.

Trying to use unique_ptr like this:

        auto td = std::make_unique<thread_data>();
        td->continueFlag.test_and_set(std::memory_order_relaxed);

        td->thread = std::thread(&work, i, td->continueFlag);

        threads.push_back(std::move(td));

Gives error std::atomic_flag::atomic_flag(const std::atomic_flag &)': attempting to reference a deleted function at line td->thread = std::thread(&work, i, td->continueFlag);. Am I fundamentally misunderstanding the use of std::atomic_flag? Is it really both immovable and uncopyable?

Preserving the type and its value

Here is the code that I am working on.

class HoldThis
{
public:
    template<typename T> explicit 
    HoldThis(const T& in)
    :a_in(in)
    ,a_givemebase([=]()-> const SomeBaseType& { 
        return boost::any_cast<const T&>(a_in); })
    { }

    const SomeBaseType& getBase() const
    {
        return a_givemebase();
    }

private:
    boost::any a_in;
    std::function<const SomeBaseType& ()> a_givemebase;
};

The problem is that type T that comes in is always derived from SomeBaseType. I want to preserve T and the value in that comes with it via some form of template metaprogramming.

Is this possible? To preserve T and then return its value via a getter when required. I am using C++11 and I can not use any C++14 or beyond features.

I have tried using boost::mpl::identity to fetch the type T but someway or other, I am stuck with not having the knowledge of T or the value that comes in.

C++ does not insert numbers/digits into the vector as desired

I have a variable (string) named eq which holds a simple equation like y=2x+5. I wanted to separate all the constants and variables. For this I declared 2 vectors:

std::vector <int> constants;
std::vector <char> variables;

I separated variables in this manner:

for(int i = 0; i < eq.size(); i++) {
  if(isalpha(eq[i])) {
    variables.push_back(eq[i]);
  }
}

The method worked well and it separated variables like I wanted. However, when I tried the same, to separate constants, the method did not work. No matter what equation was supplied, I started getting irrelevant numbers. Equation had only 1 digit numbers like 4,3 or 5. But the vector was returning 2 digit numbers like 50, 53 or 52.

I checked the contents of the vector in this way:

for(auto j: constants) {
  std::cout << j << std::endl;
}

For debugging purpose, I removed the vector.push_back line and replaced it with std::cout << eq[i] << std::endl; to check if the digits/numbers in the equation were being picked up. Yes the digits were being picked up, but the issue was that they weren't being inserted into the vector properly. The method worked fine for fetching variables but doesn't work for fetching constants. Where am I going wrong?

Edit: Here's the part of the code (actual code is very lengthy).

std::string eq = argv[1];
std::vector <char> variables;
std::vector <int> constants;

for(int i = 0; i < eq.size(); i++) {
    if(isalpha(eq[i]) && eq[i] != 'c') {
      variables.push_back(eq[i]);
    }
  }

  for(int i = 0; i < eq.size(); i++) {
    if(isdigit(eq[i])) {
      constants.push_back(eq[i]);
    }
  }

Is the execution of a c++ 11 atomic object also atomic ?

I have a object and all its function should be executed in sequential order. I know it is possible to do that with a mutex like

#include <mutex> 

class myClass {
private:
    std::mutex mtx;
public:
    void exampleMethod();
};

void myClass::exampleMethod() {
    std::unique_lock<std::mutex> lck (mtx); // lock mutex until end of scope

    // do some stuff
}

but with this technique a deadlock occurs after calling an other mutex locked method within exampleMethod.

so i'm searching for a better resolution. the default std::atomic access is sequentially consistent, so its not possible to read an write to this object at the same time, but now when i access my object and call a method, is the whole function call also atomic or more something like

object* obj = atomicObj.load(); // read atomic
obj.doSomething(); // call method from non atomic object;

if yes is there a better way than locking the most functions with a mutex ?

Custom priority queue comparator that accesses private members of a class

If you look at the code below, I am trying to create a priority_queue, I have named it DijkstraPriorityQueue, that has a custom comparator which also uses the private vector distTo.

You can see that I have some dots ....... as everything I tried have failed.

What is the cleanest solution (or possible solutions) to make this work as intended in this specific case ?

Dijkstra.h

class Dijkstra
{
public:
    Dijkstra(Graph G, int s);                          // Create
    ~Dijkstra();                                       // Destroy

private:
    bool compare(int u, int v)
    {
        return distTo[u] < distTo[v];
    }
    typedef priority_queue<int, vector<int>, .........> DijkstraPriorityQueue;


    vector<float>         distTo; // distTo[u] is the distance of the shortest s->u path 
    DijkstraPriorityQueue PQ;     // Min-Priority Queue, implemented for Dijkstra
};

Dijkstra.cpp

Dijkstra::Dijkstra(Graph G, int s)
{
     PQ = DijkstraPriorityQueue(...........);
}

can random C++ 2011 standard functions be called from a C routine?

I need to generate a random integer from a range and have found very interesting what is discussed here in the answer by @Walter. However, it is C++11 standard and I need to use C, is there a way of making the call from C? I reproduce his answer here:

#include <random>

std::random_device rd;     // only used once to initialise (seed) engine
std::mt19937 rng(rd());    // random-number engine used (Mersenne-Twister in this case)
std::uniform_int_distribution<int> uni(min,max); // guaranteed unbiased

auto random_integer = uni(rng);

passing template args to std::thread

Im having a little problem passing the args to my std::thread that calls the template function.

template <typename F, typename... A>
void start(int interval, F func, A&&... args)
{
    if (_running.load(std::memory_order_acquire)) {
        stop();
    };
    _running.store(true, std::memory_order_release);
    _thread = std::thread([this, interval, func, args]()
    {
        while (_running.load(std::memory_order_acquire))
        {
            func(std::forward<A>(args)...);

            for (int i = 0; (i <= (interval / 200)) && _running.load(std::memory_order_acquire); i++)
                std::this_thread::sleep_for(std::chrono::milliseconds(200));
        }
    });
}

edit: Added a little more detail I should be able to pass any function to "start" with any ammount or args

void ThreadProc(HWND hwnd)
{
    Beep(1000, 100);
}

start(2000, ThreadProc, hwnd);

error:

error C3520: 'args': parameter pack must be expanded in this context
    note: see reference to function template instantiation 'void CallBack::start<void(__cdecl *)(HWND),HWND&>(int,F,HWND &)' being compiled
    1>          with
    1>          [
    1>              F=void (__cdecl *)(HWND)
    1>          ]

vendredi 26 février 2016

Compile-time literal string as template argment

I'm trying to convert a C++ literal string into an instance of the following template:

template <char ... C>
struct string_literal {
    typedef string_constant type;
    static constexpr const char value[sizeof...(C)] = {C...};
    constexpr operator const char* (void) const {
        return value;
    }
};
template <char ... C>
constexpr const char string_literal<C...>::value[sizeof...(C)];

I came up with these helpers based on various sources for 'unpacking' the quoted string value into the template above.

template <unsigned N, const char (&S) [N], typename U>
struct selector;

template <unsigned N, const char (&S) [N], unsigned ...I>
struct selector<N, S, index_sequence<I...>> {
    using type = string_literal<S[I]...>;
};

template <unsigned N, const char (&S) [N]>
struct unpack {
    using type = typename selector<N, S, make_index_sequence<N>>::type;
};

However, when a call this I get a compiler error:

template <unsigned N>
constexpr auto make_string_literal(const char (&s) [N]) {
    return unpack<N, s>{}; // Error here
}

constexpr auto literal = make_string_literal("test");
// string_literal<'t','e','s','t','\0'>

GCC 4.9+ reports: error: 'const char (& s)[1]' is not a valid template argument for type 'const char (&)[1]' because a reference variable does not have a constant address

Clang 3.7.1 reports: error: non-type template argument refers to object 's' that does not have linkage

I tried a few different approaches but the errors are mostly the same. What am I missing here?

Forwarding references and template templates

Consider these two template functions:

template<typename T>
void foo(T&& bar) {
    // do stuff with bar, which may or may not be an instance of a templated class
}

template<typename U, template<typename> class T>
void foo(T<U>&& bar) {
    // do stuff with bar, which must be an instance of a templated class
}

Why does the former accept lvalues (by using a forwarding reference) while the latter does not?

Why will for-loop with multithreading not have as great performance as with single-thread?

I believed it was better to process simple and heavy works (ex. matrix-calculation) with multi-threading than with single-thread, so I tested the following code :

int main()
{
    constexpr int N = 100000;

    std::random_device rd;
    std::mt19937 mt(rd());
    std::uniform_real_distribution<double> ini(0.0, 10.0);

    // single-thread
    {
        std::vector<int> vec(N);
        for(int i = 0; i < N; ++i)
        {
            vec[i] = ini(mt);
        }

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

        for(int i = 0; i < N; ++i)
        {
            vec[i] = 2 * vec[i] + 3 * vec[i] - vec[i];
        }

        auto end = std::chrono::system_clock::now();
        auto dur = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
        std::cout << "single : " << dur << " ms."<< std::endl;
    }

    // multi-threading (Th is the number of threads)
    for(int Th : {1, 2, 4, 8, 16})
    {
        std::vector<int> vec(N);
        for(int i = 0; i < N; ++i)
        {
            vec[i] = ini(mt);
        }

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

        std::vector<std::future<void>> fut(Th);
        for(int t = 0; t < Th; ++t)
        {
            fut[t] = std::async(std::launch::async, [t, &vec, &N, &Th]{
                for(int i = t*N / Th; i < (t + 1)*N / Th; ++i)
                {
                    vec[i] = 2 * vec[i] + 3 * vec[i] - vec[i];
                }
            });
        }
        for(int t = 0; t < Th; ++t)
        {
            fut[t].get();
        }

        auto end = std::chrono::system_clock::now();
        auto dur = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
        std::cout << "Th = " << Th << " : " << dur << " ms." << std::endl;
    }

    return 0;
}

The execution environment :

OS : Windows 10 64-bit
Build-system : Visual Studio Community 2015
CPU : Core i5 4210U

When building this program in the Debug mode, the result was as I expected :

single : 146 ms.
Th = 1 : 140 ms.
Th = 2 : 71 ms.
Th = 4 : 64 ms.
Th = 8 : 61 ms.
Th = 16 : 68 ms.

This says that the code not using std::async justly has same performance as one using one-thread and when using 4 or 8 threads I can get great performance.

However, when in the Release mode, I got a different result (N : 100000 -> 100000000) :

single : 54 ms.
Th = 1 : 443 ms.
Th = 2 : 285 ms.
Th = 4 : 205 ms.
Th = 8 : 206 ms.
Th = 16 : 221 ms.

I'm wondering this result. Just for the latter half codes, multi-threading just has better performance than single. But the fastest one is the first half codes, which do not use std::async. I know the fact that optimization and overhead around multithreading has much effect on the performance. However,

  • The process is just calculation of the vector, so what can be optimized not in the multi-thread codes but in the single-thread codes?
  • This program contains nothing about mutex or atomic etc, and data conflict might not occur. I think overheads around multithreading would be relatively small.
  • CPU utilization in the codes not using std::async is smaller than in the multi-threading codes. Is it efficient to use the large part of CPU?