jeudi 30 avril 2015

Using microsoft compiler with another IDE

There are some topics on replacements for Visual Studio, here. What I need is 1) 2013 compiler which supports C++-11 and 2) light IDE. Please ignore cygwin for g++ on windows.

As you know, the visual studio express installation media is 6.5GB! and I wonder why on earth, the express edition need 6.5GB?! Yes disk is cheap but I think Microsoft is so lazy to optimize their applications....

how to limit the number of inputs for the following code? c++

so basically this code below is nothing but three stores from which user buys guns. user has to press exit to get out of one store and go into other.

I want to put a limit on the user that he can overall buy only 10 guns collectively from all three sections.

For example, if the user buys 10 guns from the first store buying from the other stores process should be skipped then. And suppose if the user buys 6 guns from first store and 4 from the other then the third store should be skipped.

Any ideas how to implement this?

cout<<endl<<"enter the guns you want from store 1 and press exit to buy from other sstore"<<endl;
cin>>a;

while(a!="exit")
{
    tmp = false;
    for(map<string,int> :: const_iterator it = storeone.begin(); it != storeone.end(); ++it)
    {  
        if(it->first == a)
        {
            b=it->second;
            setfinalguns(a,b);
            cout<<"you bought "<<a<<" for price "<<b<<endl;
            spentmoney(b);
            tmp = true;
            break;
        }
    }
    if(!tmp)
        cout<<"This gun is not available"<<endl;
    cin>>a;

} 

cout<<"enter the items you want to  from store two and press exit to buy from other store"<<endl;
cin>>c;
while(c!="exit")
{
    tmp = false;
    for(map<string,int> :: const_iterator it = stroretwo.begin(); it != storetwo.end(); ++it)
    {
        if(it->first == c)
        {
            d=it->second;
            setfinalguns(c,d);
            cout<<"you bought "<<c<<" for price "<<d<<endl;
            spentmoney(d);
            tmp = true;
            break;
        }
    }
    if(!tmp)
        cout<<"Thisgun is not available"<<endl;
    cin>>c;

} 

cout<<"enter the guns you want from store three and press exit to buy from other store"<<endl;
cin>>e;
while(e!="exit")
{
    tmp = false;
    for(map<string,int> :: const_iterator it = storethree.begin(); it != storethree.end(); ++it)
    {
        if(it->first == e)
        {
            f=it->second;
            setfinalguns(e,f);
            cout<<"you bought "<<e<<" for price "<<f<<endl;
            spentmoney(f);
            tmp = true;
            break;
        }
    }
    if (!tmp)
        cout<<"This gun is not available"<<endl;
    cin>>e;
    break;
}

how to set conditions of the following code? ++

so basically this code below is nothing but three stores from which user buys guns. user has to press exit to get out of one store and go into other.. i want put a limit on the user that he can overall buy only 10 guns collectively from all three sections.. for example if user buys 10 guns from first store buying from the other stores process should be skipped then.. and suppose if the user buys 6 guns from first store and 4 from the other then the third store should be skipped.. any ideas how to implement this?

  cout<<endl<<"enter the guns you want from store 1 and press exit to buy from other sstore"<<endl;
    cin>>a;

     while(a!="exit")
  {
    tmp = false;
   for(map<string,int> :: const_iterator it = storeone.begin(); it != storeone.end(); ++it)
   {  
     if(it->first == a)
     {
         b=it->second;
        setfinalguns(a,b);
        cout<<"you bought "<<a<<" for price "<<b<<endl;
        spentmoney(b);
        tmp = true;
        break;
    }
}
if (!tmp)
   cout<<"This gun is not available"<<endl;
    cin>>a;

 } 

  cout<<"enter the items you want to  from store two and press exit to buy from other store"<<endl;
  cin>>c;
  while(c!="exit")
 {
   tmp = false;
  for(map<string,int> :: const_iterator it = stroretwo.begin(); it != storetwo.end(); ++it)
  {
    if(it->first == c)
    {
        d=it->second;
        setfinalguns(c,d);
        cout<<"you bought "<<c<<" for price "<<d<<endl;
        spentmoney(d);
        tmp = true;
        break;
    }
}
if (!tmp)
   cout<<"Thisgun is not available"<<endl;
    cin>>c;

 } 

   cout<<"enter the guns you want from store three and press exit to buy from other store"<<endl;
   cin>>e;
   while(e!="exit")
 {
   tmp = false;
  for(map<string,int> :: const_iterator it = storethree.begin(); it != storethree.end(); ++it)
  {
    if(it->first == e)
    {
        f=it->second;
        setfinalguns(e,f);
        cout<<"you bought "<<e<<" for price "<<f<<endl;
        spentmoney(f);
        tmp = true;
        break;
    }
}
if (!tmp)
   cout<<"This gun is not available"<<endl;
   cin>>e;
   break;
 }

Move a chunk of text within a std::string to the left by X amount of chars

What is an efficient way to shift the text within a std::string, starting at some offset, to the left by X amount of characters?

Example:

[Some sTring here]

Shifted to the left by 1, starting at T, would yield:

[Some Tring here]

Background Info

I'm writing a compiler in C++ for a small text templating language, in which text of the form:

{some expression here}

represent expressions to be replaced with some value. Those expressions can appear interspersed with text; something like the following:

There are {$count} types of things.

The above would be replaced with something like the following, after the text is evaluated by the compiler.

There are 42 types of things.

I'm doing all the processing of the text within a std::string object. Basically, calling std::replace() alot.

Now, I want support the ability to 'escape' expressions, so that text that would normally represent expressions can be written verbatim. So this:

There are \{$count} types of things.

would be outputted like this:

There are {$count} types of things.

Basically, all that needs to happen is for the text after There are to be moved by 1 byte to the left. I was trying to think of an efficient way to do this. I wish I could memmove std::string's data buffer from '{...' by 1 byte to the left, but I'm not sure if that's possible. So, I'm hoping there is a better way than to do something like this:

auto s = buffer.size()
auto temp = buffer.substr(bracePos, s - bracePos)
buffer.assign(temp, bracePos - 1)
buffer.resize(s - 1)

Is there a better way to do this? I hate the idea of copying a big chunk of a string just to move the contents to the left by 1 character.

Iterating a huge std::vector of std::vectors and modifying elements

I have to iterate a huge std::vector vec, it is defined as follows:

std::vector<std::vector<int>> vec;

Since I have to modify elements of vec multiple times depends on flag I have to create another vector as follows:

std::vector<std::vector<int>> eVecTemp;

And how I am populating eVecTemp is shown below:

for(auto &x: vec)
 {
    std::vector<int> pers_vec(x);
    int arry[]={4,5,6,7}
    while(i < 4)
    {
        int candidate=arr[i];   

        if( !flag )
        {
            x.push_back(candidate);
            flag=true;                        
        }
        std::vector<int> new_vec(pers_vec);
        new_vec.push_back(candidate);
        eVecTemp.emplace_back(new_vec);
    }
    ++i;
}

I feel there may be better implementation possible for the following snippets, any suggestions please.

std::vector<int> new_vec(pers_vec);
new_vec.push_back(candidate);
eVecTemp.emplace_back(new_vec);

Can someone provide me with a simple example of a unique_ptr being set and retrieved

How would i write the following with smart ptrs:

class App
{
    Project* GetProject();
    SetProject(Project* project);
}

Project project = new Project();
App app = new App();

app.SetProject( project );
Project* project = app.GetProject();

This is related to this question: Should i stop using * pointers? - A few entry questions

I am slightly confused at what the rules are now... Thanks in advance!

Should i stop using * pointers?

I am writing a new application and want to start getting into C++ 11.

I have 2 questions:

Q1:

Should i not be using * nowadays?

I can see that the unique_ptr<Type> varName( new Type() ) seems to be preferred?

Q2:

If the above is true, is something like this correct:

h:

class App : public BaseClass
{
    // Methods
public:

    App();
    ~App();

private:

    // Properties
public:

    unique_ptr<WindowInfo> GetMainWindowInfo() const;
    void SetMainWindowInfo( unique_ptr<WindowInfo> windowInfo );

private:

    unique_ptr<WindowInfo> mainWindowInfo;

};

cpp:

App::App()
{
    // Set up the main app window
    unique_ptr<WindowInfo> windowInfo( new WindowInfo() );

    windowInfo->SetTitle( L"Blah" );
    windowInfo->SetHeight( CW_USEDEFAULT );
    windowInfo->SetWidth( CW_USEDEFAULT );

    this->SetMainWindowInfo( windowInfo );
}

App::~App()
{  
    // Probs don't need this anymore right?
    delete this->mainWindowInfo;
    this->mainWindowInfo = nullptr;
}

unique_ptr<WindowInfo> App::GetMainWindowInfo() const
{
    return this->mainWindowInfo;
}

void App::SetMainWindowInfo( unique_ptr<WindowInfo> windowInfo )
{
    this->mainWindowInfo = windowInfo;
}

The user of App is that it will be a way of getting all that information about my main window, thus it could be used throughout my application...

Implicit conversion differene between std::iterator and std::reverse_iterator

So, I just noticed that, for some reason, std::const_reverse_iterator is implicitly converted to std::reverse_iterator but std::const_iterator is not implicitly converted to std::iterator in my example. I am using cbegin and crbegin to retrieve const iterators from my vector:

#include <vector>
int main()
{
    typedef std::vector< int > Vector_t;
    Vector_t Vector;

    Vector_t::iterator          Iterator1  = Vector.cbegin();   // error
    Vector_t::reverse_iterator  Iterator2  = Vector.crbegin();  // ok
}

Why is this? Shouldn't the rules be the same for forward- and reverse iterators?

How to write one line and nested 'if' statement without '?:' (is it possible?)

Is it possible to write a one line if-else statement (i.e. only using one ;) without using the ?: expression? For instance something of the form: if (p == 1) " " else "\n";

Potential purpose could be: cout << if (p == 1) " " else "\n";

Just curious if this is possible, don't know if there are any practical applications for this.

Thanks

How to construct a vector with unique pointers

I try to construct a vector with unique_ptr. But I do not find a direct way. The following code does not compiles. The error is:Call to implicitly-deleted copy constructor of 'std::__1::unique_ptr >':

#include <iostream>
#include <memory>
#include <utility>
#include <vector>
class test1{
public:
    test1(){};
    test1(test1&&)=default;
};

int main(int argc, const char * argv[]) {
    std::unique_ptr<test1> us(new test1());
    std::vector<std::unique_ptr<test1>> vec{move(us)};
    return 0;
}

Insertion in an unordered_multimap

The following code compiles:

unordered_multimap<int, string> Map;
Map.insert( {{1, "1"}, {1, "1"}} );

... but this does not:

unordered_multimap<int, string> Map;
Map.insert( {{1, "1"}} );

I use VS13 and the error I get is

test.cpp(1170): error C2668: 'std::unordered_multimap<int,std::string,std::hash<int>,std::equal_to<_Kty>,std::allocator<std::pair<const _Kty,_Ty>>>::insert' : ambiguous call to overloaded function
          with
          [
              _Kty=int
  ,            _Ty=std::string
          ]
          c:\program files (x86)\microsoft visual studio 12.0\vc\include\unordered_map(619): could be 'std::_List_iterator<std::_List_val<std::_List_simple_types<std::pair<const _Kty,_Ty>>>> std::unordered_multimap<_Kty,_Ty,std::hash<int>,std::equal_to<_Kty>,std::allocator<std::pair<const _Kty,_Ty>>>::insert(const std::pair<const _Kty,_Ty> &)'
          with
          [
              _Kty=int
  ,            _Ty=std::string
          ]
          c:\program files (x86)\microsoft visual studio 12.0\vc\include\unordered_map(604): or       'void std::unordered_multimap<int,std::string,std::hash<int>,std::equal_to<_Kty>,std::allocator<std::pair<const _Kty,_Ty>>>::insert(std::initializer_list<std::pair<const _Kty,_Ty>>)'
          with
          [
              _Kty=int
  ,            _Ty=std::string
          ]
          while trying to match the argument list '(initializer-list)'

Any idea what's going on??

Is it definitely illegal to refer to a reserved name?

On the std-proposals list, the following code was given:

#include <vector>
#include <algorithm>

void foo(const std::vector<int> &v) {
#ifndef _ALGORITHM
  std::for_each(v.begin(), v.end(), [](int i){std::cout << i; }
#endif
}

Let's ignore, for the purposes of this question, why that code was given and why it was written that way (as there was a good reason but it's irrelevant here). It supposes that _ALGORITHM is a header guard inside the standard header <algorithm> as shipped with some known standard library implementation. There is no inherent intention of portability here.

Now, _ALGORITHM would of course be a reserved name, per:

[C++11: 2.11/3]: In addition, some identifiers are reserved for use by C++ implementations and standard libraries (17.6.4.3.2) and shall not be used otherwise; no diagnostic is required.

[C++11: 17.6.4.3.2/1]: Certain sets of names and function signatures are always reserved to the implementation:

  • Each name that contains a double underscore _ _ or begins with an underscore followed by an uppercase letter (2.12) is reserved to the implementation for any use.
  • Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.

I was always under the impression that the intent of this passage was to prevent programmers from defining/mutating/undefining names that fall under the above criteria, so that the standard library implementors may use such names without any fear of conflicts with client code.

But, on the std-proposals list, it was claimed that this code is itself ill-formed for merely referring to such a reserved name. I can now see how the use of the phrase "shall not be used otherwise" from [C++11: 2.11/3]: may indeed suggest that.

One practical rationale given was that the macro _ALGORITHM could expand to some code that wipes your hard drive, for example. However, taking into account the likely intention of the rule, I'd say that such an eventuality has more to do with the obvious implementation-defined nature of the _ALGORITHM name, and less to do with it being outright illegal to refer to it.

I'd say that, as long as we're happy that we are going to have implementation-defined results and that we should investigate what that macro means on our implementation (if it exists at all!), it should not be inherently illegal to refer to such a macro provided we do not attempt to modify it.

So, what do you think? Does "shall not be used otherwise" include simply writing such a name? Or is it probably not intended to be so strict (which may point to an opportunity to adjust the standard wording)?

The correct syntax of this for loop statement

I have a class, something like:

class A : std::queue<double>
{
  [...]

  void foo();
};

Inside foo() I want to iterate through its elements, but I can't seem to get the syntax right.

I assumed it would be something like: for(auto elem : *this) {} but that doesn't work (a long list of compiler errors). What is the correct syntax?

Difference between the move assignment operator and move constructor?

For some time this has been confusing me. And I've not been able to find a satisfactory answer thus far. The question is simple. When does a move assignment operator get called, and when does a move constructor operator get called?

The code examples on cppreference.com yield the following interesting results:

The move assignment operator:

a2 = std::move(a1); // move-assignment from xvalue

The move constructor:

A a2 = std::move(a1); // move-construct from xvalue

So has it do to with which is implemented? And if so which is executed if both are implemented? And why is there the possibility of creating a move assignment operator overload at all, if it's identical anyway.

Rule of 5 for base/derived class

Let's say you have:

class Base 
{
public:
    virtual ~Base();
private:
    int someTrivialValue;
}
class Derived : public Base
{
}

  1. I believe creating the virtual destructor in Base is required.
  2. Since a destructor is explicity declared, a default ctor and copy/move should also be explicity defined as per the Rule of 5, even if they only contain primitive data types or even user-defined objects allocated on the stack.
  3. The default ctor, copy and move operations, they have to be explicitly defined in both the base and derived classes.
  4. It is ok to use = default for the default ctor and copy
  5. I am on VS 2013 and it does not allow using =default for move operations. So this means I have to manually write field = std::move(rhs.field) for every single variable in each class.

Please correct any of my above statements if they are incorrect.

Enable default initilizer list constructor

I believe modern C++ initializer list are very usefull for initializing structure, sometime to the point of removing the need for defining your own constructor

struct point
{
    float coord[3];
};

point p = {1.f, 2.f, 3.f}; // nice !

However, such a construction doesn't work when my structure inherit from another structure

template<typename T>
class serializable
{
    protected:
        serializable() = default;
    ...
    // other stuff
}

struct point : public serializable<point>
{
    float coord[3];
};
point p = {1.f, 2.f, 3.f}; // Doesn't work :(

I tried adding point() = default; to my point structure, but that didn't work either.

  • Work can I enable sur an initialization for my structure with inheritance ?

Gcc/G++ doesn't give correct results when compiling more than 3 times

I created a program in C for a class in my college (on Linux with gcc) that do some calculus. The program works fine the first and second time i compiled it and run it (gcc name of file -o name of output file), but the third time always gives different values without having changed any code. My question is...the problem is in gcc/g++ or in my code? On Windows under Dev-C++ it works fine no matter how many times i run it. Apologies about the indentation if it is wrong/weird i had some trouble indenting here on the site and didn't have time to pay much attention to it.

#include <stdio.h>

float bullinton(float *altobj, float *distobj, float transmissor, float receptor, int n){

int i=0,j,l,w, k=0, count_tgt=0, count_tgr=0, max_tgt=0, max_tgr=0, max=0;
float tgt[n], tgr[n], somatorio_dist=0, alt=0, maxtgt=0, maxtgr=0, soma_transmissor, soma_recetor;  //tangentes do transmissor e receptor

    //Linha de vista para o transmissor
    for(i=0;i<n;i++){
        soma_transmissor+=distobj[i];
        tgt[i]=(altobj[i]-transmissor)/(soma_transmissor);
    }

    //Linha de vista para o receptor
    for(i=n-1,k=n;i>=0;i--){
        soma_recetor+=distobj[i+1];
        tgr[i]=(altobj[i]-receptor)/(soma_recetor);
    }

    //Mostra os valores da tangente e do receptor em cada posição
    for(i=0,k=n;i<=n && k!=0;i++,k--){
        printf("A tangente do transmissor na %d posição e: %.2f\nA tangente do receptor na %d e: %.2f\n",i,tgt[i],k,tgr[i]);    
    }

    //valor maximo de tgt
    for(i=1;i<n;i++){
        if(tgt[i]>tgt[max_tgt]){
            max_tgt=i;
        }
    }   

    //valor maximo de tgr
    for(i=1;i<n;i++){
        if(tgr[i]>tgr[max_tgr]){
            max_tgr=i;
        }

    }

    //Mostra o valor maximo de tgt e tgr
    printf("O valor maximo de tgt e: %.2f\nO valor maximo de tgr e: %.2f\n",tgt[max_tgt],tgr[max_tgr]);

    if(transmissor==receptor){
        for(i=0;i<n+1;i++){
            somatorio_dist+=distobj[i];
        }
    }

    float tgtt=1/tgt[max_tgt];
    float tgrr=1/tgr[max_tgr];

    alt=somatorio_dist/(tgtt + tgrr);   

    printf("Tgtt=%.2f\nTgrr=%.2f\n",tgtt,tgrr);
    printf("Somatorio %.2f\nA altura e: %.2f\n", somatorio_dist,alt);
}

int main(){

    int i, numero_objectos=0;
    float altura_objecto[numero_objectos], distancia_objecto[numero_objectos], transmissor, receptor;


    puts("Introduza o numero de objectos: ");
    scanf("%d",&numero_objectos);

    for(i=0;i<numero_objectos;i++){
        printf("Introduza a altura para o %d objecto:\n",i+1);
        scanf("%f",&altura_objecto[i]);
    }

    for(i=0;i<numero_objectos+1;i++){
        printf("Introduza a distancia para o %d objecto:\n",i+1);
        scanf("%f",&distancia_objecto[i]);
    }

    puts("Introduza a altura do transmissor: ");
    scanf("%f",&transmissor);

    puts("Introduza a altura do receptor: ");
    scanf("%f",&receptor);

    bullinton(altura_objecto, distancia_objecto, transmissor, receptor, numero_objectos);

    return 0;
}

using std::unique_ptr pimpl with explicit default destructor [duplicate]

This question already has an answer here:

When defining the following class

class Foo 
{
public:
    Foo (void);
    ~Foo (void) = default;
protected:
    class FooImpl;
    std::unique_ptr <FooImpl> _impl;
//...
};

Foo::Foo (void) : _impl (std::make_unique <Foo> ()) {
}

I get the following error (icpc):

/home/toolworks/gcc/4.8.2/bin/../include/c++/4.8.2/bits/unique_ptr.h(65): error: incomplete type is not allowed static_assert(sizeof(_Tp)>0, ^ detected during:

instantiation of "void std::default_delete<_Tp>::operator()(_Tp *) const [with _Tp=FooImpl]" at line 184 instantiation of "std::unique_ptr<_Tp, _Dp>::~unique_ptr() [with _Tp=FooImpl, _Dp=std::default_delete]" at line 290 of "/home/toolworks/gcc/4.8.2/bin/../include/c++/4.8.2/bits/shared_ptr_base.h" instantiation of "void std::_Sp_counted_ptr<_Ptr, _Lp>::_M_dispose() [with _Ptr=Foo *, _Lp=__gnu_cxx::_S_atomic]" at line 286 of "/home/toolworks/gcc/4.8.2/bin/../include/c++/4.8.2/bits/shared_ptr_base.h" implicit generation of "std::_Sp_counted_ptr<_Ptr, _Lp>::~_Sp_counted_ptr() [with _Ptr=Foo *, _Lp=__gnu_cxx::_S_atomic]" at line 286 of "/home/toolworks/gcc/4.8.2/bin/../include/c++/4.8.2/bits/shared_ptr_base.h" instantiation of class "std::_Sp_counted_ptr<_Ptr, _Lp> [with _Ptr=Foo *, _Lp=__gnu_cxx::_S_atomic]" at line 286 of "/home/toolworks/gcc/4.8.2/bin/../include/c++/4.8.2/bits/shared_ptr_base.h" instantiation of "std::_Sp_counted_ptr<_Ptr, _Lp>::_Sp_counted_ptr(_Ptr) [with _Ptr=Foo *, _Lp=__gnu_cxx::_S_atomic]" at line 452 of "/home/toolworks/gcc/4.8.2/bin/../include/c++/4.8.2/bits/shared_ptr_base.h" instantiation of "std::__shared_count<_Lp>::__shared_count(_Ptr) [with _Lp=__gnu_cxx::_S_atomic, _Ptr=Foo *]" at line 740 of "/home/toolworks/gcc/4.8.2/bin/../include/c++/4.8.2/bits/shared_ptr_base.h" instantiation of "std::__shared_ptr<_Tp, _Lp>::__shared_ptr(_Tp1 *) [with _Tp=Foo, _Lp=__gnu_cxx::_S_atomic, _Tp1=Foo]" at line 113 of "/home/toolworks/gcc/4.8.2/bin/../include/c++/4.8.2/bits/shared_ptr.h" instantiation of "std::shared_ptr<_Tp>::shared_ptr(_Tp1 *) [with _Tp=Foo, _Tp1=Foo]" at line ... of "main.cc"

However, When I define a non-default destructor it compiles:

Foo.h

class Foo 
{
public:
    Foo (void);
    ~Foo (void);
protected:
    class FooImpl;
    std::unique_ptr <FooImpl> _impl;
//...
};

Foo.cc

Foo::~Foo (void) {

} 

it compiles. I saw at some places that said that the "=default" should compile, and it is not the same class as implicit default function (I'm new to c++11).

So, why doesn't the first Foo compiles?

Note: I' don't see how it is duplicated since I've asked about defaulted destructor, not a default destructor

Overload resolution issue in generic vector class

I have a generic vector class in which I've implemented a constructor that accepts a lambda. The idea being that the lambda is called to initialise each element in the vector, the lambda's single parameter being the element index.

However this is interfering with my "from scalar" constructor when passing a scalar of a different type than the vector's element type:

template <typename T, int N>
struct SomeVectorClass
{
    T values[N];

    SomeVectorClass() {}

    SomeVectorClass(T scalar)
    {
        for (int i = 0; i < N; i++) values[i] = scalar;
    }

    template <typename InitFunctionType>
    SomeVectorClass(InitFunctionType initFunction)
    {
        for (int i = 0; i < N; i++) values[i] = initFunction(i);
    }
};

...

SomeVectorClass<int, 2> a([&] (int i) { return i; }); // This works
SomeVectorClass<int, 2> b(123); // This works
SomeVectorClass<int, 2> c(123.f); // This causes error "called object type 'float' is not a function or function pointer"

What I was expecting for "c" was for the compiler to automatically cast 123.f to 123 and then call the "from scalar" constructor (which accepts an int in this case).

Three questions:

  1. Is the lambda constructor preferred by the overload resolution because it doesn't require casting?
  2. Is there a way to make this work without std::enable_if() or similar hacks?
  3. If not, how would I use std::enable_if() to only enable the lambda constructor if InitFunctionType is a lambda?

Thanks in advance for your time!

EDIT: Forgot to mention that I can't use std::function, for performance reasons. The class needs to be inline-friendly.

C++ range-for and boost::irange

I'm using boost::irange and created a helper function to simplify the code by removing the need for explicit template parameters. I don't understand why it doesn't work. Here's the code:

#include <iostream>
#include <boost/range/irange.hpp>

template<typename T>
boost::irange<T> range_from_zero(T limit)
{
    return boost::irange<T>(T(), limit);
}

int main() {
    size_t end = 100;
    for (auto i  : range_from_zero(0,end))
        std::cout << i << ' ';

    return 0;
}

There's a live version here http://ift.tt/1DMoQot, which produces compilation errors

prog.cpp:5:8: error: 'irange<T>' in namespace 'boost' does not name a type
 boost::irange<T> range_from_zero(T limit)
        ^
prog.cpp: In function 'int main()':
prog.cpp:12:41: error: 'range_from_zero' was not declared in this scope
     for (auto i  : range_from_zero(0,end))

If I use boost::irange directly in the range-for, then it works:

#include <iostream>
#include <boost/range/irange.hpp>

int main() {
    size_t end = 100;
    for (auto i  : boost::irange<size_t>(0,end))
        std::cout << i << ' ';

    return 0;
}

this works fine: http://ift.tt/1OI0bfd

I thought maybe is was a problem using range-for on the return of a function, but it isn't; this works using a std::vector:

#include <iostream>
#include <boost/range/irange.hpp>

template<typename T>
std::vector<T> range_from_zero(T limit)
{
    auto range = boost::irange<T>(T(), limit);
    return { std::begin(range), std::end(range) };
}

int main() {
    size_t end = 100;
    for (auto i : range_from_zero(end))
        std::cout << i << ' ';

    return 0;
}

See http://ift.tt/1DMoOgf

Any ideas, please?

What pattern to use to make chain of convertors?

Okay, I need to make chain of convertors, for example, I have a 3D vector: Vec3 and:

Vec3->[Projector]->Vec2->[Rotator]->Vec2->[Moduler]->float->[Processor]->bool

[Projector], [Rotator] and others are convertors. Convertor can have any type as input, and any type as output. And I'll build it as lib, and end user should be able to make his own convertor and add it to chain.

I've thought about double dispatch:

struct Value;

struct Convertor
{
    virtual void Convert(Value& value);
}


struct Value
{
    virtual void ConvertMe(Convertor& conv)
    {
         conv->Convert(*this);
    }
}

It allows me to give user freedom to subclass Value, but problem is: Convertor should have overload of void Convert(SpecificUserValue& value). Which is not possible with built library.

Is it possible to do such thing? If so, how?

Thank you!

What could be the possible reasons for segmentation fault?

The code snippet is following:

ValueMapIter valueIter;    
for (valueIter = activeValues->begin(); valueIter !=activeValues->end(); ++valueIter)
{
        cout << "Before First" << endl;
        cout << "sizeactivevalue:" << activeValues->size() << endl;
        cout << "first:" << valueIter->first << "Second:" << valueIter->second << endl;
}

The PROGRAM output while running with gdb is: The program outputs

Before First

sizeactivevalue:10

Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x2aaaac8ad940 (LWP 8346)]
0x000000000043e732 in ValueManager::InsertModValue (this=0xd455c90, Id=4615, PId=7753, eId=1100000010570903, iId=2, inId=44301, pe=830795, t=25, bl=2, ste=3, sde=2)
    at /home/pathtofile/valuemanager.cpp:304
304     cout << "first:" << valueIter->first << "Second:" << valueIter->second << endl; 

How can it receive a segmentation fault, while I have a local copy of ValueMapIter and it ran on the code correctly previously.

The program is multithreaded; there is only one activeValues map. The snippet is inside the InsertModValues function. The size of the activeValue map is 10 then How can the iter not have a valid first element ?

Understanding DEFER and OBSTRUCT macros

I created a small macro metaprogramming library that implements basic useful constructs such as REPEAT(times, x), IF(value, true, false), tuples, and more.

Most of my implementations work by overloading macros based upon their variadic argument count or through a counter:

// Example:
#define REPEAT_0(x) 
#define REPEAT_1(x) x REPEAT_0(x) 
#define REPEAT_2(x) x REPEAT_1(x)
#define REPEAT_3(x) x REPEAT_2(x)
// ...
// (these defines are generated using an external script)
// ...

#define REPEAT(count, x) CAT(REPEAT_, count)(x)

This works fine, but I've recently come across an extremely interesting implementation of macro recursion by Paul Fultz.

Up until the deferred expression section I had no trouble understanding his article.

I am, however, having a lot of trouble understanding the use of DEFER and OBSTRUCT properly.

Paul implements a very elegant version of REPEAT that does not require script-generated defines like this:

#define EAT(...)
#define EXPAND(...) __VA_ARGS__
#define WHEN(c) IF(c)(EXPAND, EAT)

#define REPEAT(count, macro, ...) \
    WHEN(count) \
    ( \
        OBSTRUCT(REPEAT_INDIRECT) () \
        ( \
            DEC(count), macro, __VA_ARGS__ \
        ) \
        OBSTRUCT(macro) \
        ( \
            DEC(count), __VA_ARGS__ \
        ) \
    )
#define REPEAT_INDIRECT() REPEAT

//An example of using this macro
#define M(i, _) i
EVAL(REPEAT(8, M, ~)) // 0 1 2 3 4 5 6 7

DEFER, OBSTRUCT and other utilities are implemented as such:

#define EMPTY()
#define DEFER(id) id EMPTY()
#define OBSTRUCT(...) __VA_ARGS__ DEFER(EMPTY)()
#define EXPAND(...) __VA_ARGS__

#define A() 123
A() // Expands to 123
DEFER(A)() // Expands to A () because it requires one more scan to fully expand
EXPAND(DEFER(A)()) // Expands to 123, because the EXPAND macro forces another scan


  • When the preprocessor expands a macro, the result is "painted" until the next scan - it will not expand recursively unless an additional scan occurs. Is this correct?

  • Does the EXPAND(...) macro force an additional scan? If so, does this scan allow macros to expand recursively? What's the difference btween EXPAND(...) and DEFER(id)?

    • Does DEFER force two additional scans?
  • What about the OBSTRUCT(...) macro? Does it force two additional scans?

  • Now - why is OBSTRUCT required in the recursive implementation of REPEAT? Why wouldn't DEFER or EXPAND work here?

mercredi 29 avril 2015

How to intialize the string with space in char array in mac os?

I am trying to initialize the string with space in char array in c++.

I am doing like

char arr[] = "\033E 2\r"; // it is generating the "wrong expression" error.

Please give me the idea how to initialize string with space in char array in mac os.

Thaks,

How to implement an "echo" like program in C++?

I wish to write a program main such that when I run the program, it will print :

>>./main 
hello! please enter text:
>> hi
hi
>> apple
apple
>> quit
quitting

How to do it in C++?

Compile-time integrity verification of versioned struct

I have a struct called FOO that's versioned, so we have FOO_V0, FOO_V1, and FOO_V2. This is legacy architecture so I am currently not at a liberty to change it. However, I wanted to see if I could insert some compile-time checks such as static_assert that make sure FOO_V0 + d is F00_V1 and FOO_V1 + e is FOO_V2 so the integrity is somewhat enforced. Is that possible? TIA for any feedback!

typedef struct FOO_V0
{
    UINT a;   
    BOOL b;
    LARGE_INTEGER c;
} FOO_V0;

typedef struct FOO_V1
{
    UINT a;   
    BOOL b;
    LARGE_INTEGER c;
    UINT d;
} FOO_V1;

typedef struct FOO_V2
{
    UINT a;   
    BOOL b;
    LARGE_INTEGER c;
    UINT d;
    BOOL e;
} FOO_V2;

Thanks.

C++ Error: no match for call to ‘(std::string {aka std::basic_string

When I want to use string::s(unsigned, char) to assigned s, the g++ output this error message.

There is my class:

#include <string>
using std::string;

class Screen()
{
private:
    unsigned height = 0, width = 0;
    string contents;
public:
    Screen(unsigned ht, unsigned wd): height(ht), width(wd) {contents(ht * wd, ‘ ’);}
}

Why it is wrong?

I know that it should be Screen(unsigned ht, unsigned wd): height(ht), width(wd), contents(ht * wd, ‘ ’){ }, but why I can't use the functionstring(unsigned, char) to assigned a value for a string constructed?

How to define template member functions of nested struct outside header? [duplicate]

This question already has an answer here:

I'm using the boost meta state machine and have it working, until I change the member functions to declarations and move the function definitions out of the *.h and into the *.cpp files. After doing so, I end up with undefined references.

namespace test
{
    // ...

    struct player_ : public msm::front::state_machine_def<player_>
    {
        template <class Event,class FSM>
        void on_entry(Event const& ,FSM&);

        struct Empty : public msm::front::state<> 
        {    
            template <class Event,class FSM>
            void on_entry(Event const& ,FSM&);
        };

        // ...
    };
}

The problem I end up w/ is undefined references when linking. Here is how I've tried to define the template member functions.

template <class Event, class FSM>
void player_::on_entry(Event const&, FSM&)
{
    cout << "entering: Player" << endl;
}

template <class Event, class FSM>
void player_::Empty::on_entry(Event const&, FSM&)
{
    cout << "entering: Stopped" << endl;
}

Assignment to an array subsection: am I assigning to an Rvalue here, and if so how do I fix it?

In the hope of making my Fortran code easier to port over to C++ one day, I've been working on some expression template code to provide whole-array arithmetic operators and the ability to copy from and assign to specified sections of longer arrays. Unfortunately I can't think of a way of coming to my question, without a fair bit of boilerplate code which I'll cut down as much as I can.

First of all I have a very simple 'C-style array struct' encapsulating a pointer and a length, suitable for being easily passed back and forth between the C, Fortran, C++ and Java parts of my mixed-language application:

typedef struct {
    int *p;    /*!< Pointer to the data */
    int n;     /*!< The number of elements; int, not size_t, for Fortran compatibility  */
} int_array_C;

typedef struct {
    float *p;    /*!< Pointer to the data */
    int n;       /*!< The number of elements; int, not size_t, for Fortran compatibility  */
} float_array_C;

typedef struct {
    double *p;   /*!< Pointer to the data */
    int n;       /*!< The number of elements; int, not size_t, for Fortran compatibility  */
} double_array_C;

...and so on for all the native types. I then define some very simple expression templates based on the approach suggested in the Wikipedia entry on that subject:

template <typename E, typename T_C >
class VecExpression
{
    typedef typename std::remove_pointer<decltype(T_C::p)>::type TT;
public:
    //! Returns a const reference to the i'th element in the array
    TT operator[] (int i) const noexcept 
    {
        return static_cast<E const&>(*this)[i];
    }

    //! Returns the total size of the array
    int size() const noexcept
    {
        return static_cast<E const &>(*this).size();
    }

    operator E&() { return static_cast<E&>(*this); }
    operator E const&() const { return static_cast<const E&>(*this); }
};

template <typename E1, typename T_C, typename E2, typename U_C  >
class VecSum : public VecExpression< VecSum<E1, T_C, E2, U_C>, T_C >
{
    E1 const & _u;
    E2 const & _v;
public:
    //! Constructor taking two VecExpressions
    VecSum(VecExpression<E1, T_C> const& u, VecExpression<E2, U_C> const &v) : _u(u), _v(v)
    {
        assert(u.size() == v.size());
    }

    int size() const noexcept { return _v.size(); }

    auto operator[](int i) const
        -> const decltype(_u[i] + _v[i]) { return _u[i] + _v[i]; }
                 // Automatically takes care of type promotion e.g. int to double
                 // according to the compiler's normal rules
};

template <typename E1, typename T_C, typename E2, typename U_C  >
VecSum<E1, T_C, E2, U_C> const operator+(VecExpression<E1, T_C> const &u,
                                         VecExpression<E2, U_C> const &v)
{
    return VecSum<E1, T_C, E2, U_C>(u, v);
}

To give me a way of manipulating the contents of my C-style vectors, I define some templates: one which manipulates data in a pre-existing buffer, and another which manages its own memory by using a std::vector:

template <typename T_C> class nArray : public T_C, public VecExpression<nArray <T_C>, T_C >
{                                                  // This is the 'curiously recurring template
                                                   // pattern' (CRTP)
    typedef typename std::remove_pointer<decltype(T_C::p)>::type TT;

    struct startingIndex : public T_C
    {
        size_t start;

        startingIndex(const T_C *initialiser) noexcept
        {
            *(static_cast<T_C *>(this)) = *initialiser;
        }

        nArray to(int element) noexcept
        {
            T_C::n = element - start + 1;
            nArray<T_C> newArray(*(static_cast<T_C *>(this)));
            return newArray;
        }
    };

public:
    //! Constructor to create an nArray from an array_C, without copying its memory
    nArray(T_C theArray) noexcept
    {
        T_C::p = theArray.p;
        T_C::n = theArray.n;
    }

    //! Constructor to create an nArray from an ordinary C array, without copying its memory
    template<std::size_t N>
    nArray(TT (&theArray)[N]) noexcept
    {
        T_C::p = &theArray[0];
        T_C::n = N;
    }

    nArray & operator=(VecExpression<nArray<T_C>, T_C> const& source) &
    {
        // Note that we cannot use the copy-and-swap idiom here because we don't have the means to
        // construct a new temporary memory buffer. Therefore we have to handle the assignment-to-self
        // case explicitly.
        if (&source == this) return *this;
        assert(T_C::n == source.size());
        for (int i=0; i<T_C::n; ++i) T_C::p[i] = source[i];
        return *this;
    }

    //! Copy assignment operator taking a VecExpression of a different (but compatible) type
    //! without allocating any new memory
    template <typename E, typename U_C>
    nArray operator=(VecExpression<E, U_C> const& source) &
    {
        assert(T_C::n == source.size());
        for (int i=0; i<T_C::n; ++i) T_C::p[i] = static_cast<TT>(source[i]);
        return *this;
    }

    //! Returns a non-const reference to the i'th element in the array
    TT& operator[] (int i) noexcept
    {
        return T_C::p[i];
    }

    //! Returns a const reference to the i'th element in the array
    const TT& operator[] (int i) const noexcept
    {
        return T_C::p[i];
    }

    startingIndex from(int element) const noexcept
    {
        startingIndex theNewArray(this);
        theNewArray.p = &T_C::p[static_cast<size_t>(element)];
        theNewArray.n = T_C::n - element;
        theNewArray.start = element;
        return theNewArray;
    }

    nArray to(int element) const noexcept
    {
        nArray theNewArray;
        theNewArray.p = T_C::p;
        theNewArray.n = element + 1;
        return theNewArray;
    }

    // ... and a whole bunch of other functions
};

template <typename T_C> class nVector : public nArray<T_C>
{
    typedef typename std::remove_pointer<decltype(T_C::p)>::type TT;

public:
    template<std::size_t N>
    nVector(TT (&source)[N]) 
    {
        contents.resize(N);
        update_basetype();
        std::copy(&source[0], &source[N], contents.begin());
    }

    // ...and a whole bunch of other constructors and assignment operators
    // which echo those of nArray with the additional step of resizing the
    // internal std::vector and copying the contents into it

private:
    void update_basetype() noexcept
    {
        T_C::p = contents.size() > 0 ? contents.data() : nullptr;
        T_C::n = contents.size();
    }

    std::vector<TT> contents;
};

typedef nArray<float_array_C> float_array;
typedef nVector<float_array_C> float_vector;

// ...and so on

Phew! From this point, I can do things like

float a[] = { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f };
float b[] = { 9.0f, 8.0f, 7.0f, 6.0f, 5.0f, 4.0f };

float_array aArray(a);  // The array contents aren't copied, only
float_array bArray(b);  // the pointers

float_vector aVector = aArray.from(2);  // aVector is { 3.0f, 4.0f, 5.0f, 6.0f }
float_vector bVector = bArray.to(3);    // bVector is { 9.0f, 8.0f, 7.0f, 6.0f } 
float_vector cVector = aArray.from(2).to(4) + bArray.from(1).to(3);
                                        // cVector is { 11.0f, 11.0f, 11.0f } 

...and they work a treat. Now, finally, I can come to my question. Suppose I want to assign to an array subsection, for example:

float_vector dVector(10);  // An empty 10-element array
dVector.from(3).to(5) = aArray.from(2).to(4) + bArray.from(1).to(3);

As a matter of fact if I compile in Visual C++ 2013 this works just fine, but in gcc it doesn't. Compilation fails at the assignment, with the message:

error: no match for 'operator=' (operand types are 'nArray<float_array_C>' and 'const VecSum<nArray<float_array_C>, float_array_C, nArray<float_array_C>, float_array_C>')
note: candidates are:
     < ...skipping over a long list of utterly implausible options>
note: nArray<T_C>& nArray<T_C>::operator=(const VecExpression<nArray<T_C>, T_C>&) & [with T_C = float_array_C]
note: no known conversion for implicit 'this' parameter form 'nArray<float_array_C>' to 'nArray<float_array_C>&'

Now, this error message seems to crop up on the literature when trying to assign a temporary object to a non-const reference, or when trying to make an assignment to an Rvalue, and Visual C++ is documented as being slacker with respect to this rule than gcc is (with gcc being the one that conforms to the standard, naturally). I can kind-of-understand why the compiler might regard

dVector.from(3).to(5)

as an Rvalue, even though I've bent over backwards to try to prevent it from being so. For example my startingIndex::to() method diligently returns an nArray object by value, not by reference, and if I write

auto test1 = dVector.from(3).to(5);
auto test2 = aArray.from(2).to(4) + bArray.from(1).to(3);
test1 = test2;

...then this works fine and the compiler tells me that 'test1' is an 'nArray<float_array_C>' (i.e. a float_array) exactly as it should be.

So, my question is: am I in fact guilty of trying to assign to an Rvalue here? And if I am, how can I cease doing so, while still being able to make assignments to sub-arrays in this way, or at least some similarly-readable way. I truly hope that this can be done in some way in C++, otherwise I guess I'll need to go back to Fortran-land, writing

dVector(3:5) = aArray(2:4) + bArray(1:3)

...and living happily ever after.

Why don't throw() and noexcept have any overhead

throw() was added in C++03 as an exception specifier, however it was deprecated in C++11 for the noexcept specifier.

After profiling some code to find the speed of code using throw(), noexcept and just plain functions I found that all of them had roughly the same time for the function call.

Results:

throw()       noexcept      plain old function
11233 ms      11105 ms      11216 ms
11195 ms      11122 ms      11150 ms
11192 ms      11151 ms      11231 ms
11214 ms      11218 ms      11228 ms

compiled with MinGW using g++ -o test.exe inc.cpp no.cpp -std=c++11 -O3

Here is the code I use to for profiling:

int main() {
    unsigned long long iter = (unsigned long long)1 << (unsigned long long)40;
    auto t1 = std::chrono::high_resolution_clock::now();

    for(unsigned long long i = 0; i < iter; i++)
    {
#ifdef THROW
        throw_func();
#elif defined NOEXCEPT
        noexcept_func();
#else
        std_func();
#endif
     }

     auto t2 = std::chrono::high_resolution_clock::now();

     std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count() << " ms" << std::endl;
}

The functions are defined as:

unsigned long long val = 1;

struct exception {  };

void throw_func(void) throw()
{
    if (!val++)
       throw exception();
}
void noexcept_func(void) noexcept
{
    if (!val++)
        throw exception();
}
void std_func(void)
{
    if (!val++)
        throw exception();
}

I was surprised by these results because I was under the impression that throw() and noexcept added some overhead to the function.

Why don't throw() and noexcept add any overhead to the function call as compared to the regular function call?

C++ Cannot convert lambda to std::packaged_task in std::pair

I did some testing with std::packaged_task and came accross this problem.

std::packaged_task<int(void)> task([]() -> int { return 1; });
task();

compiles and calling task() really does the lambda.
However this one does not compile:

std::pair<int, std::packaged_task<int(void)>> pair(15, []() -> int { return 15; });
pair.second();

because

error C2664: 'std::pair<int,std::packaged_task<int (void)>>::pair(const std::pair<int,std::packaged_task<int (void)>> &)': cannot convert argument 2 from 'main::<lambda_abbe6cccb9110894d95e872872ec1296>' to 'const std::packaged_task<int (void)> &'

An object containing a vector referring to another vector's content

My problem is hard to explain, so I'll take the scenario itself as example: I have a templated Matrix class, which is using a std::vector as storage.

What I'm looking for is having a "row", or "block" method, capable to return another Matrix with a smaller size, but referring to its parent.

With this piece of code:

Matrix<float> mat(2, 2);
// Filling the matrix
Matrix<float> row = mat.row(0); // returns a 1x2 matrix(row vector)
row[1] = 10; // Here I modify the row, which reflects the modifications in mat
std::cout << mat(0, 1); // prints 10

I have been thinking about multiple solutions but all of them have some non-negligible downsides. Do you have any ideas about how to achieve this? Thanks!

EDIT 1 : I forgot to precise, the behavior should be recursive, like getting a block of another block, etc.

How do I get the method pointer of a class, with multiple implementations of that method?

struct A {
    void foo(int) { printf("this is the wrong function\n"; }
    void foo() { printf("this is the right function\n"; }
}

int main() {
    auto method = &A::foo; // c++ why don't you me allow to give argument types?

    A a;
    (a.*method)()
}

I know this little example works fine with just replacing auto with an explicit type, but that is not, what I am looking for. I would like to tell c++ on the right side of the equals, which method I want.

C++11 std::thread accepting function with rvalue parameter

I have some homework, and I have troubles understanding, (probably) how passing parameters to std::thread constructor works.

Assume following code (I deleted unneeded parts)

template<typename T, typename Task>
class Scheduler
{
    private:
        typedef std::unordered_map<std::size_t, T> Results;
        class Solver
        {
            public:
            Solver(Task&& task) : m_thread(&Solver::thread_function, std::move(task))
            {
                m_thread.detach();
            }

            Solver(Solver&& solver) = default; // required for vector::emplace_back
            ~Solver() = default;

            private:
            void thread_function(Task&& task)
            {
                task();
            }
            std::thread m_thread;
        };

    public:
        Scheduler() = default;
        ~Scheduler() = default;

        void add_task(Task&& task)
        {
            m_solvers.emplace_back(std::move(task));
        }

    private:
        std::vector<Solver> m_solvers;
};

template<typename T>
struct Ftor
{
    explicit Ftor(const T& t) : data(t) { }
    T operator()() { std::cout << "Computed" << std::endl; return data; }
    T data;
};

int main()
{
    Scheduler<int, Ftor<int>> scheduler_ftor;
    Scheduler<int, std::function<int(void)>> scheduler_lambda;
    Ftor<int> s(5);
    scheduler_ftor.add_task(std::move(s));
    scheduler_lambda.add_task([](){ std::cout << "Computed" << std::endl; return 1; });
}

Why it doesn't compile? MVS2015 is complaining about

functional(1195): error C2064: term does not evaluate to a function taking 1 arguments functional(1195): note: class does not define an 'operator()' or a user defined conversion operator to a pointer-to-function or reference-to-function that takes appropriate number of arguments
note: while compiling class template member function 'Scheduler<int,Ftor<int> >::Solver::Solver(Task &&)'

While G++ 4.9.2

functional: In instantiation of ‘struct std::_Bind_simple<std::_Mem_fn<void (Scheduler<int, Ftor<int> >::Solver::*)(Ftor<int>&&)>(Ftor<int>)>’:
required from ‘void Scheduler<T, Task>::add_task(Task&&) [with T = int; Task = Ftor<int>]’

functional:1665:61: error: no type named ‘type’ in ‘class std::result_of<std::_Mem_fn<void (Scheduler<int, Ftor<int> >::Solver::*)(Ftor<int>&&)>(Ftor<int>)>’ typedef typename result_of<_Callable(_Args...)>::type result_type;

I suppose there are some problems with std::moving to std::thread.

std::function vs std::function& as a function argument

consider the three functions below,

func1(std::function<size_t(...) > f, ...);
func2(std::function<size_t(...) >& f );
func3(const std::function<size_t(...)> &f);  

For any other type of argument passing by value/copy-constructor, passing by reference and passing by const reference have a clear context and their use cases are well known.

For the case of function<> objects, would e.g. passing by const reference save time (from e.g. calling potential copy constructor) or space (no need to pass a whole function object to the stack)? How big is a function object in the first place to make it worth passing passing by const reference? my guess would be that it would roughly be the size of a pointer - is this correct?

C++: Correct syntax for friending a template type member of template parameter?

I have a class that takes a template type parameter (tTRAIT). I want to friend a template type member alias of tTRAIT, but I can't figure out the syntax. (Is this even possible?).

template <bool bBOOL>
struct SFoo {};

struct STrait
    {
        template <bool bBOOL>
        using TFoo = SFoo<bBOOL>;
    };

template <typename tTRAIT>
struct SBar
    {
        template <bool bBOOL>
        friend typename tTRAIT::template TFoo<bBOOL>;
    };

SBar<STrait> bar;

Clang's error (on the friend line) is:

error: friend type templates must use an elaborated type

I have tried exhausting all possible combinations I can think of:

friend tTRAIT::TFoo;
friend tTRAIT::template TFoo;
friend typename tTRAIT::TFoo;
friend typename tTRAIT::template TFoo;
template <bool bBOOL> friend tTRAIT::TFoo;
template <bool bBOOL> friend tTRAIT::TFoo<bBOOL>;
template <bool bBOOL> friend tTRAIT::template TFoo;
template <bool bBOOL> friend tTRAIT::template TFoo<bBOOL>;
template <bool bBOOL> friend typename tTRAIT::TFoo;
template <bool bBOOL> friend typename tTRAIT::TFoo<bBOOL>;
template <bool bBOOL> friend typename tTRAIT::template TFoo;
template <bool bBOOL> friend typename tTRAIT::template TFoo<bBOOL>;

I have also tried using using, but it doesn't seem to help.

As an ugly hack (which only works for bool parameters), I can get it to work by friending each specialization manually.

friend typename tTRAIT::template TFoo<false>;
friend typename tTRAIT::template TFoo<true >;

But that's yucky.

Does anyone know how to do this, or if this can be done?

Will I get a performance boost when compiling with a C++14 compiler instead of C++11?

I know you can get a performance boost when compiling with a C++11 compiler instead of a C++03 compiler (see this question).

But can I expect a performance boost when going from a C++11 compiler to a C++14 compiler?

GNU gcc/g++ compiler version on solaris for supporting C++11/14

I need to know the GNU gcc/g++ version alongwith gmake, gdb and other GNU build tools for upgrading to C++11 first and then to C++14. Please suggest which stable version to look at/download? I will be requiring the compiler/build suite for solaris 32-bit. Please suggest.

Variadic function calling a variadic macro

I have an inline variadic function
inline int foo(...)
I need foo() to call a macro (let's call it MACRO), which is also variadic.
Basically I need foo() to pass all its input parameters to MACRO. Redefining foo() as another macro would be an easy solution because of __VA_ARGS__ option, but I also need foo() to return a value.
Note: I am trying to interface two parts of already written code and I am not allowed to change them. foo(...) is used in the first part of code and MACRO is defined in the second part. Only thing I am supposed to do is to define a foo() which uses MACRO and I can't because they are both variadic.

Travis CI: Building c++11 with xCode

Is it possible to get travis ci running with xcode and c++11?

by travis.yml file looks like this:

language: cpp
xcode_project: PROJECT.xcodeproj
xcode_scheme: PROJECT_Schema

Do you know what's going wrong?

How to get the coefficient from a std::decimal?

Background

I want to write an is_even( decimal::decimal64 d ) function that returns true if the least-significant digit is even.

Unfortunately, I can't seem to find any methods to extract the coefficient from a decimal64.

Code

#include <iostream>
#include <decimal/decimal>

using namespace std;

static bool is_even( decimal::decimal64 d )
{
    return true;  // fix this - any way to get coefficient of d?
}
int main()
{
    auto d1 = decimal::make_decimal64( 60817ull, -4 );   // not even
    auto d2 = decimal::make_decimal64( 60816ull, -4 );   // is even

    cout << decimal64_to_float( d1 ) << " " << is_even( d1 ) << endl; 
    cout << decimal64_to_float( d2 ) << " " << is_even( d2 ) << endl;

    return 0;
}

Can I create a new syntax in C++?

I am quite fond of Python generator expression and (ab)use it a lot in Python. Now I am (up to no good) working on implementing generator expression on C++ 11, using macros embedded in macros, lambdas and more obscure things. My aim is to copy all abilities of operator as close as possible. There are some implementations already, but they lack multi-variable support.
Python most complex syntax looks like

generator = i*j for i,j in zip(arr1,arr2) if i>0 and j>0 # Python

This line produces a functor that returns on every successfull call a multiplication of repective values from two arrays. And in my realization syntax now looks like

auto generator = brf_genexpr(i*j,(i,j),zip(arr1, arr2),i>0 && j>0); //C++11

My question is: do you know some way, however exotic, to get rid of those lots of commas and allow me to write

auto generator = brf_genexpr(i*j for i,j in zip(arr1,arr2) if (i>0 && j>0));

I do understand that I can write a preprocessor script that would change syntax for me, but I would love a in-code solution.

Using char16_t, char32_t etc without C++ 11?

I would like to have fixed width types including character types. stdint.h provides types for integers, but not characters, unless when using C++11, which i can't do.

Is their a clean way to define these types (char16_t, char32_t, etc) without conflicting with those defined by C++11 in case the source would ever be mixed with C++11 ?

Thank you :)

Compilation issue with instantiating function template

Consider the following code:

#include <iostream>

struct S {
  void f(const char* s) {
    std::cout << s << '\n';
  }
};

template <typename... Args, void(S::*mem_fn)(Args...)>
void invoke(S* pd, Args... args) {
  (pd->*mem_fn)(args...);
}

int main() {
  S s;
  void(*pfn)(S*, const char*) = invoke<const char*, &S::f>;
  pfn(&s, "hello");
}

When compiling the code, clang gives the following error:

main.cpp:16:33: error: address of overloaded function 'invoke' does not match required type 'void (S *, const char *)'
  void(*pfn)(S*, const char*) = invoke<const char*, &S::f>
                                ^~~~~~~~~~~~~~~~~~~~~~~~~~
main.cpp:10:6: note: candidate template ignored: invalid explicitly-specified argument for template parameter 'Args'
void invoke(S* pd, Args... args) {
     ^
1 error generated.

The message seems to suggest that the template instantiation invoke<const char*, &S::f> has failed. Could somebody give me some clues as to why is this? I believe it has something to do with the parameter pack.

Is there a way to call an initialization function only when specific class template (specialization) is instantiated?

I'm designing a wrapper over various computational functionality. Some of the underlying backends require some init functions to be called before any other API calls are made. I could use some static variable that is initialized before main, and wrap it in some function as described here so that I can catch any errors produced during initialization.

I wonder if there is a better way to handle this. Note that there will never be an instance of the class template, as everything is either a typedef or static member.

How to use QtConcurrent to qCompress on QByteArray?

I want to write a little program which compress all files from a directory by using qCompress of QByteArray.

However i want to run the compression on a multithreaded environment by using QtConcurrent. But i have some problems.

Here my code :

FilePool pool(folder,suffix);
QFutureWatcher<QString> watcher;
QProgressDialog progressDialog;


connect(&watcher,SIGNAL(progressRangeChanged(int,int)),&progressDialog,SLOT(setRange(int,int)));

connect(&watcher,SIGNAL(progressValueChanged(int)),&progressDialog,SLOT(setValue(int)));

connect(&progressDialog,SIGNAL(canceled()),&watcher,SLOT(cancel()));

QFuture<QString> future = QtConcurrent::filtered(pool,FindInFile(search));
QString text;

watcher.setFuture(future);

progressDialog.exec();

future.waitForFinished();
//Test for compressing file

QFile outFile("testCompress.ecf");
outFile.open(QIODevice::WriteOnly);
QByteArray nonCompressedData;
foreach(const QString &file,future.results()){
    //Fichier d'entrée
    QFile inFile(file);
    inFile.open(QIODevice::ReadOnly);
    nonCompressedData.append(inFile.readAll());
    inFile.close();
    text += file + "\n";
}

//QByteArray compressedData(qCompress(nonCompressedData,9));
//PROBLEM HERE
QFuture<QByteArray> futureCompressor = QtConcurrent::filtered(nonCompressedData,qCompress);
futureCompressor.waitForFinished();
QByteArray compressedData = futureCompressor.results();

outFile.write(compressedData);

The problem is that the compiler raise me an errors

First : No matching function for call to filtered(&QByteArray,).

Second : converstion from QList to non scalar type QByteArray requested.

So, my question is,is it possible to do what i want?

Thanks in advance

I have list of MyStruct objects.

struct Task {
    std::function<void()> _fn = nullptr;
    std::chrono::system_clock::time_point _execTime;
};

How to find minimum value of _execTime in list using STL algorithm ? I can find with iteration, but is there more elegant way to do this? Something like below:

std::chrono::system_clock::time_point nearestExecTime = std::min(auto t = tasks.begin(), auto p = tasks.end(), [t,p]() {return t.execTime < p.exeTime;});

Implementing Min priority Queue(C++ STL) using user-defined objects

I am implementing Prims Algorithm. I have a vector of Edges along with their weights. The problem is, after inserting, the queue does not remain in increasing order according to weight of edges.

The relevant code is given below:-

struct weightcomp // To be used solely for priority Queue...
{
    bool operator()(Edge &E1, Edge &E2)
    {
        if(E1.weight > E2.weight)
            return true;
    }
};

std::priority_queue<Edge,std::vector<Edge>,weightcomp> PQ; // Priority Queue for Edges

void visit(std::vector<Edge> &PMST, int i) // PMST = Vector of edges and i = name of node
{
    for(auto iter = PMST.begin();iter != PMST.end();++iter)
    {
        if((*iter).u == i || (*iter).v == i)
        {
            PQ.push((*iter));
            (*iter).del = true;  // Mark the vectors elements to be removed.
        }
    }

    PMST.erase(std::remove_if(PMST.begin(),PMST.end(),[](Edge e){ return e.del;}),PMST.end()); // Delete the marked elements
}

What am I missing in the implementation?

vector of unique_ptr in C++11

I recently switched to C++11 and I'm trying to get used to good practices there. What I end up dealing with very often is something like:

class Owner
{
private:
    vector<unique_ptr<HeavyResource>> _vectorOfHeavyResources;
public:
    virtual const vector<const HeavyResource*>* GetVectorOfResources() const;
};

This requires me to do something like adding a _returnableVector and translating the source vectors to be able to return it later on:

_returnableVector = vector<HeavyResource*>;
for (int i=0; i< _vectorOfHeavyResources.size(); i++)
{
    _returnableVector.push_back(_vectorOfHeavyResources[i].get());
}

Has anyone noticed similar problem? What are your thoughts and solutions? Am I getting the whole ownership idea right here?

How to set a bunch of pointers to NULL in C++ 11?

I've got a bunch of pointers with different types and need to set all to NULL but i don't want to do it manually.

How to do it using for loop?

How to make the statement shorter:

auto ptr = std::shared_ptr<CPoint>(new CPoint(x, y));

Please notice the CPoint appears twice. Can it be shorter?

like:

auto ptr = XXXX<CPoint>(x, y);

XXXX is a macro or anything. It should apply to any constructor with any parameters.

auto ptrA = XXXX<ClassA>(); // a shared_ptr to new ClassA()
auto ptrB = XXXX<ClassB>(a, b, c); // a shared_ptr to new ClassB(a, b, c)

mardi 28 avril 2015

Input using getline(cin,n); is not printing first input and i am not using cin>> to take input anywhere

I am trying to print inputs until user gives a blank input.So,I used getline(cin,input).But,When i use getline(cin,input).It is skipping first input while giving output.

#include <iostream>
using namespace std;
int main() {
    while(1)
    {
        string n;
        getline(cin, n);
        while(getline(cin,n) && !n.empty())
        {
            cout<<n<<endl;;
        }
        if(n.empty())
            break;
    }
    return 0;
}

sample input:

12 2

output obtained:

2

output needed:

12 2

Returning value from shared pointer vector string

I'm trying to implement a return method for a class I want to use smart pointers. I have:

std::shared_ptr<std::vector<std::string>> data;

I want to access its last value with this function:

std::string& rear()
    {

    };

How do I access values with the shared_ptr?

How can I use C++11's range-based for loop to output data in a table?

This is my code:

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

int main()
{
    // array< int, 5 > n;
    int n [ 5 ] = { 2, 4, 6, 8, 10};

    cout << "Element" << setw(13) << "Value" << endl;

    for ( int j : n )
    {
        cout << setw(7) << j << setw(13) << n[ j ] << endl;
    }
}

It produced this output:

Element        Value
      2            6
      4           10
      6  -1078585116
      8  -1217581056
     10            0

While I expected this output:

Element        Value
      1            2
      2            4
      3            6
      4            8
      5           10

I've tried changing small things, but they didn't work. Where did I do wrong?

Why does creating a C++11 thread cause a Fatal Signal?

I want to create a C++11 thread that runs indefinitely, after a JNI call has been made. Why does this generate a Fatal Signal?

#include <thread>

static void teste()
{
    while(true)
        LOGI("IN TEST");
}

JNIEXPORT void Java_blahblah(JNIEnv *javaEnvironment, jobject self)
{
    std::thread t(teste);
    //t.join(); //I don't want to join it here.
}

I don't need the C++11 thread to call JNI or anything like that.

Readers / writer implementation using std::atomic (mutex free)

Below is an attempt at a multiple reader / writer shared data which uses std::atomics and busy waits instead of mutex and condition variables to synchronize between readers and writers. I am puzzled as to why the asserts in there are being hit. I'm sure there's a bug somewhere in the logic, but I'm not certain where it is.

The idea behind the implementation is that threads that read are spinning until the writer is done writing. As they enter the read function they increase m_numReaders count and as they are waiting for the writer they increase the m_numWaiting count.

The idea is that the m_numWaiting should then always be smaller or equal to m_numReaders, provided m_numWaiting is always incremented after m_numReaders and decremented before m_numReaders.

There shouldn't be a case where m_numWaiting is bigger than m_numReaders (or I'm not seeing it) since a reader always increments the reader counter first and only sometimes increments the waiting counter and the waiting counter is always decremented first.

Yet, this seems to be whats happening because the asserts are being hit. Can someone point out the logic error, if you see it?

Thanks!

#include <iostream>
#include <thread> 
#include <assert.h>

template<typename T>
class ReadWrite
{

public:

    ReadWrite() : m_numReaders(0), m_numWaiting(0), m_writing(false)
    {
        m_writeFlag.clear();
    }

    template<typename functor>
    void read(functor& readFunc)
    {
        m_numReaders++;
        std::atomic<bool>waiting(false);
        while (m_writing)
        {
            if(!waiting)
            {
                m_numWaiting++; // m_numWaiting should always be increased after m_numReaders
                waiting = true;
            }
        }

        assert(m_numWaiting <= m_numReaders);

        readFunc(&m_data);

        assert(m_numWaiting <= m_numReaders); // <-- These asserts get hit ?

        if(waiting)
        {
            m_numWaiting--; // m_numWaiting should always be decreased before m_numReaders
        }

        m_numReaders--;

        assert(m_numWaiting <= m_numReaders); // <-- These asserts get hit ?
    }

    //
    // Only a single writer can operate on this at any given time.
    //
    template<typename functor>
    void write(functor& writeFunc)
    {
        while (m_writeFlag.test_and_set());

        // Ensure no readers present
        while (m_numReaders);

        // At this point m_numReaders may have been increased !
        m_writing = true;

        // If a reader entered before the writing flag was set, wait for
        // it to finish
        while (m_numReaders > m_numWaiting);

        writeFunc(&m_data);

        m_writeFlag.clear();
        m_writing = false;
    }
private:
    T m_data;
    std::atomic<int64_t> m_numReaders;
    std::atomic<int64_t> m_numWaiting;
    std::atomic<bool> m_writing;
    std::atomic_flag m_writeFlag;
};

int main(int argc, const char * argv[])
{
    const size_t numReaders = 2;
    const size_t numWriters = 1;
    const size_t numReadWrites = 10000000;

    std::thread readThreads[numReaders];
    std::thread writeThreads[numWriters];

    ReadWrite<int> dummyData;

    auto writeFunc = [&](int* pData)    { return; }; // intentionally empty
    auto readFunc = [&](int* pData)     { return; }; // intentionally empty

    auto readThreadProc = [&]()
    {
        size_t numReads = numReadWrites;
        while (numReads--)
        {
            dummyData.read(readFunc);
        }
    };

    auto writeThreadProc = [&]()
    {
        size_t numWrites = numReadWrites;
        while (numWrites--)
        {
            dummyData.write(writeFunc);
        }
    };

    for (std::thread& thread : writeThreads)    { thread = std::thread(writeThreadProc);}
    for (std::thread& thread : readThreads)     { thread = std::thread(readThreadProc);}
    for (std::thread& thread : writeThreads)    { thread.join();}
    for (std::thread& thread : readThreads)     { thread.join();}
}

Can I disable copy construction of a class based on the properties of it's template parameters? [duplicate]

This question already has an answer here:

A variant is the obvious example for this:

template <typename... Ts>
class variant {
  using types = meta::list<Ts...>;

  variant() = default;

  template <typename = std::enable_if_t<
    meta::all_of<types, meta::quote<std::is_copy_constructible>>{}
  >
  variant(const variant &);
};

Using Meta to remove TMP boilerplate code around checking to see if all of a parameter pack fulfil a trait.

I know this isn't correct as the copy constructor can't be templated amongst other restrictions. Is this something that is possible to do in a different manner? C++14+ should be fine as I'm using GCC 4.9 and Clang 3.5.

Controversial results between GCC and clang related to [basic.link]/7 in the C++ Standard

This snippet compiles in clang,

namespace A {
    void f() {
        void g();
        g();
    }
}

void A::g() { }

but GCC only accepts the code if g is defined inside the namespace A as follows:

namespace A {
    void f() {
        void g();
        g();
    }
    void g() {}
}

But I believe there's nothing in [basic.link]/7 disallowing the first snippet above.

Insert in unordered map calls constructor

In order to avoid duplication of elements, I'm building a class that holds elements and provide an acces to them.

My elements (DynLibrary) are movable but not copyable

class DynLibrary
{
    public:
        DynLibrary() : _handle(nullptr) {}
        DynLibrary(const std::string& path) { DynLibrary::open(path); }
        DynLibrary(const DynLibrary&) = delete;
        DynLibrary(DynLibrary&&) = default;
        ~DynLibrary() { DynLibrary::close(); }
    ...
}

Those object are allocated in an unordered_map which key is the path that generated them. I'm allocation them that way

class DynAllocator
{
    public:
        DynLibrary& library(const std::string& f)
        {
            if (_handles.find(f) == _handles.end())
            {
                std::cout << "@Emplace" << std::endl;
                _handles.emplace(f, DynLibrary(f));
            }
            std::cout << "@Return" << std::endl;
            return _handles.at(f);
        }
    private:
        std::unordered_map<std::string, DynLibrary> _handles;
};

However when calling DynAllocator::library I get the following output:

@Emplace
close 0x1dfd1e0 // DynLibrary destructor
@Return

Which means that the object which is inserted has somehow been copied and the destructor of the copy just invalidated my object (calling dlclose with my handler)

  • Is my movable but not copyable approach of DynLibrary ok ?
  • How can I insert an instance of DynLibrary if my unordered_map without copy ?

Please note that I know how to do that using pointers / smart pointers (std::unique_ptr) but that i'd like to avoid them at all cost !

Performance with value semantics

I am very concerned about performance and readability of the code and I get most of my ideas from Chandler Carruth from Google. I would like to apply the following rules for C++ for clean code without loosing performance at all.

  • Pass all POD as values
  • Pass all objects that you don't want to mutate by const reference
  • Pass all objects that your function needs to consume by value
  • Ban everything else. When in corner cases, pass a pointer.

That way, functions don't have side effects. That's a must for code readability and makes C++ kind of functionnal. Now comes performance. What can you do if you want to write a function that adds 1 to every element of a std::vector? Here is my solution.

std::vector<int> add_one(std::vector<int> v) {
    ...what you expect...
}

...
v = add_one(std::move(v));
...

I find this very elegant and makes only 2 moves. Here are my questions:

  • Is it legal C++11 ?
  • Do you think of any drawback with this design?
  • Couldn't a compiler automatically transform v = f(v) into this? A kind of copy elision.

Xcode : Cannot find General Tab for Target

I'm trying to locate the general settings tab for my target to embed some binaries but I can't seem to locate it. I apologize for such a sophomoric question, but does anyone know what I'm doing incorrectly?

Furthermore can anyone recommend a good OSX IDE that doesn't obfuscate every project setting in a hundred different distributed tabs? I've used eclipse but I was trying to broaden my horizons.

enter image description here

std::condition_variable::wait_until function

I have a small question about using this method. Will my thread wake up if the std::chrono::high_resolution_clock::now() is greater then the second parameter(abs_time)?

Accessing nested template class of the template base class in a template derived class [duplicate]

This question already has an answer here:

The code below results in a compile-time error: A<T>::PortIdxType is not a type when compiled using gcc 4.9.1. Is there a way to access a nested template member class of template base class in the template derived class?

template<typename T>
class A
{
public:
    template<int N> struct PortIdxType{};
};


template<typename T>
class B: public A<T>
{
public:

    using A<T>::A;

    template<int N>
    void getter(A<T>::PortIdxType<N> q)
        {}
};

Variadic template function composition

Hoping the stackoverflow community can help me with this problem. I would like to have something like the following compile

template <typename A>  
void VARIADIC_TEMPLATE_FUNCTION(A* tptr)
{   
    //Do nothing
}   

template <typename A, typename B, typename... C>
void VARIADIC_TEMPLATE_FUNCTION(A* tptr)
{   
    // Do stuff here with typename B and tptr (not included)
    VARIADIC_TEMPLATE_FUNCTION<A,C...>(tptr);
}   

clearly this doesn't work, the signatures of the two functions conflict.

I have been attempting to fix this by passing some variadic arguments as well, but nothing seems to work. I'm not against passing "fake" variables - but prefer not to.

The caller would do something like (for example):

ClassP* ptr;
VARIADIC_TEMPLATE_FUNCTION<ClassP, ClassA, ClassB, ClassC, ClassD>(ptr);

const pointer in for loop (C++ 11)

Can someone explain me why it is possible to declare a const pointer to something that has a different value for each iteration of the loop?

#include <assimp/Importer.hpp>
...

for (int i = 0; i < N; i++) {
    const aiVector3D* vp = &(mesh->mVertices[i]);
    // use vp.x ...
}

This snippet is part of an example code of how to use assimp to import mesh-data. (i am new to c++)

C++11 atomic store

According to this http://ift.tt/1bPCDnm, a released store is implemented as MOV (into memory).

According to his http://ift.tt/1krieqi

memory_order_release:

A store operation with this memory order performs the release operation: no memory accesses in the current thread can be reordered after this store. This ensures that all writes in the current thread are visible in other threads that acquire or the same atomic variable and writes that carry a dependency into the atomic variable become visible in other threads that consume the same atomic.

I understand that memory_order_release so that when used, all memory stores done previously should finish before this one.

int a;
a = 10;
std::atomic<int> b;
b.store(50, std::memory_order_release); // i can be sure that 'a' is already 10, so processor can't reorder the stores to 'a' and 'b'

QUESTION: how is it possible that only the MOV instruction is sufficient for this behaviour? How the MOV tells the processor to finish all previous stores?

Is value returned by std::unique_ptr::get valid after moving unique_ptr?

Consider the following code snippet:

class Owner {
public:
 Owner(std::unique_ptr<int> ptr) : owned_pointer<int>(std:move(ptr)) {}
private:
 std::unique_ptr<int> owned_pointer;
};


std::unique_ptr<int> ptr(new int);
int* ptr1 = ptr.get();
Owner new_owner(std::move(ptr));

Is it safe to assume that ptr1 is valid as long as new_owner stays in scope? It seems to work, but I can't find a specification that states that explicitly - is it undefined behavior/implementation specific and just happen to work for me, or the code posted above is valid (ptr1 is guaranteed to point to moved pointer as long as it stays alive)?

Need assistance on using for loop to display my array

I'm aware the C++11 way of doing this, but I'm told to use the "traditional" way.

Anyways here's the code:

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

int main()
{
  int items[ 5 ] = {1, 2, 3, 4, 5};

  cout << "items before modification: ";
  for( unsigned int whatever = 0; whatever < sizeof(items); whatever++ )
  {
    cout << items[ whatever ] << " ";
  }
}

Here is the output:

items before modification: 1 2 3 4 5 1 -1073949596 -1073949588 -1073949744 -1217175552 0 0 -1218570461 134514560 0 0 -1218570461 1 -1073949596 -1073949588

Where did I went wrong where I'm expecting this output:

items before modification: 1 2 3 4 5

?

Qt QProccess with ping utility usage

I need some help with QProcess class' method called "execute"

I wanna know is server alive using external utility "ping" in windows7. I make:

int exitCode = QProcess::execute(QString("ping -n %1 %2").arg(packetNumber).arg(hostAddr.toString()));
if (exitCode == 0){
    // it's alive
    qDebug() << "It's alive!";
}
else{
    // it's dead
    qDebug() << "It's dead!";
}

External prints into the console some info, that I don't want see. Ideally I want to run my function (part of its body is written upper) in the child thread. Other words, I just want to get "It's dead\alive !" in console from these code lines

Template class without default constructor

I guess this has been asked before but I could not find a thread for it

Lets say that we have the class A:

Class A
{
    public:
       A() = delete;
       A( const int & y )
       : x( y )
       {}
    private:
       int x;
};

How can I create a vector of type A and give an argument to A's constructor?

Edit: I tried with std::vector<A(3)> myvector; but it did not compile...

C++ universal function caller

I'd want to implement a function caller that works just like the thread constructor. For example

std::thread second (bar,0);

will start a thread which calls bar with the single argument 0. I would like to do the same thing, but I do not know how.

For example, given:

void myFunc(int a){
    cout << a << endl;
}

I would like:

int main() {
    caller(myFunc,12);
}

to call myFunc with the parameter 12.

Any way to speed up this bit list code?

I store a variable amount of bits in a list. I need to look up the bits in the range of [i,j]. Currently I'm storing the bits in a vector of unsigned 32 bit integers.

This is how I do the lookup:

std::uint32_t
Data::findInt3(const std::vector<std::uint32_t>& input, int size, int pos) {
    pos = pos*size;
    int firstc = pos >> 5;
    int ipos = pos & 31;
    int end = ipos+size;
    std::uint64_t t = input[firstc];

    std::uint64_t num = (t << 32) | input[firstc+1];
    std::uint64_t number = num >> (64-end);
    number = number & ((1 << size)-1);

    return number;
}

This piece of code is called A LOT of times. I guess just small speed-ups will be very beneficial. Can anyone see anything which could be made better? Like shifting something instead of or'ing. Or which is faster?

Thanks

how to force clang to check semantic with system(ubuntu) STL header instead of clang's

when I try to use clang++ to detect semantic My program can be compiled with gcc. when I use clang to detect semantic, I got:

error| no viable overloaded '*='

problem occurs from one header I include from open source project

std::vector<double> Hc;
checksum(H,Hc);
Hc*=1.0/mrpt::math::maximum(Hc);

I think the problem is because the clang's STLib headers are different with my Ubuntu's c++ headers, and they didn't override *= opt. I added -std=c++11 -stdlib=libc++11 -nodefaultlibs and tried this http://libcxx.llvm.org but the only error still there. Indeed, I am trying YouCompleteMe plugin in vim. this plugin only need compile semantic and without linking step. and I can't change the header. '-isystem doesn't solve the problem' What should I do to force clang to check semantic with system STL header instead of clang's?

What's wrong with my predicate function?

I'm trying to use "remove_if" method by std::list. I wanna delete the "special" element. Here some code:

Class A {
public: 
void foo(size_t id) {
tasks.remove_if(&A::IsEqual(id)); //Here I have an error
}

private:
std::list<Task> tasks;
struct IsEqual {
    IsEqual(const Task& value) : _value(value) {}
    bool operator() (const size_t id) {
        return (_value._id == id);
    }
    Task _value;
    };
};

Could someone explain where the mistake is?

I had a small program , which was generating compilation error:

following was the program:

#include <cstdio> 
#include <sstream>
int main()
{
   std::ostrstream  strm;                         
      strm.rdbuf()->freeze(0);                      
}

and I was getting following error on compilation: g++ sample3.cpp

sample3.cpp: In function 'int main()':
sample3.cpp:5: error: 'ostrstream' is not a member of 'std'
sample3.cpp:5: error: expected `;' before 'strm'
sample3.cpp:6: error: 'strm' was not declared in this scope

After searching in google , I suspect that i should use ostringstream in place ostrstream , so I have modified the programmm as blow:

#include <cstdio> 
#include <sstream>
int main()
{
   std::ostringstream  strm;                         
      strm.rdbuf()->freeze(0);                      
}

but after modification , I started getting following error:

g++ sample3.cpp
sample3.cpp: In function 'int main()':
sample3.cpp:6: error: 'struct std::basic_stringbuf<char, std::char_traits<char>, std::allocator<char> >' has no member named 'freeze'

I tried to search in google and stackoverflow also but haven't got any idea about error , Can somebody please help me that what should I do here?

How can I explicitly view the results of type inference by auto?

I am newly studying auto feature of C++11/14.

For educational purpose, I would like to explicitly display the result of type inference of my code. I tried typeid().name(), but I found two problems with this approach.

  1. Output is sometimes difficult to understand. (For example, "NSt3__16vectorIiNS_9allocatorIiEEEE")
  2. const/volatile modifiers do not seem to be displayed.

I am using clang 6.1.0.

Understanding the gdb backtrace full report

Can somebody please help me in understanding the issue that caused this segmentation fault. This points to a place where I access an Iter to a map.

The relevant code where it points is:

cout << "Iterate the Map:" << endl;     
    for(Iter=activevalues->begin(); Iter != activevalues->end(); ++Iter)
        {
            Allactivevalues.push_back(Iter->first); [Here on this line]
        }

The gdb log report is:

(gdb) bt full

#0  0x00000000004401ac in Class::Funtion (this=0x1d16ec90) at /Address/to/file/file.cpp:784
    StdVectorVariable = {<std::_Vector_base<int, std::allocator<int> >> = {_M_impl = {<std::allocator<int>> = {<__gnu_cxx::new_allocator<int>> = {<No data fields>}, <No data fields>}, _M_start = 0x0, 
      _M_finish = 0x0, _M_end_of_storage = 0x0}}, <No data fields>}

#1  0x0000000000432633 in Class1::Function1 (this=0xdc8035d0, ssMsg=0x2aaaac8acf90 "\003") at /Address/to/file1/file1.cpp:570
    bytSend = 164
    log = {<std::basic_ostream<char, std::char_traits<char> >> = {<std::basic_ios<char, std::char_traits<char> >> = {<std::ios_base> = {_vptr.ios_base = 0x2ae764454b80, static boolalpha = <optimized out>, 
        static dec = <optimized out>, static fixed = <optimized out>, static hex = 858927408, static internal = 0, static left = <optimized out>, static oct = <optimized out>, static right = <optimized out>, 
        static scientific = <optimized out>, static showbase = <optimized out>, static showpoint = <optimized out>, static showpos = <optimized out>, static skipws = <optimized out>, 
        static unitbuf = <optimized out>, static uppercase = <optimized out>, static adjustfield = <optimized out>, static basefield = <optimized out>, static floatfield = <optimized out>, 
        static badbit = <optimized out>, static eofbit = <optimized out>, static failbit = <optimized out>, static goodbit = <optimized out>, static app = <optimized out>, static ate = <optimized out>, 
        static binary = <optimized out>, static in = <optimized out>, static out = <optimized out>, static trunc = 1141968882, static beg = <optimized out>, static cur = <optimized out>, 
        static end = <optimized out>, _M_precision = 6, _M_width = 0, _M_flags = 4098, _M_exception = std::_S_goodbit, _M_streambuf_state = std::_S_goodbit, _M_callbacks = 0x0, _M_word_zero = {_M_pword = 0x0, 
          _M_iword = 0}, _M_local_word = {{_M_pword = 0x0, _M_iword = 0}, {_M_pword = 0x0, _M_iword = 0}, {_M_pword = 0x0, _M_iword = 0}, {_M_pword = 0x0, _M_iword = 0}, {_M_pword = 0x0, _M_iword = 0}, {
            _M_pword = 0x0, _M_iword = 0}, {_M_pword = 0x0, _M_iword = 0}, {_M_pword = 0x0, _M_iword = 0}}, _M_word_size = 8, _M_word = 0x2aaaac8ace58, _M_ios_locale = {static none = -1, 
          static ctype = <optimized out>, static numeric = <optimized out>, static collate = <optimized out>, static time = 149717832, static monetary = <optimized out>, static messages = <optimized out>, 
          static all = <optimized out>, _M_impl = 0x2ae76446ab80, static _S_classic = <optimized out>, static _S_global = <optimized out>, static _S_categories = <optimized out>, static _S_once = <optimized out>}}, 
      _M_tie = 0x0, _M_fill = 32 ' ', _M_fill_init = true, _M_streambuf = 0x2aaaac8acd28, _M_ctype = 0x2ae76446ae00, _M_num_put = 0x2ae76446b120, _M_num_get = 0x2ae76446b110}, _vptr.basic_ostream = 0x2ae764454b58}, 
  _M_filebuf = {<std::basic_streambuf<char, std::char_traits<char> >> = {_vptr.basic_streambuf = 0x2ae764454970, 
      _M_in_beg = 0x2aaab00009a0 "Output:Id:31,PID:37,InId:65928,bysll:2,EhId:1100000005231634\n", 
      _M_in_cur = 0x2aaab00009a0 "Output:Id:31,PID:37,InId:65928,bysll:2,EhId:1100000005231634\n", 
      _M_in_end = 0x2aaab00009a0 "Output:Id:31,PID:37,InId:65928,bysll:2,EhId:1100000005231634\n", 
      _M_out_beg = 0x2aaab00009a0 "Output:Id:31,PID:37,InId:65928,bysll:2,EhId:1100000005231634\n", 
      _M_out_cur = 0x2aaab00009a0 "Output:Id:31,PID:37,InId:65928,bysll:2,EhId:1100000005231634\n", _M_out_end = 0x2aaab000299f "", _M_buf_locale = {static none = -1, 
        static ctype = <optimized out>, static numeric = <optimized out>, static collate = <optimized out>, static time = 149717832, static monetary = <optimized out>, static messages = <optimized out>, 
        static all = <optimized out>, _M_impl = 0x2ae76446ab80, static _S_classic = <optimized out>, static _S_global = <optimized out>, static _S_categories = <optimized out>, static _S_once = <optimized out>}}, 
    _M_lock = {__data = {__lock = 0, __count = 0, __owner = 0, __nusers = 0, __kind = 0, __spins = 0, __list = {__prev = 0x0, __next = 0x0}}, __size = '\0' <repeats 39 times>, __align = 0}, _M_file = {
      _M_cfile = 0x2aaab0003d00, _M_cfile_created = true}, _M_mode = 17, _M_state_beg = {__count = 0, __value = {__wch = 0, __wchb = "\000\000\000"}}, _M_state_cur = {__count = 0, __value = {__wch = 0, 
        __wchb = "\000\000\000"}}, _M_state_last = {__count = 0, __value = {__wch = 0, __wchb = "\000\000\000"}}, 
    _M_buf = 0x2aaab00009a0 "Output:Id:31,PID:37,InId:65928,bysll:2,EhId:1100000005231634\n", _M_buf_size = 8192, _M_buf_allocated = true, _M_reading = false, _M_writing = true, _M_pback = 0 '\0', 
    _M_pback_cur_save = 0x0, _M_pback_end_save = 0x0, _M_pback_init = false, _M_codecvt = 0x2ae76446b040, _M_ext_buf = 0x0, _M_ext_buf_size = 0, _M_ext_next = 0x0, _M_ext_end = 0x0}}

#2  0x000000000042a7b2 in Class2::ThreadFunction2 (this=0xdc802520) at /Address/to/Nfile/Nfile.cpp:280
    Msg = (unsigned char *) 0x2aaaac8acf90 "\003"
    one_queue_buffer = {msg = "\003\000\002\000\037\000\000\000\000\000\000\000\037\000\000\000\"\000\000\000%\000\000\000\210\001\001\000\000\000\002\000C�\f\000\031", '\0' <repeats 12 times>}
    stomType = (short unsigned int *) 0x2aaaac8acf90
    Id1 = (short unsigned int *) 0x2aaaac8acf92
    Id = (unsigned int *) 0x2aaaac8acf94

#3  0x000000000042d139 in Class::run1 (this=0xdc802520) at /Address/to/Nfile/Nfile.hpp:152
No locals.

#4  0x00000000004295c3 in boost::_mfi::mf0<void, ThreadBase>::operator() (this=0xdc80a408, t=@0xdc802520) at /home/dev4/boost_1_54_0/boost/bind/mem_fn_template.hpp:70
No locals.

#5  0x00000000004294d4 in boost::_bi::list1<boost::reference_wrapper<ThreadBase> >::operator()<boost::_mfi::mf0<void, ThreadBase>, boost::_bi::list0> (this=0xdc80a418, f=@0xdc80a408, a=@0x2aaaac8ad0be)
    at /home/dev4/boost_1_54_0/boost/bind/bind.hpp:253
No locals.

#6  0x000000000042937b in boost::_bi::bind_t<void, boost::_mfi::mf0<void, ThreadBase>, boost::_bi::list1<boost::reference_wrapper<ThreadBase> > >::operator() (this=0xdc80a408)
    at /home/dev4/boost_1_54_0/boost/bind/bind_template.hpp:20
    a = {<No data fields>}

#7  0x000000000042924a in boost::detail::thread_data<boost::_bi::bind_t<void, boost::_mfi::mf0<void, ThreadBase>, boost::_bi::list1<boost::reference_wrapper<ThreadBase> > > >::run (this=0xdc80a250)
    at /home/dev4/boost_1_54_0/boost/thread/detail/thread.hpp:117
No locals.

#8  0x00002ae763b4e0d2 in thread_proxy () from /home/dev4/boost_1_54_0/stage/lib/libboost_thread.so.1.54.0
No symbol table info available.

#9  0x0000003b970064a7 in start_thread () from /lib64/libpthread.so.0
No symbol table info available.

#10 0x0000003b964d3c2d in clone () from /lib64/libc.so.6

My program is multi-threaded program; Can the issue be that some other thread is accessing the same Iter->first at the same time while its been accessed by the pointed code. Can it be clearly understood from the gdb log ?