dimanche 31 janvier 2016

How to resolve eclipse error as 'value' used with 'is_same' can not be resolved?

I have eclipse ide and linux platform ,inside eclipse i am using 'is_same' as :

#include <iostream>
#include <type_traits>
#include <cstdint>
int main()
{
std::cout << std::is_same<int, int32_t>::value;
}

When i build it it throws error as 'Symbol value could not be resolved'. I have done the c++11 related settings inside eclipse as:

 1)right click project> properties>C/C++ Build> Discovery Options select
 'Compiler invocation arguments' added -std=c++0x

So , now 'is_same' is being recognized but the 'value' is not getting resolved. I have also added few settings inside

 c/c++ General>Path and Symbols selected symbol tag and added      
'__GXX_EXPERIMENTAL_CXX0X__ ' and left the value blank.

So, please help me what am i missing if compiler is able to find 'is_same' then why is it not able to resolve 'value'?

Why am I not able to output a string in this particular case? - Multiple type class template with int & string types

This is my current code, only thing that I can't get to work right now is outputting the second variable b which is of type string.

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

template<class TypeA, class TypeB>
class Pair
{

public:

//default constructor
//initialize both members to their default values
//as per data type of Type1 and Type2
Pair() : a(TypeA()), b(TypeB()) {};

//parameterized constructor taking TypeA and TypeB to
//initialize values of a and b:
Pair(const TypeA& one, const TypeB& two) :
    a(one), b(two) {}

//copy-constructor to copy one Pair object from 
//another Pair object exactly same type:
Pair(const Pair<TypeA, TypeB>& rhs) :
    a(rhs.a), b(rhs.b) {}


void write(const TypeA&, const TypeB&);
void read();

private:

TypeA a;
TypeB b;
};


template<class TypeA, class TypeB>
void Pair<TypeA, TypeB>::write(const TypeA& one,const TypeB& two)
{
    a = one;
    b = two;
}

template<class TypeA, class TypeB>
void Pair<TypeA, TypeB>::read()
{
    std::cout << "These are the values: " << a << b << std::endl;
}

int main()
{
    Pair<int, std::string> object1;
    object1.write(1, "one");
    object1.read();

    system("Pause");
    return 0;
}

If I remove the b from the read() code it prints the single 1 fine. However, if I run it as is I get the following error:

C2679 binary '<<': no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion)

I tried overloading the operator<< but I haven't been able to wrap my mind around the syntax once you trow multiple typesets into the mix...

Any help is appreciated.

Can I have a static global instance of an exception?

I have read in a few places that raising exceptions can be expensive. I have an exception that I expect to occur with some frequency and I will catch it each time. This may be a naive question (like many, I'm late to the exception game):

can I create a static global instance of my exception and throw it when it does arise (only from one method), catching it each time?

Will this even save me any time? Or since I expect to throw with some frequency, will only throw this exception from this one method (at the moment), and will always catch this exception, is this a sign that I should be using some other paradigm for handling this situation?

Thanks for any helpful answers!

C++ Lambda stored in container capturing "this"

Consider the following minimal code:

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

class A
{
public:
  A() :
    s("dummy"),
    f([&, this]{ return s == "dummy"; }),
  {}
  std::string s;
  std::function<bool ()> f;
};

int main(int argc, char *argv[])
{
  A a;
  a.f(); // seems fine

  std::vector<A> as({});
  as[0].f(); // segmentation fault
}

Class A has a lambda member that captures this pointer. When running the code above, lambda works fine when invoked from standalone A instance, but I get segmentation fault when called from an instance stored in the vector.

Why does it happen?

Rotate integer for maximum trailing binary zeros

Given 16 bits of data, I need to (using C++11) find the rotation that maximises the number of trailing zeros.

e.g. (using 8 bits for clarity),

10110001 -> 11011000 so rot=1
10000011 -> 11100000 so rot=2
etc.

Obviously it's easy enough to 'brute force' it. But I suspect there is an elegant solution.

C++ multiple callback member functions from different classes without std and boost

I'm new to C++ and I don't want to use any libraries because I want to really understand whats going on internally. Additionally I try to keep my library-use as low as possible to improve performance.
So all in all I'd like to not use std or boost to solve this problem.

My question:

I have an EventHandler which has a function:

template<class T> void EventHandler::SetCallbackFunction(T* obj, void (T::*mem_fkt)(void));

I have to save the object and the function to call it later.
There are 2 possibilities:

  • EventHandler as template class (and typedef)
  • void* -> but to call the function I need to cast it back and for that I need the classname :/

Why these dont work: - The EventHandler can't be a template class because it needs to handle multiple classes.. - void* -> I don't know how to save the classname to cast it later on

How can I do that?
(Or is there another way? Maybe a way to save the classname to cast it later on?)


And I know that you could solve it based on something like this:

class A{
  public:
    void Callback();
    static void CallbackStatic(void* self){
      static_cast<A*>->CallBack();
    };
};

But this restricts me too much for my taste.

Thanks for any suggestion :)

Why does auto in `auto s = "abc"` yield char pointer instead of char array?

This program

#include <iostream>

int main() {
    auto s = "Hello, world!\n";
    decltype("Hello, world!\n") t = "Hello, world!\n";
    std::cout << sizeof s << ", ";
    std::cout << sizeof t << ", ";
    std::cout << sizeof "Hello, world!\n" << '\n';
    return 0;
}

prints

4, 15, 15

This suggests that the type of s is char *. This feels wierd considering that the type of the string literal and t is char [15].

Why doesn't this program print 15, 15, 15 instead?

Why does auto declare a pointer type instead of an array type when assigned to a string literal?

Redirect C++ Console Output to WIN32 Window on Windows

I have a simple console app on Windows 10, It just does basic input/output with iostream. What I want to know is if it is possible to do input/output in a WIN32 window, like basically a shell inside a window. I know similar answers have been asked before, but I didn't understand them. Help would be appreciated. I want an answer for a 12-year-old(me)

Pass string as regex pattern input. (non-scalar error)

I am trying to perform a regex search, but instead of typing the pattern (e.g std::regex reg = "\.") I want to give regex a string input. Here is my code where I convert string to const char* and pass it to regex_search:

void trigger_regex(string name, string body)
    {

      map<string,string>::iterator it;
      it=test.mydata.find(name);
      if( it == test.mydata.end())
      {
        std::cout<<"REGEX not found"<<endl;
      }
      else
        cout << "Found REGEX with name: " << it->first << " and rule: " << it->second << endl ;

        string subject = body;
        string rule = it -> second;
        const char * pattern = rule.c_str();
        regex reg = (pattern);
        smatch match;    

        while (regex_search (subject,match,reg)) {
          for (auto x:match) std::cout << x << " ";
          std::cout << std::endl;
          body = match.suffix().str();
        }
     }

I get error:

conversion from 'const char*' to non-scalar type 'std::regex {aka std::basic_regex}' requested regex reg1 = (rule1);

any help pls?

C++ display raw bytes as image

I'd like to take a stream of bytes, received via TCP, convert to image and display to the user.

My image is being sent as a uint8* binary array and is in PNG format.

In C#, I am doing this:

var image = Image.FromStream(new MemoryStream(ImageBytes));

However, I'd like to do the same but in C++. I am pretty new to C++ and can't being to think where I would start with this... I want to have minimal latency when converting my bytes to an image and displaying.

Any ideas?

How to set end condition of string iterator in C++?

i'm new in C++. I met a problem when doing exercise in C++ Primer 5th edition(Ex 9.43). The for loop can't stop in my function find_and_replace. Here is the code:

#include <iostream>
#include <string>

int find_and_replace(std::string& org_str, const std::string& str4find, const std::string& str4replace);

int main(int argc, char const *argv[])
{

    std::string str("I am a very loooooong string to be process!");
    int find_times;
    find_times = find_and_replace(str, "a", "###");
    std::cout << find_times << std::endl;
    std::cout << str << std::endl;

    return 0;
}

int find_and_replace(std::string& org_str, const std::string& str4find, const std::string& str4replace)
{
    int find_times = 0;

    if (org_str.size() < str4find.size())
    {
        std::cout << "Error: The original string is too short!" << std::endl;
        return find_times;
    }
    else if (org_str == str4find)
    {
        org_str.assign(str4replace);
        ++find_times;
        return find_times;
    }

    for (auto i = org_str.begin(), j = i + str4find.size(); j != org_str.end(); )
    {
        std::string temp(i, j);
        // std::cout << temp << std::endl;
        if (temp == str4find)
        {
            j = org_str.erase(i, j);
            org_str.insert(i, str4replace.begin(), str4replace.end());
            // std::cout << org_str << std::endl;
            // std::cout << *i << std::endl;
            j = i + str4find.size();
            // std::cout << *j << std::endl;
            ++find_times;
        }
        else
        {
            ++i;
            ++j;
        }
    }

    if (org_str.substr(org_str.size() - str4find.size()) == str4find)
    {
        org_str.erase(org_str.size() - str4find.size(), str4find.size());
        org_str.insert(org_str.end(), str4replace.begin(), str4replace.end());
        ++find_times;
    }

    return find_times;
}

I update iterator j and i after erase and insert operation, so i think, i and j are not invalid. Anyone can tell me why the end condition: j != org_str.end() is not work?

when g++ static link pthread, cause Segmentation fault, why?

#include <iostream>
#include <map>
#include <thread>

#define SIZE 1024
#define AMOUNT 100000
#define THREADS 4

class A
{
private:
    char a[SIZE];
};

void test()
{
    std::cout << "test start\n";
    std::map<int, A*> container;
    for(int i=0; i<AMOUNT; i++)
    {
        A* a = new A();
        std::pair<int, A*>p = std::make_pair(i, a);
        container.insert(p);
    }

    std::cout << "test release\n";
    for(int i=0; i<AMOUNT; i++)
    {
        auto iter = container.find(i);
        delete iter->second;
        container.erase(iter);
    }
    std::cout << "test end\n";
}

int main()
{
    std::thread ts[THREADS];
    for(int i=0; i<THREADS; i++)
    {
        ts[i] = std::thread(test);
    }

    for(std::thread& x: ts)
    {
        x.join();
    }

    return 0;
}

Above is a simple c++ code.

compile with: g++ -pthread -o one one.cpp -Wall -std=c++11 -O3

ldd one, gots:

    linux-vdso.so.1 =>  (0x00007ffebafce000)
    libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007fb47352a000)
    libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007fb473313000)
    libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007fb4730f4000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fb472d2a000)
    libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007fb472a22000)
    /lib64/ld-linux-x86-64.so.2 (0x00005654c5112000)

run ./one, every thing is ok.

Then I try a static link: g++ -pthread -o one one.cpp -Wall -std=c++11 -O3 -static

ldd one, gots:

    not a dynamic executable

But when I run it, some thing goes wrong...

test start
Segmentation fault (core dumped)

re-compile with -g, and the gdb shows:

wang[00:35][~/test]$ gdb one
GNU gdb (Ubuntu 7.10-1ubuntu2) 7.10
Copyright (C) 2015 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://ift.tt/KpOJT7;
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://ift.tt/xLrliR;.
Find the GDB manual and other documentation resources online at:
<http://ift.tt/1gENejF;.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from one...done.
(gdb) run
Starting program: /home/wang/test/one 
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
[New Thread 0x7ffff7ffa700 (LWP 3623)]
test start
[New Thread 0x7ffff77f8700 (LWP 3624)]
test start
[New Thread 0x7ffff6ff7700 (LWP 3625)]
test start
[New Thread 0x7ffff67f6700 (LWP 3626)]
test start

Program received signal SIGSEGV, Segmentation fault.
0x0000000000000000 in ?? ()
(gdb) 

Why this ?

Why is a const random device not possible

I am asking me the question why:

#include <random>

struct A{

   std::random_device rd; // or any other generator std::mersenne_twister...

   void doStuff() const {
       auto v = rd();
   }

}

const A a;  
a.doStuff(); // does not work since random_device::operator() is not const...

I thought maybe the random device ca still be used when constant but it cannot be seeded again but that is not the case (internal state is obviously not mutable in std::random_device)...

I want to make class A being properly defined (doStuff() is a const method) and now I suddenly need to use mutable std::random_device rd;isnt that ugly?

Is there any reason for this design?

Run a not-minimized application out off users view

I'm currently writing a program taking screenshots from a third-party application (portable Firefox), processes those and finally sends a mouse-click to a specified calculated location of the application (portable Firefox) via SendMessage.

This is actually all working, but I need to get a step further! At the moment this application is using the whole screen and the user is not able to do something else then watching the program. What I want to optimise is that the user can run my program and use other programs at the same time. But unfortunately it seems to be impossible to take a screenshot of an minimized window. That's why I need an alternative solution.

I thought about moving my application out of the users view (e.g. position -10000 -10000) using SetWindowPos but then I was again unable to take a screenshot of it. Also I was looking for a method to simulate a second monitor to windows to put my program on. I was also unable to simulate an additional desktop. Perhaps one of those ideas is the way to go, but I have no idea how.

Are there any suggestions/tips/etc. how to achieve to run my program not-minimized but out off the users view?

Thanks in advance for any answer!


Disclaimer: This is my first post and I'm not an native English speaker.

What is the diference?

I would like to understand between this two blocks of code and why the commented line leads to a crash.

int d=5;
int* b=0;
//*b=5;// this is not possible. Why?
b = &d;

and

int* b=new int;
*b=5;

Is there a way better than the other to do this? Thanks

Worst conversion sequence in list-initialization

I don't understand how worst conversion sequences for initializer_list are ranked during overload resolution. For example:

#include <initializer_list>

void fnc (std::initializer_list<int>){}
void fnc (std::initializer_list<long>){}

struct CL1 {
    operator short(){return 1;} };

struct CL2 {
    operator short(){return 1;} };

int main() {
    CL1 cl1;
    CL2 cl2;
    fnc ({cl1, cl2});
}

Here is a call of overloaded fnc function and overload resolution finds the best-viable function. The candidates are 2 functions which are ranked by comparing their needed conversion sequences.

The Standard (n4296) 13.3.3.1.5/4 [over.ics.list] says:

Otherwise, if the parameter type is std::initializer_list and all the elements of the initializer list can be implicitly converted to X, the implicit conversion sequence is the worst conversion necessary to convert an element of the list to X

For std::initializer_list<int> both conversions (CL1 -> int, CL2 -> int) are indistinguishable and both can be worst conversion (user-defined conversion + promotion). Simularly for std::initializer_list<long>, but with worst conversion sequence as user-defined conversion + standard conversion. And then the main question: which conversion (for cl1 or cl2) is selected as worst? Assume that in both initializer lists the worst conversion is selected as first (for cl1). Then, according to 13.3.3.2/3.3 [over.ics.rank]

User-defined conversion sequence U1 is a better conversion sequence than another user-defined conversion sequence U2 if they contain the same user-defined conversion function or constructor or they initialize the same class in an aggregate initialization and in either case the second standard conversion sequence of U1 is better than the second standard conversion sequence of U2.

the case with int is better because its second standard conversion sequence is better (promotion against standard conversion) and both conversions contain the same operator short(). Then assume that for std::initializer_list<long> worst conversion is for second element (cl2), and here is ambuguity because conversion functions are different.

How to find largest subgraph G' of graph G in which vertex with lowest degree V exist?

I have a undirected graph. If I have a vertex with lowest degree V there would be 2 subgraphs a subgraph containing v and other subgraph which does not cointain v that is G'=(G-v).

In general I would like to know how to find degree of vertex in undirected graph and a largest subgraph in which vertex with ith degree exist.

What is the real purpose of operator== for a std::function?

I've seen the operator== of a std::function misused more than once and I've had to explain what is its real use.
For the sake of clarity in favor of future readers, here is the documentation.
To sum up by citing the documentation above mentioned:

Compares a std::function with a null pointer. Empty functions (that is, functions without a callable target) compare equal, non-empty functions compare non-equal.

That said, the std::function has also the operator bool() (here the documentation) that works almost the same way and can be used as a replacement for the comparison my_func == nullptr.
In particular, it is said that:

Checks whether *this stores a callable function target, i.e. is not empty.

I cannot see a case where one can be used and the other does not fit well, so I cannot understand what is the purpose of the operator==, apart for the fact that it can be misunderstood and misused the most of the times.

Is there a particular case in which one cannot be used?
Otherwise, I'd rather invite my colleagues to use the bool operator and feel free to ignore the comparison operator, for it's so easy to be misused...

Why we need additional () in std::hash

I want to create an hash for a custom type and I've seen that I must write something like

template <>
struct hash<MyClass>
{
  std::size_t operator()(const MyClass& key) const
  {
    return std::hash<int>()(key.getID());
  }
};

The code works but I don't understant why I must write

std::hash<int>()(key.getID());

instead of

std::hash<int>(key.getID());

What's the meaning of the middle () operator? I'm using Visual Studio 2013 and I've tried to see the std::hash source code, but I'm not good enough to understant it well...

std::mutex::try_lock hangs when called from a static object constructor in a DLL

This happens with the MSVC 2013 compiler. I have a solution with 2 projects: .exe and .dll.
The .exe source code:

extern "C" int test_dll();

int main() {
    test_dll();

    return 0;
}

The .dll source code:

#include <mutex>

struct AAAA {
    AAAA() {
        std::mutex mutex;
        if (mutex.try_lock()) { // always blocks
            mutex.unlock();
        }
    };

} globalObject;

extern "C" __declspec(dllexport)
int  test_dll() {
    return true;
}

The try_lock call never returns. Here's the call stack:

msvcr120d.dll!Concurrency::details::ThreadScheduler::Create(const Concurrency::SchedulerPolicy & policy) Line 34
msvcr120d.dll!Concurrency::details::SchedulerBase::CreateWithoutInitializing(const Concurrency::SchedulerPolicy & policy) Line 285
msvcr120d.dll!Concurrency::details::SchedulerBase::GetDefaultScheduler() Line 654
msvcr120d.dll!Concurrency::details::SchedulerBase::CreateContextFromDefaultScheduler() Line 571
msvcr120d.dll!Concurrency::details::SchedulerBase::CurrentContext() Line 399
msvcr120d.dll!Concurrency::details::LockQueueNode::LockQueueNode(unsigned int timeout) Line 619
msvcr120d.dll!Concurrency::critical_section::try_lock() Line 1049
msvcp120d.dll!mtx_do_lock(_Mtx_internal_imp_t * * mtx, const xtime * target) Line 75
msvcp120d.dll!_Mtx_trylock(_Mtx_internal_imp_t * * mtx) Line 162
MutexDll.dll!std::_Mtx_trylockX(_Mtx_internal_imp_t * * _Mtx) Line 73
MutexDll.dll!std::_Mutex_base::try_lock() Line 46
MutexDll.dll!AAAA::AAAA() Line 8
MutexDll.dll!`dynamic initializer for 'AAA''() Line 21
[External Code]

This doesn't happen if the global object is created in the main .exe project. Only when in the DLL. What's going on here?

Where is the SDL lib folder in SDL-2.0.4?

where I can find lib folder in sdl-2.0.4 in Linux ? I tried to search in the source file but I can't found that ?

samedi 30 janvier 2016

How can I loop through all the elements in a two pair STL set

Here is the data type I am using.

  set< std::pair<string,string>,std::pair<string,string>> foo;

Here is my failed attempt at looping over it

for(auto &e: foo){
    cout << e.first << " " << e.second // this is where I am having an issue.
}

Is it possible to use auto this way? e.g

e.first, e.second // some c++ magic (i realize -> is wrong)  In pseudo -> //  e.third ...

I would love to use auto, but if not how would I write an iterator for the data type I am using?

Incomplete type error when using std::vector with structs

I'm working with c++ STL vectors, and have a vector of structures called projectileList. I'm trying to iterate through the vector, getting and setting values in the struts as I iterate, but my code refuses to compile, with the error 'Incomplete type is not allowed.'

Can anyone please point out what I'm doing wrong:

Code:

struct projectile {
    bool isEditing;
    [Code omitted]
    }


class ProjectileHandeler {

private:
    std::vector<projectile> projectileList;

     [Irrelevant code omitted]


void ProjectileHandeler::projectileUpdater()
{
    //This bit loops to infinity and beyond! ...or at least untill the handeler is destroyed.
    while (true)
    {
        for (int i = 0; i < projectileList.size(); i++)
        {
            if (*projectileList[i].isEditing == true) //Throws Incomplete type error
                break;
        }
    }

}

}

Using winAPI functions in QT (wininet)

im trying to make some ftp style upload function for that i'm using some windows libraries but i'm getting some troubles at compiling time.

uploadfile.h

#ifndef UPLOADFILE_H
#define UPLOADFILE_H

#include <QDialog>

#include <Windows.h>
#include <WinInet.h>
#include <Winineti.h>
#include <string>
#include <stdexcept>

using namespace std;

namespace Ui {
class UploadFile;
}

class UploadFile : public QDialog
{
    Q_OBJECT

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

    void setConnection(string host, int port, string user, string password);
    void uploadFile(string filename, string newFileNane);
    bool getStatErr();

private:
    Ui::UploadFile *ui;
    HINTERNET hInternet;
    HINTERNET hFtp;
    int value;
};

#endif // UPLOADFILE_H

uploadfile.cpp

#include "uploadfile.h"
#include "ui_uploadfile.h"

UploadFile::UploadFile(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::UploadFile)
{
    ui->setupUi(this);
}

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

void UploadFile::setConnection(string host, int port, string user, string password)
{
    LPCWSTR Host=(LPCWSTR)host.c_str();
    LPCWSTR User = (LPCWSTR)user.c_str();
    LPCWSTR Password = (LPCWSTR)password.c_str();

    hInternet = InternetOpenW(NULL, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
    hFtp = InternetConnectW(hInternet, Host, port, User, Password, INTERNET_SERVICE_FTP, 0, 0);

}

void UploadFile::uploadFile(string filename, string newFileNane)
{
    LPCWSTR FileName = (LPCWSTR)filename.c_str();
    LPCWSTR NewFileName = (LPCWSTR)newFileNane.c_str();
    FtpPutFileW(hFtp, FileName, NewFileName, FTP_TRANSFER_TYPE_BINARY, 0);
    if (FtpPutFileW(hFtp, FileName, NewFileName, FTP_TRANSFER_TYPE_BINARY, 0)) value = 1;
    else value = 0;
}

bool UploadFile::getStatErr()
{
    if (value==1){
        return true;
    }
    else
    {
        return false;
    }
    InternetCloseHandle(hFtp);
    InternetCloseHandle(hInternet);

}

when i try to compile it i get some unresolved external symbol errors

uploadfile.obj:-1: error: LNK2019: unresolved external symbol __imp__InternetOpenW@20 referenced in function "public: void __thiscall UploadFile::setConnection(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,int,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (?setConnection@UploadFile@@QAEXV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H00@Z)
uploadfile.obj:-1: error: LNK2019: unresolved external symbol __imp__InternetConnectW@32 referenced in function "public: void __thiscall UploadFile::setConnection(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,int,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (?setConnection@UploadFile@@QAEXV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H00@Z)
uploadfile.obj:-1: error: LNK2019: unresolved external symbol __imp__FtpPutFileW@20 referenced in function "public: void __thiscall UploadFile::uploadFile(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (?uploadFile@UploadFile@@QAEXV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@0@Z)

did i need to add some directives to the configuration file in order to work? or there's something else am i missing?

Note: i'm using qt 5.6 c++ for msvc2015

c++ operator overloading for repetition operator on string

So, it's been a while since I have written anything in C++ and now I'm working on a project using C++11 and macros.

I know that by using the stringify operator I can do this:

#define TEXT(a) #a    //converts to "a"

How am I supposed to use the preprocessor for recognizing the tokens like + and * to do this:

#define TEXT(a)+ ???  //want to convert to "a+"
#define TEXT(a)* ???  //want to convert to "a*"

when the input has to be in that syntax?

In C11/C++11, possible to mix atomic/non-atomic ops on the same memory?

Is it possible to perform atomic and non-atomic ops on the same memory location?

I ask not because I actually want to do this, but because I'm trying to understand the C11/C++11 memory model. They define a "data race" like so:

The execution of a program contains a data race if it contains two conflicting actions in different threads, at least one of which is not atomic, and neither happens before the other. Any such data race results in undefined behavior. -- C11 §5.1.2.4 p25, C++11 § 1.10 p21

Its the "at least one of which is not atomic" part that is troubling me. If it weren't possible to mix them, it would just say "on an object which is not atomic."

I can't see any straightforward way of performing non-atomic operations on atomic variables. std::atomic<T> in C++ doesn't define any operations with non-atomic semantics. In C, all direct reads/writes of an atomic variable appear to be translated into atomic operations.

I suppose memcpy() and other direct memory operations might be a way of doing this?

For performing atomic operations on non-atomic variables, atomic_load() and atomic_store() in C11 seem like they might possibly work for this. The C11 standard doesn't appear to require that the argument you pass points to an atomic variable:

7.17.7.2 The atomic_load generic functions

Synopsis

#include <stdatomic.h>
C atomic_load(volatile A *object);
C atomic_load_explicit(volatile A *object, memory_order order);

Description

The order argument shall not be memory_order_release nor memory_order_acq_rel. Memory is affected according to the value of order. Returns Atomically returns the value pointed to by object.

I was able to compile a C11 program with GCC 5.2.1 that accepted an atomic_store() of a non-atomic variable.

However the same doesn't appear to be possible in C++11. std::atomic_store appears to only be defined for a std::atomic<T> parameter. I couldn't get a program to compile that called std::atomic_store() on a non-atomic variable.

So what is the story here? Is it really about memcpy()?

EDIT: I just thought of one other possible explanation. I remember reading in Stroustrup that initialization of an atomic variable is not atomic. I don't know where in the standard it says that, but perhaps that could be another example of a non-atomic operation on an atomic variable.

invalid operands to binary expression ('std::ostream' (aka 'basic_ostream

When trying to compile my c++ code with Cheerp (using clang++), I get this output from my terminal:

example.cpp:102:9: error: invalid operands to binary expression ('std::ostream'
      (aka 'basic_ostream<char>') and 'const char *')
    out << "(" << loc.x << ", " << loc.y << ")";
    ~~~ ^  ~~~

Here is my command to the terminal:

/opt/cheerp/bin/clang++ -target cheerp example.cpp -o example.js

And Here is the code it has trouble with:

static std::ostream& operator <<(std::ostream & out, const CornerLoc &loc)
{
    out << "(" << loc.x << ", " << loc.y << ")";
    if (loc.type == kCorner)
        out<<"-corner";
    if (loc.type == kCornerNorthWest)
        out<<"-cornerNW";
    if (loc.type == kCornerNorthEast)
        out<<"-cornerNE";
    if (loc.type == kCornerSouthWest)
        out<<"-cornerSW";
    if (loc.type == kCornerSouthEast)
        out<<"-cornerSE";
    return out;
}

Error C2679 when reading in vector values

DESCRIPTION:

I'm working on a image editing program for school and can't seem to get rid of this error message. The program reads a ppm file, modifies it, and outputs a modified ppm file.

ERROR MESSAGE:

Error C2679 binary '>>': no operator found which takes a right-hand operand of type 'std::vector>,std::allocator>>>' (or there is no acceptable conversion)

RELEVANT CODE:

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

    ifstream fin;
    fin.open(infile);
    if (fin.fail()) {
        cerr << "Error opening input file '";
        cerr << infile << "', exiting!" << endl;
        return -1;
    } 

    string magic;
    int cols, rows, maxColor, red, green, blue, COLORS = 3;
    fin >> magic >> cols >> rows >> maxColor;

// TODO: read in columns/rows/depth header info; make a data structure
// rows x columns x 3 integers.

    vector<vector<vector<int>>> photo(rows, vector<vector<int>>(cols, vector<int>(COLORS)));

// TODO: read all of the image data into data structure.

    for (int r = 0; r < rows; r++) {
         for (int c = 0; c < cols; c++) {
             for (int i = 0; i < 3; i++) {
                 fin >> photo[r, c, i];           
             }
         }
     }

    // The error is under the last ">>" between fin and photo. 

Thanks in advance for your help everyone!!

Questions about a piece of code with templates, conversion operator and copy ctor

Two questions about the following piece of code:

template <class T> class A {
protected:
    T j;
public:
    A(T k) :j(k) {cout << *this;}
    ~A() { cout << *this; }
    A(const A<T> &a) {
        j = a.j;
        cout << *this;
    }
    virtual void print() const {cout << j << ' ';}

    friend ostream &operator << (ostream &os, const A<T> &a) {
        a.print();
        return os;
    }
    operator T() {  return j;}
};

template <class T> class inherit:public A<T> {
    T field;
public:
    inherit(const T&t) :A<T>(t), field(1+t) {
        cout << *this;
    }
    void print() const {
        A<T>::print();
        cout << field << ' ';
    }
};
int main(){
    inherit <int> b(3);

    inherit <string> c("asdf");
    string k="str";
    c + k;//error no operator +
    b + 5;//no error
}

  1. Why does inherit <int> b(3); leads to the copy ctor of inherit? Why copy instead of making a new instance of inherit from scratch using the default ctor?

  2. Why does b+5; leads to the conversion operator operator T() and why it doesn't happen with c+k?

C++ Function templates for only types that extend the same superclass

I come from a C# background, where I would be able to do something like this

void AddComponent<T>() where T : Component, new()
{
    T newT = new T();
    //Do other things...
    ListOfComponents.Add(newT);
}

I'm rather new when it comes to C++ Templates, but after visiting a number of tutorials and sites, I haven't been able understand how to replicate this.

Does anyone know if this is possible in C++ using templates?

Efficient way to initialize array with a byte sequence?

Let's say I have a byte sequence of some odd size n, with n = 3 for the sake of this example:

char source[n] = "abc"

And I have a memory range of sufficient size to hold m copies of this sequence:

char * dest = new char[m*n]

Now I want to initialize dest with those m copies of source. Sure, I could use a nested loop:

for ( unsigned i1 = 0; i1 < m; ++i1 )
{
    for ( unsigned i2 = 0; i2 < n; ++i2 )
    {
        dest[ i1 * n + i2 ] = source[ i1 ];
    }
}

But somehow this lacks all the finesse that usually tells me that I got the "right" solution for a problem.

Does C++ offer some more efficient way for this?

template member variable specialization

I have a template class with lots of functions and only want to specialize a few of them, while also adding a member variable.

Is that possible without the need to reimplement all the functions for the specialized class?


What I have:

template<class T> class Vector3
{
    union {
        T data[3];
        struct { T x, y, z; };
    };

    //a lot of functions

    T Length() { ... };
};

What I want to do:

template<> class Vector3<float>
{
    union {
        float data[3];
        struct { float x, y, z; };

        //new union member only for <float>!
        __m128 xmm;
    };

    float Length() {
        //special instructions for special case <float>
    };
};

As 95% of all functions stay exactly the same, I definitely don't want to reimplement them for every single specialization. How can I achieve that?

How to use C++ 11's using for template function to remove namespace in a scope

I have a template function:

namespace Example
{
template<class T>
T Foo() { return T(0); };
}

I would like to use a using statement or similar so that I do not have to prefix the function name with it's namespace when calling it i.e.

template<class T> using Foo = Example::Foo<T>;

However this does not work.

I do not want to use this approach as it would include everything form the namespace Example:

using namespace Example;

Is there a nice C++ 11 way to create a shortened alias to a function in a namespace?

Searching a portion of vector in c++

I have a vector which contains unsigned integers in sorted order. Now I want to apply binary search on the vector from a particular position of the vector to the end of it.

For example, my vector is:

vector<unsigned> vec;
vec.push_back(1); vector.push_back(2), vector.push_back(3); 

vector.push_back(4); 
vector.push_back(5); vector.push_back(6); vector.push_back(7); vector.push_back(8); 
vector.push_back(9); vector.push_back(10); vector.push_back(11); vector.push_back(12);

Now, I want to apply binary search on "vec" starting from the 6th position to the size of vector, i.e. I want to binary search on only the vector: starting from pos:6 to pos:11.

I know I can apply std:lower_bound(vec.begin(),vec.end(),9) on the entire vector, but I am not able to understand as to how can I apply it on a portion of the vector. I want to find the position of "9" in the vector vec. I'll greatly appreciate any help on this

Xcode 7.2 can't find c++ std::pair

First of all, I use Xcode 7.2 on OSX 10.11.2. In my main.cpp file, the std library is working fine. But, whenever I try to use it in any other c++ file, I get unexpected unqualified-id.

I have the following files :

main.cpp (std is working in it)

algo.hpp (std is not working in it)

algo.cpp (std is not working in it)

Why is the deployment target OSX 10.11 not finding the standard c++ library in all my files ?

Here is for exemple my header file algo.hpp

#ifndef algo_hpp
#define algo_hpp

std::pair<unsigned int, unsigned int> pgcdFB(const int m,const int n);

std::pair<unsigned int, unsigned int> euclide(const int m, const int n);

unsigned int fibonacci(const unsigned int i);

#endif /* algo_hpp */

On each line where I use std I get undeclared identifier 'std

Paradigm regarding template class specialization

I'm currently writing a template class for archiving (or serializing) and unarchiving data into/from a binary format. First off, I'm trying to close on what pattern I'll use. I am mostly inclined to using templates because unarchivers don't have an input type for method overloading. For instance, the following example is OK:

Archiver ar;
int i;

archive(ar, i);

But it's counterpart isn't:

Unarchiver unar;
int i;

i = unarchive(unar);

I would like to avoid using the function's name, such as unarchive_int because it would be troublesome when using templates. Say:

template <class T> class SomeClass
{
public:

   void doSomething()
   {
      // Somewhere
      T value = unarchive(unar);
   }
};

This would make things messy, and as such I rather really use templates for this, whereas the previous expression would be T value = unarchive<T>(ar);. It also seems silly (arguably) to write a global function if either the first or only parameter are always the archiver and unarchiver objects; a template class seems to be in order:

template <class T> class Archiver
{
public:

    void archive(T obj);
};

This works, but the archiving method always copies its input object. This is OK with POD data types, but not so much which classes. The solution seems obvious, and instead use a const reference as in void archive(const T & obj), but now it also seems silly to be passing integers, floats, and other PODs by reference. Although I would be happy with this solution, I tried to go a little further and have the object make the distinction instead. My first approach is std::enable_if, while assuming a copy by default (for all non-class members) and provide a class specialization where the archive method gets its input by reference instead. It doesn't work. Here's the code:

template <class T, class E = void>
class Archiver
{
public:

    // By default, obj is passed by copy
    void archive(T obj);
};

template <class T>
class Archiver<T, typename std::enable_if<std::is_class<T>::value && !std::is_pod<T>::value>::type>
{
public:

    // I would expect this to be used instead if is_class<T> && !is_pod<T>
    void archive(const T & obj);
};

The problem is that the second declaration is not visible at all to the compiler, and here's proof:

template <> void Archiver<std::uint8_t>::archive(uint8_t obj);
template <> void Archiver<std::string>::archive(const std::string & obj);

The former compiles fine, but the later gives:

out-of-line declaration of 'archive' does not match any declaration in 'Archiver<std::__1::basic_string<char>, void>'

On the other hand, if I get the std::string instead by copy if compiles just fine. I think I know why this happens, the compiler chooses the first template as it's generic enough for both declarations, but then how do I make it choose the more specialized version?

wrapper class for ostream to dispatch stream operator<< calls through a strand

I am fairly new to boost::asio and I am trying to implement a class to wrap an std::ostream object so that all calls to the stream operator are serialized through a strand.

Ideally, this is the behavior i'm looking for:

// from thread 1
logstream << "Kiwi";
// from thread 2
logstream << "Apple";

//logstream output could be "KiwiApple" or "AppleKiwi", but
// never something like "KAppleiwi"

I have been working from other answers (here and here) explaining how to wrap an ostream to get custom behavior, but it relies on a template argument which I can't get to play nice when I use it inside an anonymous handler passed to strand::dispatch(...). I should also add that I have dropped the const modifiers for the time being as they were causing more problems (I could also use some advice on this). Here is my code:

// logstream.hpp ------------------------------------------------------------
#include <ostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>

class LogStream {
public:
    // construct with an io service and a unique ostream
    LogStream(std::shared_ptr<boost::asio::io_service> io_service,
        std::ostream &out)
        : work_(*io_service), strand_(*io_service), out_(out) {};

    // used to be:
    // template<typename T>
    // inline const LogStream & operator<<(const T& v) const {...}
    template<typename T>
    inline LogStream& operator<<( T& v)  {
        // ideally i would like to dispatch an anonymous "quickie"...
        strand_.dispatch([this, v](){this->out_ << v; });
        return *this;
    };

private:
    boost::asio::io_service::work work_;
    boost::asio::strand strand_;
    std::ostream &out_;
    // no default constructor
    LogStream() = delete;
};

// main.cpp -----------------------------------------------------------------
#include <iostream>
#include <logger/logstream.hpp>
#include <boost/thread.hpp>
#include <boost/bind.hpp>

using namespace std;

void foo(int id, LogStream &ls) {
    for (int i = 0; i < 1000; i++) {
        // ls << i; // this actually seems to work
        ls << "kiwi"; // compiler error - it doesn't like the array of characters.
    }
}

void worker(std::shared_ptr<boost::asio::io_service> io_service) {
    io_service->run();
}

int main() {
    std::shared_ptr<boost::asio::io_service> io_service = 
        std::shared_ptr<boost::asio::io_service>(new boost::asio::io_service());

    LogStream ls = LogStream(io_service, cout);

    boost::thread_group workers;
    for (int i = 0; i < 4; i++) {
        workers.create_thread(boost::bind(&worker, io_service));
    }

    boost::thread_group threads;
    for (int i = 0; i < 4; i++) {
        threads.create_thread(boost::bind(&foo, i, ls));
    }
    io_service->run();


    return 0;
}

I have tried a couple different variations of this basic structure (using boost::bind with a class method, for example) and the errors are different every time. As I presented it, the code now generates this compiler error:

error C2536: 'LogStream::<<::<lambda_d3e85e85f4366eae12cc7bf533b39faa>::LogStream::<<::<lambda_d3e85e85f4366eae12cc7bf533b39faa>::v' : cannot specify explicit initializer for arrays
1>          d:\code projects\wfc\cpp\src\logger\logstream.hpp(28) : see declaration of 'LogStream::<<::<lambda_d3e85e85f4366eae12cc7bf533b39faa>::v'

I have looked around for info on error C2536, but I am having a hard time relating those answers to my code. As I mentioned before, I am new to boost, and I am also not very experienced with using templates.

Answers that explain what I am doing wrong, and answers that suggest a better way to achieve the desired behavior are equally welcome. Thanks very much in advance for any help.

I am compiling with msvc120 (2013).

Destruction via const iterators in C++11

Take http://ift.tt/1tl2KTy for an example. Why have the signatures changed from using non-const iterators to const-iterators given that the operation does modify the container via the supplied iterator?

I thought that was the definition of what non-const iterators were for. What is the reasoning behind the change?

How to iterate two vectors in one loop in C++11? [duplicate]

This question already has an answer here:

#include <vector>

using namespace std;

class A
{
public:
    A() = default;

    void Add(int n)
    {
        m_count += n;
    }

private:
    int m_count;
};

int main()
{
    vector<int> coll_1 = {1, 2, 3};
    vector<A> coll_2(3);

    // Is there a more elegant way to do the "for loop"?
    for (int i = 0; i < 3; ++i)
    {
        coll_2[i].Add(coll_1[i]);
    }

    return 0;
}

I know there are many new ways (i.e. C++11 flavor) to do the for loop, such as for_each, transform, for (auto& elem : coll), etc.

However, I cannot find an elegant way to do the work as illustrated as above.

Any suggestions?

Initialize std::vector

I have the following array:

static const char * const names[] = { "Banana", "Apple", "Kiwi" }

Is it possible to construct a std::vector<std::string> from this with a simple constructor call?

Knocking out a class template constructor depending on class template parameter

Given the following class template:

#include <type_traits>

template< class T, class Unrelated >
struct MyClass
{
    static_assert( std::is_same< T, char >::value ||
                   std::is_same< T, char16_t>::value ||
                   std::is_same< T, char32_t >::value,
                   "MyClass only defined for char, char16_t, char32_t" );
    MyClass( T init ) {}
    MyClass( char32_t init ) {}
    // ...
};

The second (char32_t) constructor is a special case for T == char and T == char16_t.

Obviously, it would generate an error for T == char32_t. So, I would like to "knock out" that constructor for that case. The class is rather large, with most of the code being shared for all T, so I would rather not specialize the whole class for the char32_t case.

I have seen enable_if as well as related answers like this one here on SO, but was unable to adapt any of the presented solutions / examples to my specific case (non-templated constructor in class template).

So I ask for your assistance:

How to disable the MyClass( char32_t ) constructor for MyClass< T, U > with T == char32_t?

How to get random salt from OpenSSL as std::string

I would like to generate a random string with OpenSSL and use this as a salt in a hashing function afterwards (will be Argon2). Currently I'm generating the random data this way:

if(length < CryptConfig::sMinSaltLen){        
    return 1;
}
if (!sInitialized){
    RAND_poll();
    sInitialized = true;
}

unsigned char * buf = new unsigned char[length];
if (!sInitialized || !RAND_bytes(buf, length)) {      
    return 1;
}

salt = std::string (reinterpret_cast<char*>(buf));
delete buf;

return 0;

But a std::cout of salt doesn't seem to be a proper string (contains control symbols and other stuff). This is most likely only my fault.

Am I using the wrong functions of OpenSSL to generate the random data?

Or is my conversion from buf to string faulty?

rvalue reference to temporary declaration

E && e0 = E () ; 
E e1 ;

In the first case name given to rvalue , so this rvalue is no longer rvalue ; ( is my assume correct.? ) and is there any differences between these two cases of object declaration.? ;

cocos2dx detect intersection with polygon sprite

I am using cocos2d-x 3.8. I try to create two polygon sprites with the following code. I know we can detect intersect with BoundingBox but is too rough. is there a way to detect the intersect of polygon sprites? Thank you.

auto pinfoTree = AutoPolygon::generatePolygon("Tree.png");
auto treeSprite= Sprite::create(pinfoTree);
treeSprite-> setPosition(width / 4 * 3 - 30 , height / 2 - 200);
this->addChild(treeSprite);

auto pinfoBird = AutoPolygon::generatePolygon("Bird.png");
auto Bird= Sprite::create(pinfoTree);
Bird->setPosition(width / 4 * 3, height / 2);
this->addChild(Bird)

vendredi 29 janvier 2016

problems with shared_from_this in constructor

I understand why shared_from_this doesn't work in the constructor. I've found a number of posts on here clearly explaining why. I've also seen a workaround for it. My problem is related to this but I'm looking for an elegant workaround.

I quite like this kind of design

class Foo : public enable_shared_from_this<Foo> {
public:
  typedef shared_ptr<Foo> Ptr;

  Ptr setA(int) {/* .... */ return this->shared_from_this(); } 
  Ptr setB(int) {/* .... */ return this->shared_from_this(); } 
  Ptr setC(int) {/* .... */ return this->shared_from_this(); } 
};

so I can daisy chain like this, which I find very readable

Foo::Ptr foo = make_shared<Foo>();
foo->setA(3)->setB(4)->setC(5);

However, my setX methods do more than just assign the value to a property, they might do slightly more complex things (like set other properties etc). So I'd like to use them in my constructor. i.e.

Foo::Foo(int a, int b, int c) {
    setA(a);
    setB(b);
    setC(c);
}

Of course this crashes. However in my case I don't actually need a shared this pointer in my constructor. It's just a side-effect of my wanting to daisy chain later.

A dirty fix could be I just make a bunch of private setX_ methods which do the actual assignment and other tasks, but don't return anything. The constructor calls those. Then I have public setX methods simply call the private ones and then return the this->shared_from_this(). That's safe, but a bit of a PITA. Is it possible to check if a shared pointer to this already exists without crashing? i.e.

class Foo : public enable_shared_from_this<Foo> {
public:
  typedef shared_ptr<Foo> Ptr;

      Ptr setA(int) { /*.....*/ return getThis(); }

protected:
    Ptr getThis() {
        return safe_to_get_this ? this->shared_from_this : Ptr();
    }

};

Why computer takes more time in arranging different permutations?

I just learned the heap's algorithm. Well the larger the number of objects get the more time the system takes to arrange them in all possible permutations. But when i calculate the the factorial of that number of objects in a calculator the results are instant. Why does it happen that same no. of permutations take more time than calculating the factorial?

how to improve this random number generator code in c++?

I am c++ student and i am working on creating a random number generator by myself. I know about library functions but i want to make one myself. Here is the function.It just selects a possible number within a defined range. Problems are listed below. Any help would be appreciated.Please help any suggestions or tricks anything. I am making this for about 2 months.

   int rn(int lowerlt,int upperlt)
    {
/**
This function returns a random number generated using loops.
I have tried to generate a random number by taking an integer array and storing all the possible values within the defined
range in the calling part. The theory is that a variable named pointer starts getting greater and breaks the main loop
when the seed taken from system time becomes equal or greater than the pointer.

MAIN PROBLEMS:-
-The problem is that the seed which is system time is very predictable and it is very same most times which lessens the degree of randomness.
-It also takes time more than usual which is undesirable(about 10 secs).
-If range is very large then degree of randomness is very less and results are predictable.

 *But over short ranges results are very effective.
 I want to make it effective for big ranges.
**/

const int size=upperlt-lowerlt;          //Constant size of the integer array.

int ar[size];                         //Array to store all possible values within defined range.
int i,x,ret;                   //Variables to control loops and return value.
long pointer=0;     //pointer variable. The one which breaks the main loop.


//Loop to initialize the array with possible values..
for(i=0,x=lowerlt;x<=upperlt;i++,x++)
    ar[i]=x;

long seed=time(0);

//Main loop . To find the random number.
for(i=0;pointer<=seed;i++,pointer++)
{
    ret=ar[i];
    if(i==size-1)
    {
        for(;i>=0;i--)    //Reverse loop.
            {
                ret=ar[i];
            }
    }
}

return ret;     //The return statement .
}

Passing member functions with variadic template arguments to variadic constructors

I can't figure out how to pass member function with variadic template arguments to std::thread constructor. I have a method that receives function and its arguments and need to pass them to other method which is invoked in new thread and call passed function there. Here is simplified version:

class Test
{
public:
    template<typename Function, typename... Args>
    void Run(Function&& f, Args&&... args)
    {
        std::thread t(&Test::Operation, this, f, args...); // how???
        t.detach();
    }

    template<typename Function, typename... Args>
    void Operation(Function&& f, Args&&... args)
    {
        f(args...);
        // ...
    }
};

Test test;
test.Run([](const std::string& msg) { std::cout << msg; }, "Hi!");

There is something wrong in passing arguments this way, I get the following error: 'std::thread::thread': no overloaded function takes 4 arguments. How can I do this?

About multiple inheritance and ambiguity

In the following example:

class A {
public:
    virtual void f() { cout << "a" << endl; }
    virtual void h() { cout << "A" << endl; }
};
class s1 : public A {
public:
    virtual void f() { cout << "s1" << endl; }
};
class s2 : public A {
public:
    virtual void h() { cout << "s2" << endl; }
};
class GS : public s1, public s2 {
public:
};
int main()
{
    s1 *q = new GS;
    q->h();//no problem

    GS a;
    a.h();//error

}

Why does a.h(); give an ambiguity error yet q->h(); doesn't?

Doesn't *q have an instance of GS which should cause the same ambiguity problem?

Are name spaces required for free functions in the STL?

I'm playing around with my coding style. I used to explicitly prefix every library call with std:: but I'm switching over to using declarations like this:

using std::count;
using std::vector;

One thing I've noticed over the past few days is that sometimes if I forget a using declaration -- using std::vector; is a good example -- I get reams of compiler errors. However, if I neglect to namespace delcare an algorithm such as using std::count; my code compiles just fine.

Does this have to do with the difference with classes and free functions? On all the reference sites, both count(first, last, value) and vector are prefixed with std:: so I would expect them to behave the same.

Or does it have to do with other functions in the global namespace? I notice std::max also seems to require a namespace declaration, perhaps it defined in a default-included Apple/glibc/LLVM file and thus there is a conflict if I used it sans namespace declaration?

I am using Apple LLVM 7.0.2. on El Capitan.

What does the "template" keyword mean when places after scope resolution operator (::) [duplicate]

This question already has an answer here:

I came accross the following construct while reading this article:

template<typename F, typename...As>
using meta_apply = typename F::template apply<As...>;

Can someone explain to me what does the template keyword mean when it's placed after the scope resolution operator ::? Or better point me to where this usage is described in C++ reference of any kind. I tried looking it up myself but couldn't find any.

std::atomic as a value of std::map

I want to use atomic variable in a map. I am using Visual Studio 2012 (msvc-11) and gcc 4.7. I have defined a type:

typedef std::map<uint64_t, std::atomic<int64_t>> value_map_t;

In msvc-11, lines

value_map_t map;
map[1] = 0;

produce error:

error C2248: 'std::atomic<__int64>::atomic' : cannot access private member declared in class 'std::atomic<__int64>'

Same happens with gcc 4.7 (see here)

error: use of deleted function 'std::atomic::atomic(const std::atomic&)'

However, in Visual Studio 2013 (msvc-12) and beyond, as well as in gcc 4.8 and newer, it works fine.

See for yourself gcc 4.8 and Visual Studio 2013+

What can I do in msvc-11 / gcc 4.7 to make it work ?

std::list

The code

#include <list>
#include <memory>

class B;
class A {
    std::list<std::unique_ptr<B>> bs;
public:
    A();
    ~A();
};

int main()
{
    A x;
    return 0;
}

obviously compiles. It doesn't link because A::A() and A::~A() are missing, but that is expected and alright. Changing

std::list<std::unique_ptr<B>> bs;

which is supposed to call the std::list's standard constructor

list() : list(Allocator()) {}

(C++14 and up) to

std::list<std::unique_ptr<B>> bs{};

which is supposed to call

list(std::initializer_list<T>, const Allocator & = Allocator());

i.e. calling the initializer_list constructor with an empty initializer_list, gives the following error with c++ (Ubuntu 5.2.1-22ubuntu2) 5.2.1 20151010 and the --std=c++17 parameter:

/usr/include/c++/5/bits/unique_ptr.h: In instantiation of ‘void std::default_delete<_Tp>::operator()(_Tp*) const [with _Tp = B]’:
/usr/include/c++/5/bits/unique_ptr.h:236:17:   required from ‘std::unique_ptr<_Tp, _Dp>::~unique_ptr() [with _Tp = B; _Dp = std::default_delete<B>]’
/usr/include/c++/5/bits/stl_list.h:106:12:   required from ‘void __gnu_cxx::new_allocator<_Tp>::destroy(_Up*) [with _Up = std::_List_node<std::unique_ptr<B> >; _Tp = std::_List_node<std::unique_ptr<B> >]’
/usr/include/c++/5/bits/list.tcc:75:4:   required from ‘void std::__cxx11::_List_base<_Tp, _Alloc>::_M_clear() [with _Tp = std::unique_ptr<B>; _Alloc = std::allocator<std::unique_ptr<B> >]’
/usr/include/c++/5/bits/stl_list.h:446:17:   required from ‘std::__cxx11::_List_base<_Tp, _Alloc>::~_List_base() [with _Tp = std::unique_ptr<B>; _Alloc = std::allocator<std::unique_ptr<B> >]’
/usr/include/c++/5/bits/stl_list.h:507:11:   required from here
/usr/include/c++/5/bits/unique_ptr.h:74:22: error: invalid application of ‘sizeof’ to incomplete type ‘B’
  static_assert(sizeof(_Tp)>0,
                      ^

Which barks about the type of B being incomplete. My question is:

Why does the initializer_list constructor need the complete type of B for an empty initializer list?

How does experimental::basic_string_view<> work?

I am not 100% that the following code is semantically correct:

#include <iostream>
#include <experimental/string_view>

int main()
{
    std::string str = "lvalue string";

    std::experimental::string_view view_lvalue(str);
    std::experimental::string_view view_rvalue(std::string{"rvalue string"});

    std::cout << view_lvalue << '\n' << view_rvalue << '\n';
}

Live on Wandbox

Question: Can I legally bind a rvalue to such a view, or is it just UB? If yes, how does it work? As far as I know, a rvalue does not bind to a const reference (which I assume the view holds to the original string) via the constructor, so I thought that at the end of the statement std::experimental::string_view view_rvalue(std::string{"rvalue string"}); the reference will be dangling. Does string_view use a more sophisticated approach?

I am asking this because I am trying to write a similar view for some matrix class, and don't yet know how to deal with rvalues (I can disable them of course, but I don't think it's the best approach).

Do STL containers do smart deallocation like shared_ptr?

Are STL containers smart like shared_ptr?

They do deallocate on their own when out of scope, but what about assignment operations?

vector<int> aa(9);
...fill aa...
vector<int> bb;
aa = bb;

Did the assignment operation deallocate properly everything that was in aa?

Is this copying values twice?

Let's assume I have a class like this:

class Foo
{
  QString a;
  void setA(QString val);
}

and implement setA() like this:

void Foo::setA(QString val)
{
  this->a = val;
}

and use it like:

Foo f;
QString v = "foo";
f.setA(v);

Am I copying the v struct twice on stack? one for pass in the argument and other in the assignment within the function, is this right? by rather using void setA(QString &val); will avoid copying the object twice because in the first one I'm just copying a reference (a pointer) and not the entire object so the only copy of the object is in the assignment:

  this->a = val;

What are unevaluated contexts in C++?

One example that frequently comes to mind is :

sizeof expression, where it doesn't evaluates the expression but determines the size by static type. For example :

int func();
sizeof(func());

This is my limit of thinking, so if there are other unevaluated contexts, then what are they?

How C++ placement new works?

This question is to confirm I understood the concept right and take expert opinion on style of usages and possible optimization.

I am trying to understand "placement new" and following is the program I came up with...

 1  #include <iostream>
 2  #include <new>
 3
 4  class A {
 5    int *_a;
 6    public:
 7      A(int v) {std::cout<<"A c'tor clalled\n";_a= new int(v);}
 8      ~A() {std::cout<<"A d'tor clalled\n"; delete(_a);}
 9      void testFunction() {std::cout<<"I am a test function &_a = "<<_a<<" a = "<<*_a<<"\n";}
10  };
11  int main()
12  {
13    A *obj1 = new A(21);
14    std::cout<<"Object allocated at "<<obj1<<std::endl;
15    obj1->~A();
16    std::cout<<"Object allocated at "<<obj1<<std::endl;
17    obj1->testFunction();
18    A *obj2 = new(obj1) A(22);
19    obj1->testFunction();
20    obj2->testFunction();
21    delete(obj1);// Is it really needed now? Here it will delete both objects.. so this is not the right place.
22    obj1->testFunction();
23    obj2->testFunction();
24    return 0;
25  }

When I run this program I get following o/p

A c'tor clalled
Object allocated at 0x7f83eb404c30
A d'tor clalled
Object allocated at 0x7f83eb404c30
I am a test function &_a = 0x7f83eb404c40 a = 21
A c'tor clalled
I am a test function &_a = 0x7f83eb404c40 a = 22
I am a test function &_a = 0x7f83eb404c40 a = 22
A d'tor clalled
I am a test function &_a = 0x7f83eb404c40 a = 0
I am a test function &_a = 0x7f83eb404c40 a = 0

I have following question...

  • Is it a correct example to demonstrate placement new?
  • member _a is dynamically allocated (with no placement new). So why it is getting same same address for obj1 & obj2. Is it just a coincidence?
  • is D'tor call on line 15 a good practice?

Please also point out of you see any thing which I can improve on or just do not try. Any good reference or reads are also welcome.

Thanks Vikrant

Conversion from String to char* C++ function

Here is my code :

Excella.h

class Excella
{
public:
    string ScannerCheque(string DeviceName, char* settings, char* docInfo, DWORD docInfoBufferSize);
};

Excella.cpp

string Excella::ScannerCheque(string DeviceName, char * settings, char* docInfo, DWORD docInfoBufferSize)
{
    DWORD dwStatus;
    dwStatus = MTMICRProcessCheck((char*) DeviceName.c_str(), settings, docInfo, &docInfoBufferSize);

    //checking if the process went well
    if (dwStatus == MICR_ST_OK) {
        string docInfoString(docInfo);
        return docInfoString;
    }
    else 
        return "";
}

The result I get from MTMICRProcessCheck is stored in the argument docInfo.

main.cpp

DWORD dwStatusS;
DWORD SettingsBufferSize;
SettingsBufferSize = 4096;
DWORD docInfoBufferSize;
docInfoBufferSize = 4096;
string scanner;
char docInfo[4096] = "";
char Settings[4096] = "";

//devices is a combobox
String^ dev = devices->Text->ToString();

if (dev != "") {
    MessageBox::Show(dev);
    IntPtr p = Marshal::StringToHGlobalAnsi(dev);
    string DeviceName;
    DeviceName = static_cast<char*>(p.ToPointer());
    Marshal::FreeHGlobal(p);
    scanner = excella.ScannerCheque(DeviceName, Settings,docInfo,docInfoBufferSize);
}
else MessageBox::Show("Device s name is null");

The problem is that the function "MTMICRProcessCheck" in excella.cpp file returns 'Bad parameter' so clearly, there is a problem with the variable DeviceName..maybe when i tried to do the convertion from System::String to std::string something went wrong! thank u for ur help!

why an enum value can not be used as a rvalue?

I am using Clion 1.2.4 to build a C++ project based on C++11, when I try use make_shared function to create a shared_ptr object like this:

auto item = std::make_shared<Type>(EnumType::Value);

where Type is an struct with a constructor like this:

Type(EnumType t = defaultValue) { }

and the param of constructor is an enum type.

But the compiler give me an error :

parameter type mismatch: Expression must be rvalue.

So I want to know whether an enum value can be used as a rvalue to call a function? And why.

And if I use like this:

auto item = std::make_shared<Type>(std::move(EnumType::Value));

compiler will not show error. What the move function do? And is it right that using a constant value as the actual parameter of move function.

regex pattern to extract empty field from CSV file

I have a csv file that needs to be read into Matrix. Right now i have regex pattern

regex pat { R"(("[^"]+")|([^,]+))" }

Right now it chooses between sequences that are between quotes and anything that is not comma. The file contains data from the survey that has questions with yes no answers. If you answer "no" you do not need to answer to some related questions. Therefore i get some sequences in file like this: ":,,,,,,,," Wheres each two commas mean an empty field. But i would like to remain the row as an equally numbered array. It seems that it would be easyer to later navigate through matrix to get information. So i would have to extract these empty fields between the commas. I could not find a regex pattern for empty sequence. Is regex pattern a proper way for solving this issue?

error: 'const std::array

I am trying to make a dump for most of the conteners but I got a problem when I put put a contener in value of my map. there is my code:

#include <vector>
#include <iterator>
#include <iostream>
#include <list>
#include <string>
#include <array>
#include <map>



template<typename T>
struct has_const_iterator
{
private:
    typedef char                      yes;
    typedef struct { char array[2]; } no;

    template<typename C> static yes test(typename C::const_iterator*);
    template<typename C> static no  test(...);
public:
    static const bool value = sizeof(test<T>(0)) == sizeof(yes);
    typedef T type;
};

template <typename T>
struct has_begin_end
{
    template<typename C> static char (&f(typename std::enable_if<
      std::is_same<decltype(static_cast<typename C::const_iterator (C::*)() const>(&C::begin)),
      typename C::const_iterator(C::*)() const>::value, void>::type*))[1];

    template<typename C> static char (&f(...))[2];

    template<typename C> static char (&g(typename std::enable_if<
      std::is_same<decltype(static_cast<typename C::const_iterator (C::*)() const>(&C::end)),
      typename C::const_iterator(C::*)() const>::value, void>::type*))[1];

    template<typename C> static char (&g(...))[2];

    static bool const beg_value = sizeof(f<T>(0)) == 1;
    static bool const end_value = sizeof(g<T>(0)) == 1;
};

template<typename T> 
struct is_container : std::integral_constant<bool, has_const_iterator<T>::value && has_begin_end<T>::beg_value && has_begin_end<T>::end_value> 
  {};


template<typename T>
void dumpSingle(T const& cont) {
    std::copy(cont.cbegin(), cont.cend(), std::ostream_iterator<typename T::value_type>(std::cout, " "));
    std::cout << "\n";
}

template <typename T, bool U>
class Dump {
 public:
     static void dump(T const& cont) {
        dumpSingle<decltype(cont)>(cont);
    }
};

template<typename T>
class Dump<T, false> {
public:
    static void dump(T const& val) {
        std::cout << val << "\n";
    }
};

template<typename T>
void dumpPair(T const& cont) {
    for (auto pair : cont) {
        std::cout << "[" << pair.first << "]: ";
        Dump<decltype(pair.second), is_container<decltype(pair.second)>::value>::dump(pair.second);
    }
}

int main(int argc, char const *argv[])
{
    std::vector<int> vec = {2, 4, 42, 0, 7};
    dumpSingle<decltype(vec)>(vec);

    std::array<int, 3> arr = {1, 7, 5};
    dumpSingle<decltype(arr)>(arr);

    std::list<std::string> l = {"toto", "tutu", "titi"};
    dumpSingle<decltype(l)>(l);

    std::map<std::string, int> map;

    map["yop"] = 42;
    map["test"] = 25;
    dumpPair<decltype(map)>(map);

    std::map<std::string, std::array<int, 3>> map2;

    map2["yop"] = {42, 258, 72};
    map2["test"] = {77, 42, 21};
    dumpPair<decltype(map2)>(map2); // error here

    return 0;
}

the error message is:

dump.cpp: In instantiation of 'void dumpSingle(const T&) [with T = const std::array<int, 3u>&]':
dump.cpp:59:34:   required from 'static void Dump<T, U>::dump(const T&) [with T = std::array<int, 3u>; bool U = true]'
dump.cpp:75:92:   required from 'void dumpPair(const T&) [with T = std::map<std::basic_string<char>, std::array<int, 3u> >]'
dump.cpp:100:31:   required from here
dump.cpp:51:101: error: 'const std::array<int, 3u>&' is not a class, struct, or union type
  std::copy(cont.cbegin(), cont.cend(), std::ostream_iterator<typename T::value_type>(std::cout, " "));

Can you help me to find why it's not working for this but it's work for all the others tests in my main ?

thread-safe, data-race free, lag-free shared container (circular_buffer)

I face the following situation (which I have to admit I'm too noob to trust myself in solving alone..): I have thread A which occasionally creates new cv::Mat objects for thread B to consume. I need a thread-safe container C (a boost::circular_buffer in this case) which will hold the cv::Mat objects thread A generates. Then, thread B needs to constantly iterate through all items in C to produce an animation. Therefore I need a thread-safe C which will disallow data-races but also cause no (ideally) or very small (if not possible otherwise) lag to thread B's animation -> I dot want thread B to freeze when thread A updates C. The best I could come up with is this:

#include <boost/circular_buffer.hpp>
#include <opencv2/core.hpp>
#include <boost/core/noncopyable.hpp>
#include <memory>
#include <type_traits>
#include <algorithm>

using im_buf = boost::circular_buffer<cv::Mat>;
class ImageBuffer : private boost::noncopyable { 
private:
  im_buf buffer;
  std::mutex mtx;
  std::unique_lock<std::mutex> lock;
public:
  // operator<< accepting cv::Mat, cv::Mat& and cv::Mat&&
  template <class T,
    class = typename std::enable_if
    <std::is_same<cv::Mat, typename std::decay<T>::type>
     ::value>::type>
   void operator<<(T&& mat) {
      lock.lock();
      buffer.push_back(std::forward<T>(mat));
      lock.unlock();
    }
    template <typename Func> // excpect callable objects only
    inline void iterate(Func func) {
      lock.lock();
      std::for_each(buffer.begin(),buffer.end(),func);
      lock.unlock();
    }
    inline ImageBuffer():
      buffer {settings::max_images_in_loop},
      mtx {},
      lock {mtx} {}
    ~ImageBuffer()=default;
    ImageBuffer(const ImageBuffer&&)=delete; 
    ImageBuffer& operator=(const ImageBuffer&&)=delete;  
};

(Note that even if this is not an invariant, thread B is not suppose to mutate C or any of its contents (I'd love to use a const_iterator here but boost::circular_buffer does not provide one..)

Yet, with this code thread B will freeze the entire animation for some time each time thread A adds new elements.. so, a. isn't there some better approach?? b. is implementation truly thread safe?

pointer does not get copied, possible compiler bug?

In n yers of C++ I've never stumbled upon something as strange as this:

struct whatever {
    whatever *ptr;    
};

set<whatever*> s;

...populate s with valid pointers..

for(whatever *t : s) {
    whatever *h = t,e = t->ptr;

    func(h,e); //<- CRASH (h is garbage)
}

now, in GDB:

print t
(whatever*)0x818c7e0
print t->ptr
(whatever*)0x7ea2430
print e
(whatever*)0x7ea2430
print h
(whatever*)0x10000ff00010101

this is clearly absurd.. t is not copied into h, but t->ptr is copied into e..

the function is correctly executed millions of times, but at some random point it crashes with this behaviour.

note that stepping through the set gives valid pointers, infact t is initialized accordingly..

someone has an idea of whats going on here? icpc on mint 17 + gdb 7.9

Accumulating into std::ostream using std::accumulate

I am trying to use std::accumulate to write into std::ostream in the operator<< (this is just a minimum example, I know this could be implemented much simpler):

#include <iterator>
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>

struct A {
    A() : v(std::vector<int>()){};
    std::vector<int> v;
    A(std::vector<int> v) : v(v){};
    friend std::ostream& operator<<(std::ostream& stream, A& a);
};

std::ostream& operator<<(std::ostream& stream, A& a) {
// I need something similar to
//    return std::accumulate(a.v.begin(), a.v.end(), "",
                           std::ostream_iterator<int>(stream, " "));
// or:
// return std::accumulate(a.v.begin(), a.v.end(), stream,
                           []()->{});
}

int main(int argc, char* argv[]) {
    std::vector<int> v({1, 2, 3, 4, 5});
    A a(v);
    std::cout << a << std::endl;

    return 0;
}

How can I make this operator work?

jeudi 28 janvier 2016

C++ standard library forward_list issue

I need some help solving the exercise 9.28 from the C++ Primer 5th edition. Here is the task:

Write a function that takes a forward_list and two additional string arguments. The function should find the first string and insert the second immediately following the first. If the first string is not found, then insert the second string at the end of the list.

I can't get the idea written in the book as to how forward_list actually works and why we indeed need it, so I'm asking for help. Below is the code I wrote which is incomplete and I need someone help me finish it:

#include <iostream>
#include <forward_list>

using namespace std;

void find_and_insert(forward_list<string>& flstr, const string& needle, const string& rplc) {

    auto curr = flstr.begin();
    auto last = flstr.end();
    bool found = false;

    while (curr != last) {

        if (*curr == needle) {

            found = true;
            // what to put here?!
            break;
        }

        // what to put here?!... 
        ++curr;
    }

    for (const auto& elem : flstr) {

        cout << elem << endl;
    }

    return;
}

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

    cout << endl;

    forward_list<string> flstring = {"Foo", "Bar", "Baz", "Tomcat"};

    find_and_insert(flstring, "Bar", "Insertion");

    cout << endl;

    return EXIT_SUCCESS;
}

Any suggestion to refactor the code is welcome!

I want to highlight the border of a sprite .

I want to highlight a border of a sprite. I have a sprite type variable "m_sprImage" in which I want to highlight border.

I used below codes but not highlighting as per my game requirement.

  TintTo* action = TintTo::create(0.1f, 255, 0, 0);
   TintTo* actionReverse = TintTo::create(5.5f, oldColor.r, oldColor.g,oldColor.b);;
   TintTo* actionReverse = TintTo::create(10.0f, 255, 255, 255);;
   m_sprImage->runAction(Sequence::create(action, actionReverse, NULL));
   m_sprImage->setOpacity(255);

Error implementing Caesar Cipher Using C++

I am trying to implement Caesar Cipher using C++. The directions are to use this file which is already encrypted:

5
Asi ymj rtrjwfymjx tzylwfgj.
Aqq rnrxd bjwj ymj gtwtlwtajx
Dni ldwj fsi ldrgqj ns ymj bfgj.
Tbfx gwnqqnl fsi ymj xnymjd ytajx

The number 5 represents the shift that is applied to the text. I have to decode the Caesar ciphered text and reverse the lines as in put line 4 in line 1's position and line 3 in line 2's. The first letter of each line does not need to be decoded (the uppercase letters).

The text should look like this after running the program:

Twas brillig and the sithey toves
Did gyre and gymble in the wabe.
All mimsy were the borogroves
And the momerathes outgrabe.

As of right now, I have this code:

#include <iostream>
#include <vector>
#include <string>
#include <fstream>

using namespace std;

char decipher (char c, int shift);

int main(){
    //declare variables
    char c;
    string deciphered = "";
    int shift;
    vector <string> lines;

    //ask for filename and if not found, keep trying
    ifstream inFile;
    string filename;
    cout << "What is the name of the file? ";
    cin >> filename;
    inFile.open(filename);
    while (!inFile){
        cout << "File not found. Try again: ";
        cin >> filename;
        inFile.open(filename);
    }

    //find shift from file
    inFile >> shift;

    //get lines from file
    inFile >> noskipws;
    while (inFile >> c){
        char decipheredChar = decipher (c, shift);
        deciphered += decipheredChar;
    }
    cout << deciphered;

}

char decipher (char c, int shift){
    string letters = "abcdefghijklmnopqrstuvwxyz";
    if (c == 'T'){
        return c;
    }
    else if (c == 'D'){
        return c;
    }
    else if (c == 'A'){
        return c;
    }
    else if (c == ' '){
        return c;
    }
    else {
        int currentPosition = letters.find(c);
        int shiftedPosition = currentPosition - shift;
        if (shiftedPosition < 0){
            shiftedPosition = 26 + shiftedPosition;
        }
        char shifted = letters[shiftedPosition];
        return shifted;
    }
}

The result I'm getting is this:

uAnd the momerathes outgrabeuuAll mimsy were the borogrovesuDid gyre and gymble in the wabeuuTwas brillig and the sithey tovesu

How do I get rid of the u's and also separate the words by line? I have an idea of reversing the lines using a vector and using a loop counting backwards but I'm not sure how to get to there yet. Please help. Thank you.

How to disable default setting for File Type and to modify it in Linux?

When i save a file such as filename.amf, but output file type "XML document (application/xml)" instead of "AMF type/amf"

Write a pass to replace all llvm instructions

I'm trying to write an llvm pass to replace all BinaryOperator instructions by a multiplication, the problem is that only the 1st instruction is replaced:

virtual bool runOnFunction(Function &F) {
  for (auto &B : F) {
     for (BasicBlock::iterator DI = B.begin(); DI != B.end(); ) {
      Instruction *Inst = DI++;

      if (auto *op = dyn_cast<BinaryOperator>(&*Inst)) {
        // Insert at the point where the instruction `op` appears.
        IRBuilder<> builder(op);

        // Make a multiply with the same operands as `op`.
        Value *lhs = op->getOperand(0);
        Value *rhs = op->getOperand(1);
        Value *mul = builder.CreateMul(lhs, rhs);

        // Everywhere the old instruction was used as an operand, use our
        // new multiply instruction instead.
        for (auto &U : op->uses()) {
          User *user = U.getUser();  // A User is anything with operands.
          user->setOperand(U.getOperandNo(), mul);
        }


        // We modified the code.
        return true;
      }


    }
  }

  return false;
}

STL sequential containers support insert (before) whereas forward_list support insert_after

STL sequential containers like vector, deque, list support insert to insert elements before given iterator to support statements like

vector.insert(std::end(container), container2.begin(), container2.end())

Whereas forward_list supports insert_after. Why STL maintainers had to make this design choice?

static member function make_shared of shared_ptr

Using libc++ I find out std::shared_ptr::make_shared() static member function in public section. It is very handy when I have already defined type alias to std::shared_ptr's specialization:

using T = int;
using P = std::shared_ptr< T >;
auto p = P::make_shared(123); // <=> std::make_shared< T >(123)

I'm worry about standard compliance, because articles (1, 2) from trusted source mentions nothing about static member function make_shared of std::shared_ptr.

Is it bad parctice to use the function currently? Why?

std::atomic_store and std::atomic_exchange do not exchange

According to en.cppreference.com, std::atomic_exchange and std::atomic_store are equivalent to a thread-safe std::swap. But that's not the behavior that I'm getting with g++ or clang++.

Problem live on coliru.(see below)

It prints this though:

std::atomic_store

a: 0x1ed2c30    0
b: 0x1ed2c50    1

a: 0x1ed2c50    1
b: 0x1ed2c50    1

std::atomic_exchange

a: 0x1ed2c50    0
b: 0x1ed2c30    1

a: 0x1ed2c30    1
b: 0x1ed2c30    1

Why is this? Am I doing something wrong? Have I misread the documentation?

Code Listing

#include <iostream>
#include <memory>

int main()
{
    {
        std::cout << "std::atomic_store\n\n";
        auto a = std::make_shared<int>(0);
        auto b = std::make_shared<int>(1);

        std::cout
        << "a: " << a.get() << '\t' << *a << '\n'
        << "b: " << b.get() << '\t' << *b << '\n' << std::endl;

        std::atomic_store(&a, b);

        std::cout
        << "a: " << a.get() << '\t' << *a << '\n'
        << "b: " << b.get() << '\t' << *b << '\n' << std::endl;
    }
    {
        std::cout << "std::atomic_exchange\n\n";
        auto a = std::make_shared<int>(0);
        auto b = std::make_shared<int>(1);

        std::cout
        << "a: " << a.get() << '\t' << *a << '\n'
        << "b: " << b.get() << '\t' << *b << '\n' << std::endl;

        std::atomic_exchange(&a, b);

        std::cout
        << "a: " << a.get() << '\t' << *a << '\n'
        << "b: " << b.get() << '\t' << *b << '\n' << std::endl;
    }
}

Are std::get<> and std::tuple<> slower then raw pointers?

I have an C++11 application where I commonly iterate over several different structure of arrays for various algorithms. Raw CPU performance is important for this app.

The array elements are fundamental types (int, double, ..) or simple struct. The array are typically tens of thousands of elements long. I often need to iterate several arrays at once in a given loop. So typically I would need one pointer for each array of whatever type. So times I need to increment five individual pointers which is verbose.

Based on these answers about tuples, Why is std::pair faster than std::tuple C++11 tuple performance I hoped there was no overhead to using tuples to pack the pointers together into a single object.

I thought it might be nice to implement a cursor like object to assist in iterating, since missing the increment on a particular pointer would be an annoying bug.

auto pts = std::make_tuple(p1, p2, p3...); allow you to bundle a bunch of variables together in a typesafe way. Then you can implement a variadic template function to increment each pointer in the tuple in a type safe way.

However... When I measure performance, the tuple version was slower then using raw pointers. But when I look at the generated assembly I see additional mov instructions in the tuple loop increment. Maybe due to the fact the std::get<> returns a reference? I had hoped that would be compiled away...

Am I missing something or are raw pointers just going to beat tuples when used like this? Here is a simple test harness. I threw away the fancy cursor code and just use a std::tuple<> for this test

On my machine, the tuple loop is consistently twice as slow as the raw pointer version for various data sizes.

My system config is Visual C++ 2013 x64 on Windows 8 with a release build. I did try turning on various optimization in Visual Studio such as Inline Function Expansion : Any Suitable (/Ob2) but it did not seem to change the time result for my case.

I did need to do two extra things to avoid aggressive optimization by VS
1) I forced the test data array to allocated on the heap, not the stack. That made a big difference when I timed things, possibly due to memory cache effects.
2) I forced a side effect by writing to static variable at the end so the compiler would not just skip my loop.

struct forceHeap
{
    __declspec(noinline) int* newData(int M)
    {
        int* data = new int[M];
        return data;
    }    
};

void timeSumCursor()
{
    static int gIntStore; 
    int maxCount = 20;
    int M = 10000000; 
    // compiler might place array on stack which changes the timing
    // int* data = new int[N];         
    forceHeap fh;
    int* data = fh.newData(M);
    int *front = data; 
    int *end = data + M;

    int j = 0;
    for (int* p = front; p < end; ++p)
    {
        *p = (++j) % 1000;
    }

    {
        BEGIN_TIMING_BLOCK("raw pointer loop", maxCount);
        int* p = front;
        int sum = 0;
        int* cursor = front;
        while (++cursor != end)
        {
            sum += *cursor;
        }
        gIntStore = sum;// force a side effect
        END_TIMING_BLOCK(); 
    }
    printf("%d\n", gIntStore);

    {
        // just use a simple tuple to show the issue 
        // rather full blown cursor object
        BEGIN_TIMING_BLOCK("tuple loop", maxCount);
        int sum = 0;
        auto cursor = std::make_tuple(front);
        while (++std::get<0>(cursor) != end)
        {
            sum += *std::get<0>(cursor);
        }
        gIntStore = sum; // force a side effect
        END_TIMING_BLOCK();
    }
    printf("%d\n", gIntStore);

    delete[] data;
}

Is it possible to avoid repetition of std::move() on a tuple?

Let's say I have a tuple and a function:

typedef std::tuple< std::unqiue_ptr<int>, std::unqiue_ptr<char> > SomeTuple;          
void someFunction( std::unqiue_ptr<int>, std::unqiue_ptr<char> );

so in a helper function I am unrolling tuple into arguments:

void unroll( SomeTuple &t )
{
    someFunction( std::get<0>( std::move( t ) ), std::get<1>( std::move( t ) ) );
}

It works, but I want to avoid repeating of std::move multiple times. Naive solutions like:

void unroll( SomeTuple &t )
{
    auto &&rt = std::move( t );
    someFunction( std::get<0>( rt ), std::get<1>( rt ) );
}

obviosly does not work, as rt is a lvalue. So is there a way to avoid repeating std::move() multiple times for each std::get?

Detecing class member with specific signature

I have Class A with functions with different signatures. I would like to detect if specific signature exists and if it does call it and call some other more generic function if it doesn`t.

#include <iostream>
#include <type_traits>

template < class T >
struct has_fun_with_bool;

class B {};
class C {};
class D {};

class A
{
public:
    void fun (B b) { std::cout<<"B without bool " << std::endl; };
    void fun (B b, bool f) { std::cout<<"B with bool: " << f << std::endl; };
    void fun (C b) { std::cout<<" C without bool "<< std::endl; };
    void fun (D d ,bool f ) { std::cout<<"D with bool: "<< f <<std::endl;

    template <class T>
    void bar(T in, const bool b = false) {
        fun (in, b); or fun (in);
    }
};


int main()
{
    A a;
    B b;
    C c;
    D d;
    a.bar(b);
    a.bar(c);
    a.bar(d);

return 0;
}

For A bar should use fun with bool parameter, for C without and for D with.

Performance hit from using std::find

I have the following code to check whether a value belongs to a list of values. eg: contains({1,2,3},3). Almost always, I could write a bunch of if-elses. How much performance hit does the contains approach create? Is there a way to avoid this?

template<typename T1,typename T2>
std::enable_if_t<std::is_same<std::initializer_list<T2>,T1>::value, bool> contains(const T1 &container,const T2 &item)
{
    return(std::find(container.begin(),container.end(),item)!=container.end());
}

What are the benefits of constexpr char[] as a class member?

It is more of the rhetorial question (and a rant). Pre-11 everytime I had to make a library which exhibited static const char* const (as in static const char* const class_name = "ClassA";) as class members, I knew the library could no longer be header-only - I had to provide a .cpp file with a definition of this variable and it's value.

So instead, I had to turn it into the static function name(), returning the pointer.

Than C++11 came, and now I can have static constexpr char[] as my meber - and I can even give it a value in my header! But I still have to provide the definition... so I am not excited at all.

Why would that be the case? If constexpr can be evaluated by compiler at compile time, why do I need a definition of it? Why does it have to have linkage at all?

C++ - Producer / Consumer only allow consumption in defined chunks

There's two threads A (Producer) and B (Consumer).

The data A produces is only meant to be read in chunks, hence B shall only be allowed to read once A has produced a whole chunk. A single piece of data is a simple struct and the chunk length is variable. For example once it could be that B is allowed to read after 50 pieces of data are produced, another time it might be 200.

I've found this implementation of a producer/consumer queue that I'd like to use: http://ift.tt/1wsl4Cd

My current idea is that A writes its data into a std::vector and then pass the std::vector into the queue. But I doubt this works since the queue does not know how much memory an std::vector will take and it wants to allocate the memory beforehand.

I hope anybody knows an easier solution for this.

Cannot iterate over map whose elements hold a uniq_ptr

The following code fails to compile:

#include <iostream>
#include <memory>
#include <map>

struct HaveUniq {
    std::unique_ptr<int> uniq;
};

void print_hus(const std::map<int, HaveUniq>& hus) {
    for (const std::pair<int, HaveUniq>& p: hus)
        std::cout << *p.second.uniq << std::endl;
}

int main() {
    std::map<int, HaveUniq> hus;
    for (int i = 0; i < 10; ++i)
        hus[i].uniq = std::unique_ptr<int>(new int(i));
    print_hus(hus);
}

With the following error:

uniq_wtf.cpp: In function ‘void print_hus(const std::map<int, HaveUniq>&)’:
uniq_wtf.cpp:10:42: error: invalid initialization of reference of type 
‘const std::pair<int, HaveUniq>&’ from expression of type
‘const std::pair<const int, HaveUniq>’
for (const std::pair<int, HaveUniq>& p: hus)

So, it tries to iterate over values rather than constant references, and it cannot coerce those values into references.

It is clear that an objects that has a unique_ptr as one of its fields cannot have a default copying constructor. But if I understand correctly, iterating over a map doesn't involve copying, so it shouldn't be a problem. Or does the map iterator actually copy the values? And why would it have problem with coercing values to references?

By the way, the code works if the unique_ptr is replaced with simple integer, and if the map is replaced with std::array.