mardi 28 février 2017

Use operator== and initializer-list

For example

template<class Container, class T>
bool operator==(Container const& c, std::initializer_list<T> const& l)
{
    return c.size() == l.size() && equal(c.begin(), c.end(), l.begin());
}

Check by

std::vector<int> v = {1, 2};
bool b = operator==(v, {1, 2}); // okay
b = (v == {1, 2}); // Error

Why? and How to fix it?

How to compare a container and a initializer-list to see if they are equal?

For example

template<class Container, class List>
bool isEqual(Container const& c, List const& l)
{
    return c == Container(l); // Error!!
}

And check by

std::vector<int> v;
bool b = isEqual(v, {1, 2, 3});

But error in my code. No conversion from list to container. How to fix the bug?

Counting case-sensitive words in a string using C++

I want to count how many case-sensitive words are in string 's'. So far, I've transformed the punctuations into spaces and added each separate word in a set. Since, set only includes only unique elements, I am getting output 1.

How can I check the case-sensitivity of the words in string s?

int main() {
    string s = "ab\nAB!ab?AB:ab.AB;ab\nAB";

    transform(s.begin(), s.end(), s.begin(), [](char c)->char {
        if (isWordSeparator(c))
            return ' ';
    });

    istringstream iss(s);

    set<string> words((istream_iterator<string>(iss)), istream_iterator<string>());



    cout << "Number of Words: " << words.size() << endl;

    return 0;
}

Creating a set of sets of objects in C++

I am trying to create a set of set of objects, but am having an error message with how I use the -> with iterator k. I think I have to define some overloaded operators before I use this? I can't seem to find any resources online about my specific problem.

My error message is

no instance of overloaded function "std::set<_Kty, _Pr, _Alloc>::insert [with _Kty=Triangles, _Pr=std::less<Triangles>, _Alloc=std::allocator<Triangles>]" matches the argument list and object (the object has type qualifiers that prevent a match)

std::set<std::set<Triangles>>::iterator k;
for (k = setofTriangles.begin(); k != setofTriangles.end(); k++) {
    double v1query = k -> begin() -> getV1()[1];
    double v2query = k -> begin() -> getV2()[1];
    double v3query = k -> begin() -> getV3()[1];

    double iterYMax = std::max(v1query, std::max(v2query,v3query));             
    if (iterYMax == triangleYMax) {
        k -> insert(addTriangle);
    }
}

Please let me know if you need more information. Thank you.

Changing vector inside std::for_each on the same vector

I want to figure out if it is allowed to change the vector inside for_each. Consider the code:

std::vector<int> v;
for (int i = 0; i < 10; i++) v.push_back(i);

for (auto &i : v) std::cout << i << " ";
std::cout << std::endl;
std::transform(v.begin(), v.end(), std::back_inserter(v),
          [](auto i) { return i;});

for (auto &i : v) std::cout << i << " ";
std::cout << std::endl;

I expect to expand vector with elements which are base on exist vector contents. Here is the output:

0 1 2 3 4 5 6 7 8 9 
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 

But if I replace begin and end with rbegin and rend correspondingly the output is following:

0 1 2 3 4 5 6 7 8 9 
0 1 2 3 4 5 6 7 8 9 9 8 7 6 5 4 3 2 0 0

I get unexpected 0 instead of 1 in a position before last. This makes me wonder if this code is a UD per se, and I should not rely on correct output with forward iterators.

FLTK incorporating FL_window title into FL_input

How to incorporate FL_window title into FL_input and add custom icons on the dialog boxes instead of the system defaults.

#include <FL/Fl.H>
#include <FL/fl_ask.H>
#include <FL/Fl_Input.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Widget.H>
#include <FL/Fl_Text_Display.H>
#include <iostream>

using namespace std;

int main()
{
    Fl_Window beacon (1,1);
    beacon.show();

fl_input("===============================\n"
        "Library Management System\n"
        "===============================");
//return (Fl::run());
}

Efficiently moving contents of std::unordered_set to std::vector

In my code I have a std::unordered_set and I need to move the data into a std::vector. I'm using the std::unordered_set while getting the data to ensure only unique values are stored prior to converting to a std::vector. My question is how do I move the contents to the std::vector the most efficiently? I don't need the std::unordered_set after the data is moved. I currently have the following:

std::copy(set.begin(), set.end(), std::back_inserter(vector));

Poco C++ Libraries: "Not found: mysql"

i am using poco-1.7.7 with MySQL. I am building with g++ on Ubuntu. Building, linking and running works fine. However, when a Data Session is created, an exception "Not found: mysql" is thrown:

std::string str = Poco::format("host=%s;user=%s;password=%s;compress=true;auto-reconnect=true;secure-auth=true", _mySQLParams.host, _mySQLParams.user, _mySQLParams.password);
_session = new Poco::Data::Session(Poco::Data::SessionFactory::instance().create(Poco::Data::MySQL::Connector::KEY, str));

The mysql client is installed and is part of $PATH.

Additional information: I am running Ubuntu using Docker. See below for Makefile. The same code can connect to MySQL when i compile and run on MacOSX.

Do you have any idea what is going wrong here?

--

Snippet from Makefile:

CXX=g++
HEADER_SEARCH_PATH=-I"../../Core/Application/" -I"../../Core/Model/" -I"../../Core/Object/" -I"../../Core/UserInterface/" -I"/usr/local/include/" -I"/usr/include/mysql"
LIB_SEARCH_PATH=-L/usr/local/lib -L/usr/lib/x86_64-linux-gnu
LIBS=-l"PocoJSON" -l"PocoXML" -l"PocoUtil" -l"PocoNet" -l"PocoFoundation" -l"crypto" -l"ssl" -l"PocoCrypto" -l"PocoData" -l"PocoDataMySQL" `pkg-config --libs --cflags icu-uc icu-io`
PPD=-DMPS_MYSQL=1
CXXFLAGS=-std=c++11 -g -m64 -pthread -Wl,--verbose -fabi-version=2 -fno-omit-frame-pointer $(HEADER_SEARCH_PATH) $(PPD)

malloc error when using std::shared_ptr

I've decided to parallelize a huge program I wrote and eventually I came across the new C++11 smart pointers.

I had a routine that should be executed many times (usually above 1000 times) that is somewhat expensive. It was ran in a dead simple for loop, what I did was to install this for loop in a method which would be ran by some worker threads.

Did it so, made some parameters wrapped by a std::shared_ptr, cared for race conditions, everything seemed fine.

But now, some times, process will be aborted and I am given one of the following errors:

Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)

or

malloc.c:2395: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed.

All of these errors occur while the parallel for is ongoing; not before, not right in the beginning, not in the end, but somewhere in between, which smells me like a race condition not covered.

The program is huge, but I created a miniature of it that is able to reproduce the problem:

#include <iostream>
#include <vector>
#include <unordered_map>
#include <thread>
#include <set>
#include <memory>
#include <atomic>

namespace std {
    template <>
    struct hash<std::multiset<unsigned long>>
    {
        std::size_t operator()(const std::multiset<unsigned long>& k) const
        {
            std::size_t r = 0;

            bool shift = false;
            for (auto&& it : k) {
                r = (r >> !shift) ^ (std::hash<unsigned long>()(it) << shift);
                shift = !shift;
            }

            return r;
        }
    };
}

typedef std::unordered_map<std::multiset<unsigned long>, int*> graphmap;

std::multiset<unsigned long>* bar(int pos) {
    std::multiset<unsigned long> *label = new std::multiset<unsigned long>;

    label->insert(pos%5);
    label->insert(pos%2);

    return label;
}

void foo(std::shared_ptr<graphmap> &kSubgraphs, int pos) {
    int *v = (*kSubgraphs)[*bar(pos)];

    if(v == nullptr) {
        v = new int[pos+1]();
        v[0]++;
    } else {
        v[pos]++;
    }
}

void worker(std::shared_ptr<std::atomic_int> *counter, int n, std::shared_ptr<graphmap> *kSubgraphs)
{
    for (int pos = (*counter)->fetch_add(1); pos <= n; pos = (*counter)->fetch_add(1)) {
        if (pos%100==0) std::cout << pos << std::endl;
        foo(*kSubgraphs, pos);
    }
}

int main() {
    int n = 1000;

    std::vector<std::thread> threads;
    std::shared_ptr<graphmap> kSubgraphs = std::make_shared<graphmap>();
    std::shared_ptr<std::atomic_int> counter = std::make_shared<std::atomic_int>(0);
    for (int i=0; i<5; i++) {
        foo(kSubgraphs, n);
    }

    for (int i=0; i<4; i++) {
        threads.push_back(std::thread(worker, &counter, n, &kSubgraphs));
    }

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

    return 0;
}

This code basically mimics the behavior of the original code, which is to use an unordered_map keyed by a multiset with values that are pointers to int arrays. First some keys are inserted and the array initialized (maybe the problem is caused by the way I am initializing it?) and finally the worker threads run to update a unique position of the array of an entry of the unordered_map.

Two threads may access the same map entry simultaneously, but they will never write to the same index of the array at the same time.

Different from the original code, this code won't throw any errors when running over internet compilers such as ideone.com, I also tried to run it from CLion ide and no errors will occur (maybe it can occur errors if one tries enough times), but I got similar error as the original when running from the command line multiple times. I compiled it with:

g++ -std=c++11 -pthread -o test.exe test.cpp

And after running several times it eventually gives this error:

*** Error in `./test.exe': double free or corruption (fasttop): 0x00000000006a2d30 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x77725)[0x7fccc9d4f725]
/lib/x86_64-linux-gnu/libc.so.6(+0x7ff4a)[0x7fccc9d57f4a]
/lib/x86_64-linux-gnu/libc.so.6(cfree+0x4c)[0x7fccc9d5babc]
./test.exe[0x404e9e]
./test.exe[0x40431b]
./test.exe[0x4045ed]
./test.exe[0x407c6c]
./test.exe[0x4078d6]
./test.exe[0x40742a]
./test.exe[0x40869e]
./test.exe[0x4086be]
./test.exe[0x4085dd]
./test.exe[0x40842d]
./test.exe[0x4023a2]
./test.exe[0x401d55]
./test.exe[0x401c4a]
./test.exe[0x401c66]
./test.exe[0x401702]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0)[0x7fccc9cf8830]
./test.exe[0x401199]
======= Memory map: ========
00400000-0040f000 r-xp 00000000 08:05 12202697                           /home/rodrigo/test.exe
0060e000-0060f000 r--p 0000e000 08:05 12202697                           /home/rodrigo/test.exe
0060f000-00610000 rw-p 0000f000 08:05 12202697                           /home/rodrigo/test.exe
00691000-006c3000 rw-p 00000000 00:00 0                                  [heap]
7fcca8000000-7fcca8089000 rw-p 00000000 00:00 0 
7fcca8089000-7fccac000000 ---p 00000000 00:00 0 
7fccb0000000-7fccb008b000 rw-p 00000000 00:00 0 
7fccb008b000-7fccb4000000 ---p 00000000 00:00 0 
7fccb8000000-7fccb8089000 rw-p 00000000 00:00 0 
7fccb8089000-7fccbc000000 ---p 00000000 00:00 0 
7fccc0000000-7fccc007c000 rw-p 00000000 00:00 0 
7fccc007c000-7fccc4000000 ---p 00000000 00:00 0 
7fccc79cb000-7fccc79cc000 ---p 00000000 00:00 0 
7fccc79cc000-7fccc81cc000 rw-p 00000000 00:00 0 
7fccc81cc000-7fccc81cd000 ---p 00000000 00:00 0 
7fccc81cd000-7fccc89cd000 rw-p 00000000 00:00 0 
7fccc89cd000-7fccc89ce000 ---p 00000000 00:00 0 
7fccc89ce000-7fccc91ce000 rw-p 00000000 00:00 0 
7fccc91ce000-7fccc91cf000 ---p 00000000 00:00 0 
7fccc91cf000-7fccc99cf000 rw-p 00000000 00:00 0 
7fccc99cf000-7fccc9ad7000 r-xp 00000000 08:05 24126366                   /lib/x86_64-linux-gnu/libm-2.23.so
7fccc9ad7000-7fccc9cd6000 ---p 00108000 08:05 24126366                   /lib/x86_64-linux-gnu/libm-2.23.so
7fccc9cd6000-7fccc9cd7000 r--p 00107000 08:05 24126366                   /lib/x86_64-linux-gnu/libm-2.23.so
7fccc9cd7000-7fccc9cd8000 rw-p 00108000 08:05 24126366                   /lib/x86_64-linux-gnu/libm-2.23.so
7fccc9cd8000-7fccc9e98000 r-xp 00000000 08:05 24126374                   /lib/x86_64-linux-gnu/libc-2.23.so
7fccc9e98000-7fccca097000 ---p 001c0000 08:05 24126374                   /lib/x86_64-linux-gnu/libc-2.23.so
7fccca097000-7fccca09b000 r--p 001bf000 08:05 24126374                   /lib/x86_64-linux-gnu/libc-2.23.so
7fccca09b000-7fccca09d000 rw-p 001c3000 08:05 24126374                   /lib/x86_64-linux-gnu/libc-2.23.so
7fccca09d000-7fccca0a1000 rw-p 00000000 00:00 0 
7fccca0a1000-7fccca0b9000 r-xp 00000000 08:05 24126373                   /lib/x86_64-linux-gnu/libpthread-2.23.so
7fccca0b9000-7fccca2b8000 ---p 00018000 08:05 24126373                   /lib/x86_64-linux-gnu/libpthread-2.23.so
7fccca2b8000-7fccca2b9000 r--p 00017000 08:05 24126373                   /lib/x86_64-linux-gnu/libpthread-2.23.so
7fccca2b9000-7fccca2ba000 rw-p 00018000 08:05 24126373                   /lib/x86_64-linux-gnu/libpthread-2.23.so
7fccca2ba000-7fccca2be000 rw-p 00000000 00:00 0 
7fccca2be000-7fccca2d4000 r-xp 00000000 08:05 24121519                   /lib/x86_64-linux-gnu/libgcc_s.so.1
7fccca2d4000-7fccca4d3000 ---p 00016000 08:05 24121519                   /lib/x86_64-linux-gnu/libgcc_s.so.1
7fccca4d3000-7fccca4d4000 rw-p 00015000 08:05 24121519                   /lib/x86_64-linux-gnu/libgcc_s.so.1
7fccca4d4000-7fccca646000 r-xp 00000000 08:05 6029347                    /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21
7fccca646000-7fccca846000 ---p 00172000 08:05 6029347                    /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21
7fccca846000-7fccca850000 r--p 00172000 08:05 6029347                    /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21
7fccca850000-7fccca852000 rw-p 0017c000 08:05 6029347                    /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21
7fccca852000-7fccca856000 rw-p 00000000 00:00 0 
7fccca856000-7fccca87c000 r-xp 00000000 08:05 24126370                   /lib/x86_64-linux-gnu/ld-2.23.so
7fcccaa44000-7fcccaa4a000 rw-p 00000000 00:00 0 
7fcccaa78000-7fcccaa7b000 rw-p 00000000 00:00 0 
7fcccaa7b000-7fcccaa7c000 r--p 00025000 08:05 24126370                   /lib/x86_64-linux-gnu/ld-2.23.so
7fcccaa7c000-7fcccaa7d000 rw-p 00026000 08:05 24126370                   /lib/x86_64-linux-gnu/ld-2.23.so
7fcccaa7d000-7fcccaa7e000 rw-p 00000000 00:00 0 
7ffc6b1c8000-7ffc6b1e9000 rw-p 00000000 00:00 0                          [stack]
7ffc6b1fa000-7ffc6b1fc000 r--p 00000000 00:00 0                          [vvar]
7ffc6b1fc000-7ffc6b1fe000 r-xp 00000000 00:00 0                          [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]
[1]    26639 abort (core dumped)  ./test.exe

At last, when running the original code with debug mode on in CLion set up to capture Exceptions as breakpoints, it shows a Signal interruption of SIGBUS(Bus error) or a SIGSEGV(Segmentation fault) sometimes and last line of code executed before the interruption maps to the line:

    int *v = (*kSubgraphs)[*bar(pos)];

in the foo function of the code presented here.

I am a little bit lost with this one. My strongest assumption is that I am using smart pointers the wrong way, despite I do not see where.

c++ lambda callback to trigger event

I have been trying to wrap my head around the callback functionality in c++. What I am trying to achieve is the following:

I have two objects, each one with its own thread. One object A has a pointer to the second object B. See example:

class A
{
  public:
   // ...
  private:
   std::unique_ptr<B> b;
};

class B
{
  public:
   void add_message(MessageType msg);
   // ...
};

What I am trying to achieve is having object A add a message using the pointer to B and then continue doing other stuff, but having a callback or handler or something that gets triggered when B has a reply to that message. B does some processing with the message and might pass it to other objects for processing on its own thread but eventually will come up with a reply. So how can I know when B has a reply to my message, for example:

// In class A
MessageType m();
b->add_message(m)
// A's thread continues doing other stuff
...
// some notification that b has a reply?

I know I might have to use std::function for a callback which I would like to use but I can't get my head around how exactly to do this by looking at a lot of examples already. Any help is appreciated and note that I have looked at a lot of examples but can't tie it back to what I am trying to achieve or am not understanding...

I just can not understand DR 712

DR 712 was responsible for the change in the wording of [basic.def.odr]/2 in C++11 to the current wording today, in [basic.def.odr]2 and 3. But I'm still trying to understand the reason for the change, as stated in the DR, as follows:

712. Are integer constant operands of a conditional-expression “used?”

In describing static data members initialized inside the class definition, 9.2.3.2 [class.static.data] paragraph 3 says,

The member shall still be defined in a namespace scope if it is used in the program...

The definition of “used” is in 3.2 [basic.def.odr] paragraph 1:

    An object or non-overloaded function whose name appears as a potentially-evaluated
    expression is used unless it is an object that satisfies the requirements for appearing in a     constant expression (5.20 [expr.const]) and the lvalue-to-rvalue conversion (4.1 [conv.lval])
    is immediately applied.

Now consider the following example:

 struct S {
      static const int a = 1;
      static const int b = 2;
 };
 int f(bool x) {
      return x ? S::a : S::b;
 }

According to the current wording of the Standard, this example requires that S::a and S::b be defined in a namespace scope. The reason for this is that, according to 5.16 [expr.cond] paragraph 4, the result of this conditional-expression is an lvalue and the lvalue-to-rvalue conversion is applied to that, not directly to the object, so this fails the “immediately applied” requirement. This is surprising and unfortunate, since only the values and not the addresses of the static data members are used. (This problem also applies to the proposed resolution of issue 696.)

Well, if the "immediately applied requirement fails, then the expressions S::a and S::b in the conditional expression are not used (odr-used), and so, the respective static members of struct S will not need to be defined in namespace scope. But this is exactly the opposite of what the DR is saying. What am I missing???

How to use c99 standard for c files and c++14 with cpp file in a clang front-end tool

I have created a clang front-end tool using libtooling for static analysis. Now I have a source directory which contains both c and cpp files. When I run the tool with this source directory as input, by default for cpp files c++14 standard is used. And for c files there is no mention of standard in clang command. But I want that c99 standard should be used for all the c files. So can we do it in clang front-end tool?

Thanks in advance.

Thanks, Hemant Bhagat

Assigning a vector to a single element

Consider std::vector<T> for some type T. I receive a pointer to such a type into a function, and also an instance of T; t say.

My function looks like this:

void bar(std::vector<T>* foo, const T& t)
{
    foo->clear();
    foo->push_back(t);
}

Is there a way I write the function body in one statement? *foo = t; does not work due to an appropriate assignment operator not existing. I was also thinking of using

foo->assign(&t, &t + 1);

but that seems naughty.

I'm using C++11.

gcc using c++11 standard even though 98 explicitely specified

I'm getting a strange error I suspect has to do with my system configuration. I am compiling/linking a trivial c++ program using g++ --version = g++ (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609. The default language standard is documented to be c++98, yet even with the -std=c++98 option specified, I am seeing c++11 symbols in the output .o file. This is my test.cpp:

#include <string>
int main() {
  std::string str = "Hello World!";
  return 0;
}

Here are my compile and link commands (with presumably unnecessary explicit language standard option) and associated output:

$ g++ -c -Wall -std=c++98 -o test.o test.cpp
$ g++ -Wall -std=c++98 -o test test.o
$ nm -C test.o
                 U __gxx_personality_v0
0000000000000000 T main
                 U __stack_chk_fail
                 U _Unwind_Resume
                 U std::allocator<char>::allocator()
                 U std::allocator<char>::~allocator()
                 U std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&)
                 U std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()

Notice the references to __cxx11::*. I presume those are c++11 symbols that the compiler inserted. I get a successful build, but apparently using c++11. Here is the output from ldd:

$ ldd test
    linux-vdso.so.1 =>  (0x00007ffc381f5000)
    libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f6548d48000)
    libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f6548b32000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f6548768000)
    libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f654845f000)
    /lib64/ld-linux-x86-64.so.2 (0x000055785493c000)

For my real project, I have to link to third party libs that are c++98 but am unable to do so because of this compiler issue. My object files are looking for c++11 symbols in those libs but can't find them. Any insights?

Functions signatures differences C++

Could you explain me which are the differences between these three functions signatures? Why can auto be used as returned data type and not in parameters declarations? Thank you.

//auto f1(auto x) { return x; }   not accepted

auto f1(int x) { return x; }

auto f2(double x) -> decltype(x) { return x; }

template <typename T> 
T f3(T x) { return x; }

Why define a friend function inside class definition [duplicate]

This question already has an answer here:

In C++, we are allowed to define a friend function inside the class definition like:-

class A {
public:
    A(int a): mem(a){}
    ~A() {}
    friend void fun() {}
private:
    int mem;
};
void fun();

and then we can call this function, just like any regular function.

fun();

Can someone explain about( with examples ):-

1- In what cases do we need to define friend function inside the class definition.

2- What is special about this kind of definition which can not be achieved with just declaring function as friend in class and then defining the function outside.

Does C++11 guarantee a dying object will be moved rather than copied as an argument?

#include <vector>

using namespace std;

void f(const vector<int>&) {}
void f(vector<int>&&) {}

int main()
{
    while (true)
    {
        vector<int> coll;

        //
        // coll is dying, so,
        // "f(coll)" will call "f(const vector<int>&)" or
        // "f(vector<int>&&)" as per C++11?
        //
        f(coll); 
    }
}

In the code above, coll is dying; so, f(coll) will call f(const vector<int>&) or f(vector<int>&&) as per C++11?

Assign range to a letter

I'm actually wondering what is a best way to assign letter to range properly in C++.

For example, we have that scale:

enter image description here

We can do assignment in simpliest way:

if(a < 40)
  return 'T';
else if(a >= 40 && a < 55)
  return 'D';
else if(a >= 55 && a < 70)
  return 'P';
else if(a >= 70 && a < 80)
  return 'A';
else if(a >= 80 && a < 90)
  return 'E';
else if(a >= 90 && a <= 100)
  return 'O';

However, do you have some better ideas to make this?

C++ .what() error

I am using Netbeans. Iostream,string,cstdlib and stdexcept are included but I keep getting the error Unable to resolve identifier .

int main()
    try{
    for (int i{-3};i<10;++i)
        cout <<i << '\t' << divi(100,i) << endl;
    return 0;
    }
catch (std::exception& e){
    std::cerr << e.what();
    return -2;
}
catch ( ... ){
    std::cerr << "Unknown exception";
    return -1;
}

Static classes or instance pointers

Backstory:

Currently I have a series of three classes related to a game. I've previously made games using Unity where you access components such as the camera using functions accessible throughout all code. My current setup, however, relies on instances of each class being sent across the other classes. See the following outtake:

class World{
     *Game game;
     *Camera camera;
};
class Game{
     *Camera camera;
     *World world;
};
class Camera{
     *Game game;
     *World world;
};

Questions:

  • Is this a result of bad design or are there times when a setup like this is justified?

  • Should I rather use static classes over my current setup since it would clarify the code and no more than one instance of each class is ever used?

  • What are the possible downsides of using static classes over instances?

Placing class constructor

Why this code is incorrect?

class Method
{
public:
   Method(decltype(info2) info1);
   virtual ~Method(){}
protected:
  QSharedPointer<info> info2;
};

But this code is correct:

class Method
{
public:
   virtual ~Method(){}
protected:
  QSharedPointer<info> info2;
public:
  Method(decltype(info2) info1);   
};

why place of class constructor is important? I thought that place of definition class constructor isnt important.

Encapsulate a function with another function that has the same set of parameters

I have a function that has a lot of parameters. (4-7 parameters)

For simplicity, this is an example:-

class B{
    friend class C;
    int f(int param1,float param2, structA a, structB b){
         //... some code ...
    }
    //.... other functions ....
};

Sometimes, I want to encapsulate it under another (more-public) function that has the same signature:-

class C{
    B* b;
    public: int g(int param1,float param2, structA a, structB b){
        return b->f(param1,param2,a,b);
    }
    //.... other functions ....
};

In my opinion, the above code is :-

  • tedious
  • causes a bit of maintainability problem
  • human error-prone

Is there any C++ technique / magic / design-pattern to assist it?

In the real case, it happens mostly in edge-cases that composition is just a little more suitable than inheritance.

I feel that <...> might solve my problem, but it requires template from which I want to avoid.

How can I support window.external.xxx in cef framework

I want to switch from an embedded IE activeX to the libcef framework. My web project's javascript call C++ function use window.external.xxx method. But I can't get window.external object in cef framework. I try to bind my c++ function in window object. sadly, it doesn't work for me.

My code for binding c++ function to window object is like that:

CefRefPtr<CefV8Value> ptrGlobalObj = context->GetGlobal();
CefRefPtr<CefV8Value> jsCallOrthoLink = CefV8Value::CreateFunction(_T("CallOrthoLink"), m_ptrV8Handler);
ptrGlobalObj->SetValue(_T("CallOrthoLink"), jsCallOrthoLink, V8_PROPERTY_ATTRIBUTE_NONE);

I test it with window.xxx method in javascript. it works. so I know my bind codes are correctly.

How can I fixed this issue with window.external.xxxx method?

Thanks.

lundi 27 février 2017

Append a string to a variable (function name) in #define MACRO

Is it possible to append a string to a variable (function/field name) in MACRO? How?

#include <iostream>
using namespace std;

#define T1(hoho) \
   void hoho(){}

#define T2(hoho) \
   void hoho_(){}  //append underscore

T1(happy)
T2(sad)

int main() {
    happy(); //<--- work OK
    sad_();  //<--- this function not exist (compile error)
    return 0;
}

I want to use it for some (hacky-but-cool) function generation, e.g. :-

#define T3(hoho) \
int hoho_;  \
void hoho_clear(){hoho_=0;}  \
int hoho_get(){return hoho_;}  

class Magic{
    T3(magicField)    //<-- use only 1 MACRO parameter
}

The result will be like :-

class Magic{
    int magicField_;
    void magicField_clear(){magicField_=0;}
    int magicField_get(){return magicField_;}
}

I know it is not a good practice. I will rarely use it, I promise.

Time complexity relation to input, and nest for loops

In this for loop, the time complexity would be o(x) or o(n)

for(int i =0, i<x, i++)

say X is now

int x = 2^b

where b is an input, this would change the time complexity to o(2^x) or o(2^n)?

I want to confirm if my understanding of time complexity is valid. If so, a follow up question would be that when the initial for loop has a nested for loop, it would change the time complexity again to o(2^n * n) ?

int x = 2^b
for(int i =0; i<x; i++)
   for(int j = 0; i<z; j++)

Quick sort parameters

I'm trying to apply a quicksort snippet to my program but none of the vast amount of tutorials or examples I've found explain in layman's terms what I use for the second and third parameters most commonly referred to as left and right are in simple enough terms for me to understand.

Beneath is the snippet verbatim so if there are any issues I apologize.

void quickSort(int arr[], int left, int right) 
{
    int i = left, j = right;
    int tmp;
    int pivot = arr[(left + right) / 2];
      /* partition */
    while (i <= j) 
    {
        while (arr[i] < pivot)
            i++;
            while (arr[j] > pivot)
                j--;
                if (i <= j) 
                {
                    tmp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = tmp;
                    i++;
                    j--;
                }
    };

      /* recursion */
    if (left < j)
    quickSort(arr, left, j);

    if (i < right)
    quickSort(arr, i, right);
}

I understand that the first parameter is the array to be sorted but what exactly in reference to that array am I passing in for "left" and "right?"

I've been coding for a few years now but I haven't had the best direction so if this is remedial to you please educate me since I'm still very much learning.

Qt5 Separating a video widget

I am trying to find a way to create and separate a video widget into two parts, in order to process stereo videos:

  • The first one would play a part of the video;
  • The second one would play the other part of the video.

I currently do not know where to start. I am searching around qt multimedia module, but I do not know how to achieve this behavior.

Does anyone have an idea?

I was also thinking to build two video widgets and run them into two threads but they have to be perfectly synchronized. The idea was to cut the video into two ones with ffmpeg and affecting each one to a video widget. However I do not think it would be easy to achieve this (each frame would have to be sync).

Thanks for your answers.

std::invoke no matching overloaded function found error in C++

I'm learning about threads, parallel programming and tasks and farming.

I'm trying to have a Task class with its derivates, and basically create a vector of threads, each taking a worker function that loads an element from a queue of tasks (one task simply is a 'hello' message printed on the console), runs it, and then pops it out of the queue, going to the next one in the queue. The problems is that after doing everything I am getting two errors:

C2672: std::invoke no matching overloaded function found

C2893: Failed to specialize function template 'unknown-type std::invoke (_Callable&&, _Types&&...)

This is the code for my classes:

class Task
{
public:
    virtual ~Task()
    {
    }
    virtual void run() = 0;
};

class MessageTask : public Task
    {
    public:
        MessageTask(const string& message)
            : message_(message)
        {
        }
        void run()
        {
            cout << message_ << endl;
        }
    private:
        const string message_;
    };

class Farm
{
public:
    void add_task(Task* task);
    void run();

protected:
    queue<Task*> farmTasks;
    mutex farm_queue_mutex;

private:
    void workerFunction(queue<Task*>& theQueue);
};

Here are the memeber functions implementations:

void Farm::add_task(Task * task)
{
    mutex_lock queueLock(farm_queue_mutex);
    farmTasks.push(task);
}
void Farm::run()
{
    int pcThreadsNo = thread::hardware_concurrency();

    vector<thread*> threads(pcThreadsNo);
    for (int i = 0; i < threads.size(); i++)
    {
        mutex_lock queueLock(farm_queue_mutex);
        threads.push_back(new thread(mem_fun(&Farm::workerFunction), farmTasks));
    }

    for (int i = 0; i < threads.size(); i++)
    {
        threads[i]->join();
    }
}
void Farm::workerFunction(queue<Task*>& theQueue)
{
        while (true)
        {
            mutex_lock queueLock(farm_queue_mutex);
            if (theQueue.empty())
            {
                return;
            }
            else
            {
                //get task from queue and run it, then remove it
                Task* currentTask = theQueue.front();
                theQueue.pop();
                currentTask->run();
                currentTask = nullptr;
            }
        }
}

In Farm::run() I had to use 's mem_func in order to transform the member workerFunction() into a function-like object to pass it to the new thread constructor. Finally, here's the main():

int main()
{
    Farm farm;
    for (int i = 0; i < 5; i++)
    {
        farm.add_task(new MessageTask("hello"));
    }
    farm.run();

    return 0;
}

I really hope someone can help me with this problem, and any help or further explanation of what exactly is happening behind the scenes with these errors and the threads in order to understand this topic more would be greatly appreciated.

Count number of rehashing in unordered map

What is the right way to evaluate the unordered_map performance? [C++14]

In my code, I am using std::unordered_map very extensively in the order of billions of keys. For the purpose of performance I wished to know the behavior of unordered_map as how many times it had to rehash and all other parameter (how many buckets? How many buckets where empty before rehashing?). I know stl provides the number of buckets? But what else would be needed to profile or what do you use to analyze?

Unable to pass macro definition to base class

Base class is not able to view the macros defined in the derived class on the creation of derived class object. [C++14]

Base.HPP

 class Base {
          public:
            Base() {
               #ifndef SKIP
               std::cout << "Bing" << std::endl;
               #endif
             }
    };

File : Derived.HPP

#define SKIP
class Derived : public Base {
   public:
   Derived() {}
};

So, whenever I create the object of Derived class I expected not to see the "Bing" in the output terminal since I have defined the macro "SKIP".

But this does not happens. It seems Base class is clueless about the definition of macro "SKIP". Is there a way to do it or this is not possible to do it without compiling the code with -DSKIP flag?

Structure defined in a dynamically loaded library

I am dynamically loading the cudart (Cuda Run Time Library) to access just the cudaGetDeviceProperties function. This one requires two arguments:

  • A cudaDeviceProp structure which is defined in a header of the run time library;
  • An integer which represents the device ID.

I am not including the cuda_runtime.h header in order to not get extra constants, macros, enum, class... that I do not want to use.

However, I need the cudaDeviceProp structure. Is there a way to get it without redefining it? I wrote the following code:

struct cudaDeviceProp;

class CudaRTGPUInfoDL
{   
    typedef int(*CudaDriverVersion)(int*);
    typedef int(*CudaRunTimeVersion)(int*);
    typedef int(*CudaDeviceProperties)(cudaDeviceProp*,int);

public:
    struct Properties
    {
        char   name[256];                           /**< ASCII string identifying device */
        size_t totalGlobalMem;                      /**< Global memory available on device in bytes */
        size_t sharedMemPerBlock;                   /**< Shared memory available per block in bytes */
        int    regsPerBlock;                        /**< 32-bit registers available per block */
        int    warpSize;                            /**< Warp size in threads */
        size_t memPitch;                            /**< Maximum pitch in bytes allowed by memory copies */
        /*... Tons of members follow..*/
    };

public:
CudaRTGPUInfoDL();
~CudaRTGPUInfoDL();

int getCudaDriverVersion();
int getCudaRunTimeVersion();
const Properties& getCudaDeviceProperties();

private:
    QLibrary                library;

private:
    CudaDriverVersion       cuDriverVer;
    CudaRunTimeVersion      cuRTVer;
    CudaDeviceProperties    cuDeviceProp;

    Properties              properties;
};

As everybody can see, I simply "copy-pasted" the declaration of the structure.

In order to get the GPU properties, I simply use this method:

const CudaRTGPUInfoDL::Properties& CudaRTGPUInfoDL::getCudaDeviceProperties()
{
    // Unsafe but needed.
    cuDeviceProp(reinterpret_cast<cudaDeviceProp*>(&properties), 0);
    return properties;
}

Thanks for your answers.

The data types the 4 different casts can take (or normally take) in c++

It seems static_cast take could take value, reference or pointer and convert them to another type of value, reference or pointer. for instance: value:

B* pb; D* pd;
pointer:D* pd2 = static_cast<D*>(pb);   // Not safe, D can have fields and methods that are not in B.

However, it is not safe for static_cast to take pointer as input because the pointer could not be compatible with the pointer type converted to.

Seems dynamic_cast and reinterpret_cast can only take reference and pointer. Not sure what will happen if use dynamic_cast and reinterpret_cast on value types:

int B; char D;
B = dynamic_cast<B>(D);

int B; char D;
B = reinterpret_cast<B>(D);

I know for cont_cast, it only take pointer or reference but not variable which is undefined behavior.

Efficient concatenation of STL list to an existing non-empty vector

How to perform an efficient concatenation of a STL list to an existing non-vector?[C++14] Following is the code which I am trying to do it efficiently. Though it will work, I believe their will be a much better way of concatenating.

Vector V does has some elements prior to described merge operation.

Size(V) > Size(L)

If this information helps anymore.

void merge(std::list<int>& L, std::vector<int>& V) {
    for (auto& x : L) V.push_back(x);
    std::sort(V.begin(), V.end());
}

C++ List Iteration and erasing

I'm using C++ and having trouble erasing an element from a std::list while iterating through it. I have a list of a custom class ('Objects' for the sake of this question), and my code looks like this:

for(auto i : Objects)
    if(i.EraseFlag == true)
        {
            i = Objects.erase(i);
        }

I'm getting the error: 'no matching function for call to std::list::erase(Object&)'

I believe this is the right way (as of C++11) to iterate through lists, erase an element and return an iterator that takes into account the erasure, but clearly I'm doing something wrong. Previously when using vectors I would use 'Objects.erase(Objects.begin() + i)' with i being an integer in a for loop, but given the access requirements of lists this won't work.

Help appreciated.

Thanks

Is there a way to create a static const class value that is initialized with a loop?

A static member may be declared const, but then it must be initialized in the declaration. Consider the following case of a static array to be initialized with code in loops:

class A {
private:
  enum { SIZE = 360 };
  static double* vertices;
public:
  static void staticInit();
};

double* A::vertices = new double[SIZE];
void A::staticInit() {
  double a = 0, b = 0;
  for (int i = 0; i < SIZE; i++, a += .01, b += .02)
    vertices[i] = sin(a) + c2 * sin(b);
}

The code above would work. But if the intent is to make vertices constant, then declaring it const will give a compile error on the staticInit function.

In older C++ I would declare the pointer const, and cast it to non-const just in this function, but today, compilers won't allow this because it is unsafe. Of course, not declaring the pointer const is even less unsafe.

Is there any clean way out?

Minify output from rapidjson

I am using rapidjson to output some data for doing some statistic and plotting of a c++ programms algorithm like an internal runtime snapshots of the algorithm.

I output json like this:

string filename="output.json";
StringBuffer sb;
PrettyWriter<StringBuffer> writer(sb);
writer.StartArray();
for (std::vector<O_Class>::const_iterator netItr = O_Class_Array.begin();   netItr != O_Class_Array.end(); ++netItr)
    netItr->Serialize(writer);
writer.EndArray();

ofstream out;
out.open(filename);
out << sb.GetString() ;

As files become quite big (~100MiB) i'd like to output minified json, but I didn't find a documented way of doing so. With an external minifier I shrunk filesize from 100 to 18MB and like to have the same result as native in my application.

Any ideas?

Thanks for any suggestions!

How to take advantage of the Move Semantics for a better performance in C++11?

After many trials I still do not understand how to properly take advantage of the move semantics in order to not copy the result of the operation and just use the pointer, or std::move, to "exchange" the data pointed to. This will be very usefull to speed-up more complicated functions like f(g(),h(i(l,m),n(),p(q())) The objective is to have:

t3={2,4,6}; 
t1={}; // empty

While executing the code below the output is:

t3={2,4,6};
t1={1,2,3};

Code:

namespace MTensor {

 typedef std::vector<double> Tensor1DType;

 class Tensor1D {
  private:
    //std::shared_ptr<Tensor1DType> data = std::make_shared<Tensor1DType>();
    Tensor1DType * data = new Tensor1DType;
  public:
    Tensor1D() {
  };
  Tensor1D(const Tensor1D& other) {
    for(int i=0;i<other.data->size();i++) {
      data->push_back(other.data->at(i));
    }
  }
  Tensor1D(Tensor1D&& other) : data(std::move(other.data)) {
    other.data = nullptr;
  }
  ~Tensor1D() {
    delete data;
  };
  int size() {
    return data->size();
  };
  void insert(double value) {
    data->push_back(value);
  }
  void insert(const std::initializer_list<double>&  valuesList) {
    for(auto value : valuesList) {
      data->push_back(value);
    }
  }
  double operator() (int i) {
    if(i>data->size()) {
      std::cout << "index must be within vector dimension" << std::endl;
      exit(1);
    }
    return data->at(i);
  }
  Tensor1D& operator=(Tensor1D&& other)  {
    if (this == &other){
      return *this;
    }
    data = other.data;
    other.data = nullptr;
    return *this;
  }
  void printTensor(Tensor1DType info) {
    for(int i=0;i<info.size();i++) {
      std::cout << info.at(i) << "," << std::endl;
    }
  }
  void printTensor() {
    for(int i=0;i<data->size();i++) {
      std::cout << data->at(i) << "," << std::endl;
    }
  }
};
} // end of namespace MTensor

g++ 4.8.5 compiles c++14 code silently in c++11 mode

To my surprise, the following program compiles just fine:

int main()
{ 
    int i = 4;
    [j = i]{}();
}

> g++ --std=c++11 ext.cpp
> 

The problem is that I want this to fail: Generalized Lambda Capture is a C++14 feature, and my current project has a requirement for C++11.

Now, Clang compiles this too with a warning, which I can promote to an error using -Werror=c++14-extensions. However, I can find no similar flag for g++. I can use -pedantic-errors or -Werror=pedantic, but those come with way, way more baggage.

Have I overlooked some compiler option for this compiler?

Reusing objects in functions defined in C++ header

I have a function library in a header file, which includes the following function:

// Get a normally distributed float value in the range [0,1].
inline float GetNormDistrFloat()
{
    std::random_device _RandomDevice;
    std::normal_distribution<float> _NormalDistr(0.5, 2.0);

    float val = -1;
    do { val = _NormalDistr(_RandomDevice); } while(val < 0.0f || val > 1.0f);

    return val;
}

This works well, however, I don't want to create the std::random_device and std::normal_distribution objects every time I call this function GetNormDistrFloat().

What is the "best" (correct) way in C++ to deal with this? I tried to just move those two object definitions outside the function, but that led to linker errors. Do I have to create a .cpp file for this header and initialize the objects there?

compare two unorderes type lists for equality

How can one check if two parameter packs are the same, ignoring their internal order?

So far I only have the frame (using std::tuple), but no functionality.

#include <tuple>
#include <type_traits>

template <typename, typename>
struct type_set_eq : std::false_type
{
};

template <typename ... Types1, typename ... Types2>
struct type_set_eq<std::tuple<Types1...>, std::tuple<Types2...>>
    : std::true_type
{
    // should only be true_type if the sets of types are equal
};

int main() {
    using t1 = std::tuple<int, double>;
    using t2 = std::tuple<double, int>;
    using t3 = std::tuple<int, double, char>;

    static_assert(type_set_eq<t1, t1>::value, "err");
    static_assert(type_set_eq<t1, t2>::value, "err");
    static_assert(!type_set_eq<t1, t3>::value, "err");
}

time complexity of unordered_set

what is the time complexity of find method in unordered_set<int>?

and also it it possible to change the hash functions?

Fastest ways to check if a value already exists in a stl container

I am holding a very big list of memory addresses (around 400.000) and need to check if a certain address already exists in it 400.000 times a second.

A code example to illustrate my setup:

std::set<uintptr_t> existingAddresses; // this one contains 400.000 entries

while (true) {
    // a new list with possible new addresses
    std::set<uintptr_t> newAddresses; // also contains about ~400.000 entries

    // in my own code, these represent a new address list
    for (auto newAddress : newAddresses) {

        // already processed this address, skip it
        if (existingAddresses.find(newAddress) != existingAddresses.end()) {
          continue;
        }

        // we didn't have this address yet, so process it.
        SomeHeavyTask(newAddress);

        // so we don't process it again
        existingAddresses.emplace(newAddress);
    }

    Sleep(1000);
}

This is the first implementation I came up with and I think it can be greatly improved.

Next I came up with using some custom indexing strategy, also used in databases. The idea is to take a part of the value and use that to index it in its own group set. If I would take for example the last two numbers of the address I would have 16^2 = 256 groups to put addresses in.

So I would end up with a map like this:

[FF] -> all address ending with `FF`
[EF] -> all addresses ending with `EF`
[00] -> all addresses ending with `00`
// etc...

With this I will only need to do a lookup on ~360 entries in the corresponding set. Resulting in ~360 lookups being done 400.000 times a second. Much better!

I am wondering if there are any other tricks or better ways to do this? My goal is to make this address lookup as FAST as possible.

QT signal error: "this" is unavailable for static member function

I'm working at a socket class for my application that will introduce me in QT framework. When I try to build I get this error: 'this' is unavailable for static member functions. This is my class .h and .cpp

#pragma once
#include <QObject>
class QTcpSocket;
namespace Ps{
    class InstSocket : public QObject
    {
        Q_OBJECT
    public:
        InstSocket(QObject *parent=0);
        bool Connect();
        bool isOpen();
        void Disconnect();

        //Geters
        QString GetHostName() const {return m_hostName;}
        quint16 GetPort() const {return m_port;}
        //seters
        void SetHostName(const QString& value);
        void SetPort(quint16 value);
        void SetLongWaitMs(int value){m_longWaitMs = value;}
        void SetShortWaitMs(int value){m_shortWaitMs = value;}
        void WriteData(const QString &data) const;

        ~InstSocket();
        QString ReadData() const;
    signals:
        static void NotifyConnected();
        static void NotifyDisconnected();

    private slots:
        void onConnected();
        void onDisconnected();

    private:
        //this holds a reference to QtcpSocket
        QTcpSocket& m_socket;
        QString m_hostName;
        quint16 m_port;
        int m_shortWaitMs;
        int m_longWaitMs;

        explicit InstSocket(const InstSocket& rhs) = delete;
        InstSocket& operator= (const InstSocket& rhs) = delete;
    };
}

and the cpp:

#include "instsocket.h"
#include "QTcpSocket"
#include "QDebug"
#include "utils.h"

namespace Ps
{
    InstSocket::InstSocket(QObject *parent) :
        QObject(parent),
        m_socket(*new QTcpSocket(this)),
        m_hostName(""),
        m_port(0),
        m_shortWaitMs(0),
        m_longWaitMs(0)
    {
        /* my signals are wired to the undelying socket signals, the signal connected is triggered, when a conection
         * is established. This will be wired to onConnected and Disconnected slots*/
        connect(&m_socket, &QTcpSocket::connected, this, &InstSocket::onConnected);
        connect(&m_socket, &QTcpSocket::disconnected, this, &InstSocket::onDisconnected);
    }

    bool InstSocket::Connect()
    {

        qDebug() << "attempting to connect to "<< m_hostName << "on port" << m_port << "with wait time: "<<m_longWaitMs;
        m_socket.connectToHost(m_hostName, m_port, QTcpSocket::ReadWrite);
        return m_socket.waitForConnected(m_longWaitMs);
    }

    bool InstSocket::isOpen()
    {
        return m_socket.isOpen();
    }

    void InstSocket::Disconnect()
    {
        if(!isOpen()) return;
        m_socket.disconnectFromHost();
    }


    void InstSocket::onConnected()
    {
        emit NotifyConnected();
    }

    void InstSocket::onDisconnected()
    {
        emit NotifyDisconnected();
    }

    void InstSocket::SetHostName(const QString &value)
    {
        m_hostName = value;
    }

    void InstSocket::SetPort(quint16 value)
    {
        m_port = value;
    }

    void InstSocket::WriteData(const QString &data) const
    {
        /*support for writeing to socket. The write metod of the socket will return the number of bites writen*/
        int bytes_written = m_socket.write(qPrintable(data));
        qDebug() << "Bytes written: "<<bytes_written;
    }

    QString InstSocket::ReadData() const
    {
        if(!m_socket.isReadable())
        {
            return "ERROR: Socket is unreadable.";
        }
        QString result;
        //until the socket reports there is no data available
        while(!m_socket.atEnd())
        {
            result.append(m_socket.readAll());
            /*since typically a PC would be much faster at reading than an instrument might be at writing
             * instrument must have a chance to queue up more data in case the message it's sending us is long.*/
            m_socket.waitForReadyRead(m_shortWaitMs);

        }
        return result;
    }

    InstSocket::~InstSocket()
    {
        Utils::DestructorMsg(this);
    }
}

and this is the error:

Qt Projects\build-Vfp-Desktop_Qt_5_7_0_MSVC2015_64bit-Debug\debug\moc_instsocket.cpp:-1: In static member function 'static void         Ps::InstSocket::NotifyConnected()':
    error: 'this' is unavailable for static member functions

QMetaObject::activate(this, &staticMetaObject, 0, Q_NULLPTR); In static member function 'static void Ps::InstSocket::NotifyDisconnected()':
error: 'this' is unavailable for static member functions
    QMetaObject::activate(this, &staticMetaObject, 1, Q_NULLPTR);

When I clicked on them, QT creator took me to moc_instsocket.cpp (that is in build folder and poit to this:

    // SIGNAL 0
void Ps::InstSocket::NotifyConnected()
{
    QMetaObject::activate(this, &staticMetaObject, 0, Q_NULLPTR);
}

// SIGNAL 1
void Ps::InstSocket::NotifyDisconnected()
{
    QMetaObject::activate(this, &staticMetaObject, 1, Q_NULLPTR);
}

I can't figure out what to do althought I checked all the code several times. There is no need to know about utils class since there are just some debug messages. Did anyone know how to fix it?

using constexpr with yaml-cpp's node

Is it a way to use constexpr with yaml-cpp ? I tried :

constexpr YAML::Node sample = YAML::LoadFile("sample.yaml");

but it seems that's not possible with the actual implementation of yaml ?

Macro generating a valid name of template-class static instance

Background

I am tinkering with polymorphic serialization and deserialization in C++. For that purpose I use a static map: [type id-string] -> [type factory function].

Each type has to be registered in this map and I would like to do it at compile-time.

Approach

The naïve approach is:

/// Creates a concrete serializable type provided as a template parameter
template <typename T>
ISerializable* createSerializable() { return new T; }

/// Factory that registers a serializable type T
template <typename T>
struct SerializableFactory
{
    SerializableFactory(const char* type_name)
    {
        // registerType adds a type_name->factory_function entry to the map
        registerType(type_name, createSerializable<T>);
    }
};

Registering the types is done with the macro:

/// Macro that registers the type at compile-time using a static factory instance
#define REGISTER_TYPE(T)                                                   \
    static SerializableFactory<T> global_##T##Factory(#T);

For example REGISTER_TYPE(ArbitraryClass) will become:

static SerializableFactory<ArbitraryClass> 
    global_ArbitraryClassFactory("ArbitraryClass");

Problem

Unfortunately this will not work for ArbitraryClass<int> bacause <, > are not allowed to be used in identifier.

Question

Is there a good work-around to achieve registering arbitrary template type this way?

Alternatives

I considered the following alternatives (each has disadvantages):

  • Registering types run-time: looks less elegant, requires more effort from the serialization user;
  • RTTI: requires RTTI to be enabled, gives no guarantees that different types will have always different hashes/names (very unlikely of course, but still);
  • Asking the user to provide an alias name: less elegant, more effort from the serialization user

Digits after decimal points in printing outputs

I need to do the following computations.

sqrt(abs(pow(a, 2) - pow(b, 2)))
sqrt(abs(pow(a, 2) + pow(b, 2)))

Let a = 4 and b = 5 so the outputs are 3 and 6.40312. Now if I want to print like 3.0 and other one kept as same 6.40312 how can I do that? If I use setprecision() and fixed the outputs are 3.0000and 6.40312. How can I have varible lenght decimal points results with cout?

How to use bitmask_operators.hpp with namespace and classes

I want to use C++11 enum class as bitfields and find a nice approach here.

But I stuck, if my enum class declaration is not in global namespace but in custom namespace or inside of a class instead. E.g.:

#define ENABLE_BIT_OPERATORS(E) template<> struct enable_bitmask_operators<E> { static constexpr bool enable=true; };

// anonymous namespace
namespace {
enum class Ean {
    None = 0x00,
    Bit0 = 0x01,
    Bit1 = 0x02,
    Bit2 = 0x04,
    Bit3 = 0x08,
};
ENABLE_BIT_OPERATORS(Ean);
} // anonymous namespace

// custom namespace
namespace Custom {
enum class Ecn {
    None = 0x00,
    Bit0 = 0x01,
    Bit1 = 0x02,
    Bit2 = 0x04,
    Bit3 = 0x08,
};
ENABLE_BIT_OPERATORS(Ecn);
} // custom namespace

// inside class in global namespace
class MyclassGN {
public:
    enum class Ecgn {
        None = 0x00,
        Bit0 = 0x01,
        Bit1 = 0x02,
        Bit2 = 0x04,
        Bit3 = 0x08,
    };
    ENABLE_BIT_OPERATORS(Ecgn);
};

// inside class in anonymous namespace
namespace {
class MyclassAN {
public:
    enum class Ecan {
        None = 0x00,
        Bit0 = 0x01,
        Bit1 = 0x02,
        Bit2 = 0x04,
        Bit3 = 0x08,
    };
    ENABLE_BIT_OPERATORS(Ecan);
};
} // anonymous namespace

// inside class in custom namespace
namespace Custom {
class MyclassGN {
public:
    enum class Ecgn {
        None = 0x00,
        Bit0 = 0x01,
        Bit1 = 0x02,
        Bit2 = 0x04,
        Bit3 = 0x08,
    };
    ENABLE_BIT_OPERATORS(Ecgn);
};
} // custom namespace

This always gives me errors:

error: specialization of 'template<class E> struct enable_bitmask_operators' in different namespace

until I place my template specialization to the same namespace as the template enable_bitmask_operators in bitmask_operators.hpp is located (global namespace in this case).

But I want to have my specialization close to my enum class declaration.

In the mentioned article, this problem is also commented by Jay Miller and it seems that he provides a solution. But I failed to follow his hints to solve this in bitmask_operators.hpp.

Example code here.

How to use sfinae to check, whether type has operator ()?

I have following code:

template <typename T>
struct function_traits
{
    typedef decltype(&T::operator()) test_type;
    typedef std::true_type res_type;
};

template <typename T>
struct function_traits
{
    typedef std::false_type res_type;
};

In other words, I want to know whether type has operator (). I thought that I can use SFINAE way to do this. However compiler tells:

'function_traits' : class template has already defined.

What's wrong with such code?

P.S.: here is simple usage:

auto f1 = [](const int a){ std::cout << a << std::endl; };
function_traits<decltype(f1)>::res_type;
auto f2 = false;
function_traits<decltype(f2)>::res_type;

EDIT: I am using c++ 11 standard

Using std::forward on sub fields

I was experimenting with how std::move and std::forward differs, and I have found that I am not able to use std::forward on class field:

name = std::forward<T>(rhs.name);

below is full example. The error I am getting under gcc 6.3 is:

C:/PROGRA~1/MINGW-~1/X86_64~3.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/6.3.0/include/c++/bits/move.h:89:7: error: static assertion failed: template argument substituting _Tp is an lvalue reference type
       static_assert(!std::is_lvalue_reference<_Tp>::value, "template argument"
       ^~~~~~~~~~~~~

I understand that the cause is probably because T is of type WrongUseOfMove. But I wonder if forwarding only a sub variable is possible. For example I could use passed in rhs parameter and forward its fields to different class variables.

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

class WrongUseOfMove {
 public:
  template<typename T>
  WrongUseOfMove(T&& rhs)
  {
    //name = std::move(rhs.name); // Very wrong!!
    //name = std::forward<T>(rhs.name); // Does not compile, T is WrongUseOfMove instead decltype(rhs.name);
    name = std::forward<decltype(rhs.name)>(rhs.name); // compiles - but is it correct? 
    std::cout << __PRETTY_FUNCTION__ << "\n";
  }

  WrongUseOfMove(){}

  std::string name;
};

int main()
{
  WrongUseOfMove wm;
  WrongUseOfMove wm2 = wm;
}

http://ift.tt/2lMaBze

dimanche 26 février 2017

C++: Enforcing a function so it cannot accept any parameter that is passed by value

How would you define and declare a function that would just not accept any parameter that get passed by value, in C++.

Exception during running custom clang Frontend tool on some input files

I have written a custom clang Frontend tool according to the following link. http://ift.tt/WYB0vy

Now I am giving clang source code itself to my frontend tool for static analysis. My tool is throwing an exception for this test case http://ift.tt/2lL5j8L

From the documentation of this test case, It is written for undefined behavior. And while running ClangTool on this test it throws stackoverflow exception even before the control comes in HandleTranslationUnit.

As clang can generate AST for the above test case, I assume the exception might be coming during compilation. Now the question is can't I continue visiting AST nodes for such files as I don't care about the semantics of input source files. I am only interested in static analysis.

Is this the expected behavior? Then how to traverse the generated AST and visit the nodes. I am really stuck at this moment and have no clue how to proceed. Would you please help me to fix this issue.

Thanks in advance!

Thanks, Hemant Bhagat

How to assign memory using shared pointer instead of malloc for char array

I have a character array and I want to initialize it using shared pointer I wrote like this below, but getting syntax error. Can anyone suggest what needs to be modified to make this work. I want the size of the array based on the rows and column. The maparray will hold bunch characters of '*'. Something like:

***
* *
***

 std::shared_ptr<unsigned char*> maparray;
 maparray=std::make_shared<unsigned char*>(rows*cols);

Brace-or-equal-initializers on anonymous struct does not work on VS2013

Brace-or-equal-initializers in an anonymous struct within a struct doesn't do their work on output produced by VS2013. There's the code:

#include <iostream>
#include <cstdint>


struct S
{
    struct
    {
        uint64_t val = 0;
    }anon;
};

int main()
{
    S s;
    S *a = new S;

    std::cout << s.anon.val << std::endl;
    std::cout << a->anon.val << std::endl;

    return 0;
}

Compile with this command on Linux:

g++ -std=c++11 def-init-anon-atruct.cpp -o def-init-anon-atruct

(Adding optimisation flags does not affect the result)

Expected result:

0
0

Weird. Running that with VS2013 gives garbage values. Who's right on this one in terms of implementing C++11 standards right? I highly doubt this is GCC's fault.

Is it something to do with some useless VS compiler options? Windows extensions? I have to make default constructors for the structures because of a bug MS made? this is absurd.

Lambda state behavior differences between an internal static and a captured mutable

I noticed that creating a lambda then making a copy results in different behavior between statics declared in the lambda and captured by value mutables. Specifically, when the lambda is copied the state of the mutable is copied and becomes independent of the lambda it was copied from. However, the value of the static internal to the lambda shares state between the copies.

#include <iostream>

int main()
{
    int i = 0;
    auto f = [i]() mutable {
        static int h=0;
        std::cout << "mutable captured i by value=" << ++i << "  static h=" << ++h << std::endl;
    };
    f();       // mutable captured i by value=1  static h=1
    i = 10;    // This shows that, as expected, changes in i are ignored by fc
    auto fc = f;
    f();       // mutable captured i by value=2  static h=2
    f();       // mutable captured i by value=3  static h=3
    fc();      // mutable captured i by value=2  static h=4
}

From this I gather that copies of a lambda share the same execution code and any retained state but also that mutable captured values are not shared between duplicated instances of the same lambda even though they are retained between calls.

Is this behavior correct? I have found this about statics in lambdas but haven't run across this difference in state behavior.

How to use std::function in cython

I've seen here that you can do

from libcpp.string cimport string
from libcpp.vector cimport vector

to refer to parameters of type std::string and std::vector. I need to pass functions to a c++ method expecting std::function<>. I tried doing

from libcpp.function cimport function

but that didn't work:

from libcpp.function cimport function
^
------------------------------------------------------------

cython_topics.pyx:3:0: 'libcpp/function/function.pxd' not found
Traceback (most recent call last):
  File "setup.py", line 18, in <module>
    language="c++",                   # generate and compile C++ code
  File "/usr/lib64/python2.7/site-packages/Cython/Build/Dependencies.py", line 934, in cythonize
    cythonize_one(*args)
  File "/usr/lib64/python2.7/site-packages/Cython/Build/Dependencies.py", line 1056, in cythonize_one
    raise CompileError(None, pyx_file)
Cython.Compiler.Errors.CompileError: cython_topics.pyx

What's the right way to call a c++ function expecting std::function<>?

What is this use of auto ? - ADL?

I have always thought that auto should be used in the following form auto varName = someOtherVar;. Today I have found that I could also use auto varName(someOtherVar);. At first I thought that maybe this is Argument Depending Lookup at work. But I am not sure. What are the restrictions for using such auto syntax? Below is some code:

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

class Person {
    public:
    Person(std::string s) : name(s) {}
    Person(const Person& p) : name(p.name) {}
    std::string name;
};

int main()
{
    Person p("hello");
    auto p2(p); // equivalent to auto p2 = p; ?
    std::cout << p2.name;
}

What's the difference between "auto v = f()" and "auto&& v = f()"?

#include <vector>

using namespace std;

vector<int> f()
{
    return{};
}

void g(vector<int>)
{}

void g(vector<int>&&)
{}

int main()
{
    auto   v1 = f();
    auto&& v2 = f();

    g(forward<vector<int>>(v1));
    g(forward<vector<int>>(v2));
}

Does C++11 guarantee g(forward<vector<int>>(v1)) will call f(vector<int>) and g(forward<vector<int>>(v2)) will call f(vector<int>&&)?

Cannot return vector containing derived pointers

Okay, so to illustrate the issue I am having I will show some (pseudo) code.

Lets say I have the following models:

class Animal : public GameObject;

class Player : public GameObject;

class GameObject : public ObjectInterface;

class ObjectInterface
{
public:
    virtual ~ObjectInterface() = default;
    virtual vec3 GetPosition() = 0;
}

Now I also hold some "object context", which holds collections of certain game objects.

class ContextObject
{
     // they implement ObjectInterface
     vector<shared_ptr<Animal>> animals;
     vector<shared_ptr<Player>> players; 
}

Now I have a TargetSelector class, which works directly with the ObjectInterface only.

class TargetSelector
{
    // this is somehow not possible, although `animals` are a subclass of `ObjectInterface`
    vector<shared_ptr<Model::ObjectInterface>>& GetAvailableTargets()
    {
        return context->animals; // context is some `ObjectContext`
    }
}

I would expect the above code to work, since an Animal is of the type ObjectInterface. But instead I get an error saying it cannot convert from an vector<shared_ptr<Animal>> to an vector<shared_ptr<ObjectInterface>>. Is this even suppose to work?

Could someone explain me why I cannot do this kind of polymorphism and if possible a nice solution so I can make this work.

Thanks, any help is appreciated!

std::uniform_int_distribution different behaviour on Mac and Windows

Code example:

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

int main()
{
    mt19937 generator(0);
    uniform_int_distribution<int> distr(0, 100);

    for(auto i = 0; i < 10; ++i)
    {
         cout << distr(generator) << "\n";
    }
}

This code produces different numbers on Mac and Windows, but replacing uniform_int_distribution with uniform_real_distribution fixes that issue, and sequence generated is the same on both platforms.

My question is: why does it happen?

Printing a variable without assigning a value

In C++, what happens if I print a variable that has not been assigned a value? The following two code gives me two different result. Also, the first one gives different result in each compilation and second one prints 0 everytim. Why?

int main() {
    int x = 1;
    int y;   // No value has been assigned
    if (x) {
        cout << y;    // without using endl
        // prints different value each time
    }
}

vs.

int main() {
    int x = 1;
    int y;   // y is not initialized
    if (x) {
        cout << y << endl;    // using endl
        // prints 0
    }
}

Dedicated SSE4.2 C++ Stream will it be faster?

I'm busy testing SSE4.2 string instructions using C++11 (MS VS 2015). Because MS VC++ doesn't support inline assembly I use the intrinsic functions.

The test case is simple: Counting lines in Huge (12,5+M lines) text file. I do this by counting the number of '\n' LF.

My code so fare:

#include "nmmintrin.h"
#include <iostream>
#include <fstream>
#include <string>
#include <chrono>

static inline long long popcnt128(__m128i n) 
{
    return _mm_popcnt_u64(n.m128i_u64[0])
    +_mm_popcnt_u64(n.m128i_u64[1]);
}

static inline size_t sse4_strChrCount(const char* pcStr, size_t iStrLen, const char chr) 
{
    const __m128i   mSet = _mm_set1_epi8(chr);
    const int       iMode = _SIDD_CMP_EQUAL_EACH;
    size_t          iResult = 0;

    for (size_t i = 0; i < iStrLen; i += 16)
    {
        const __m128i   data = _mm_loadu_si128(reinterpret_cast<const __m128i*>(pcStr + i));
        __m128i         ret = _mm_cmpistrm(data, mSet, iMode);
        iResult += popcnt128(ret);
    }

    return iResult;
}



int main(int argc, char** argv)
{
    // NOTE: NO CHECKS FOR SSE4.2 SUPPORT! So be carefull!
    const int bufSize = 4096 * 128; // +/- 5Mb on Heap
    char* buf = new char[bufSize];

    if (argc <= 1)
    {
        std::cerr << "Provide filename to count newlines on!" << std::endl;
        exit(0);
    }

    std::string fileName(argv[1]);
    std::cout << "C++ LineCounter for " << fileName << " with bufSize: " << bufSize << std::endl;

    std::chrono::steady_clock::time_point begin =  std::chrono::steady_clock::now();

    size_t lineCount = 0;
    std::ifstream inFile;
    inFile.open(fileName, std::ios_base::in | std::ios_base::binary);

    while (inFile.good())
    {
        inFile.read(buf, bufSize);

        if (inFile || inFile.gcount() > 0)
        {
            lineCount += sse4_strChrCount(buf, inFile.gcount(), '\n');
        }
    }
    inFile.close();

    std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();

    std::cout << "Find newline char using SSE4.2 intrinsic functions: Counted " << lineCount << " lines in " <<         std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count() << "(ms) " << std::endl;

    return 0;
}

Result is:

C++ LineCounter for ..\HugeLogfile.txt with bufSize: 524288
Find newline char using SSE4.2 intrinsic functions: Counted 12867995 lines in 11568(ms)

My questions:

  • Is it possible to write a __m128i C++ basic_streambuf<__m128i> with char_traits<__m128i> etc..?
  • Would it be faster? E.g. by omiting the high level buffer?

Testing on my Macbook Pro with Windows 10 under Parallels.

CPU Specification: Intel(R) Core(TM) i7-4960HQ CPU @ 2.60GHz.

Thanks for any input and feedback!

Parsing a std::string to a std::tuple

I'm looking to read input from a file and convert this to a std::tuple type. For example, I might have input like this:

((3,12,8),(2,4,6),(14,5,2))

in a file. Is there any built-in way to parse this to a std::tuple?

The ultimate goal is to create a minimax tree from this input, so the tree would look like this. My Tree type looks something like this:

class Tree{
    int data;
    bool is_max_ply;
    vector<Tree*> children
};

Any better options on creating my tree other than using std::tuple?

Thanks!

Initialization of member array of non-copyable, non-movable, explicitly constructed types

A library which I can't modify has a type akin to the following:

class A {
  public:
    A () : A(0) { }
    explicit A (int const value) : value_(value) { }

    A (A const &) = delete;
    A (A &&) = delete;

    A & operator= (A const &) = delete;
    A & operator= (A &&) = delete;

  private:  
    int value_;
}

Now, I have a class which requires a bunch of As as members. The most logical way to structure them is by putting them in an array. E.g. something like :

struct Foo {
  A a[2];
}

Is there any way to initialize each member with a distinct initial value? I've been trying various forms of using braced-list initialization, but they all fail due to either A(int) being explicit or A not having a copy/move-constructor.

What doesn't work:

  • Foo () : A{ { 1 }, { 2 } } { }: won't call A(int) since it's explicit.
  • Foo () : A{ { A(1) }, { A(2) } } { }: can't copy- nor move-assign.

Using function pointers to uniquely identify types

I need to assign unique values to types for run-time equality comparison. Using function pointers as values does the job:

#include <cassert>

struct type_id {
  using value_type = void(*)();

  template<class T>
  static void get() { }
};

// some types
struct A {};
struct B {};

int main() {
    type_id::value_type a = &type_id::get<A>;
    type_id::value_type b = &type_id::get<B>;   

    assert(a != b);

    return 0;
}

My question is the following: what are the restriction (if any) I should be aware of? I am especially curious about uniqueness across multiple translation units, and performance.

What is the best way to analyze implementations of algorithms in C++?

At present, I am implementing several simple search, sort, tree, graph and divide and conquer algorithms like Djikstra's, quicksort, minimax, etc. in C++.

I want to analyze my implementations by measuring mostly the time taken for execution and growth (increase in time taken as the input increases). If I can estimate the space occupied, it would be an added bonus.

I am currently using the functions available in ctime (time.h) to measure the running time of the functions which apply the algorithms. Is there any better or more accurate and reliable way to do the same? I am more than willing to learn some new features that might have come with C++11 and 14.

Is there any dedicated IDE though which I can achieve the above task by using features like profilers, etc?

Why is it recommended to use "auto&&" rather than "auto&" in range-for loop?

#include <vector>

using namespace std;

int main
{
    vector<int> coll;
    for (auto&  i : coll) {} // 1
    for (auto&& i : coll) {} // 2
}

According to cppref:

It is safe, and in fact, preferable in generic code, to use deduction to forwarding reference, for (auto&& var : sequence).

However, I think 2 is completely equivalent to 1; in other words, 1 is enough.

Why is it recommended to use auto&& rather than auto& in range-for loop?

C++ Random Number Generation: Generate cos squared function

The probability distribution of interest is

double x; // range: -pi/2.0 to +pi/2.0
double y = std::pow(std::cos(x), 2.0);

This function can be integrated analytically, however it cannot be inverted. Therefore the usual trick of mapping a uniform distribution to the required probability distribution cannot be performed.

Is there another method which can be used to generate a random variable cos^2(theta) distribution?

It may be possible to find the inverse function numerically, however I do not know of an efficient (memory and computationally) method of doing this.

How do two overloaded std::forward work?

I have found in std library the following implementation of std::forward:

// TEMPLATE FUNCTION forward
template<class _Ty> inline
constexpr _Ty&& forward(
    typename remove_reference<_Ty>::type& _Arg) _NOEXCEPT
{   // forward an lvalue as either an lvalue or an rvalue
return (static_cast<_Ty&&>(_Arg));
}

template<class _Ty> inline
constexpr _Ty&& forward(
    typename remove_reference<_Ty>::type&& _Arg) _NOEXCEPT
{   // forward an rvalue as an rvalue
static_assert(!is_lvalue_reference<_Ty>::value, "bad forward call");
return (static_cast<_Ty&&>(_Arg));
}

First function works obviously, but for second I cannot find usefull example. If I try to do something like this:

template<class _Ty> inline
constexpr _Ty&& my_forward(
   typename std::remove_reference<_Ty>::type&& _Arg) _NOEXCEPT
{   // forward an rvalue as an rvalue
   static_assert(!std::is_lvalue_reference<_Ty>::value, "bad forward call");
   return (static_cast<_Ty&&>(_Arg));
}

template<typename T>
T getRValue()
{
    return std::remove_reference<T>::type{};
}

template<typename T>
void setValue(T && i)
{
   my_forward<T>(getRValue<T>());
}

int main()
{
    int i = 1;
    setValue(i);
}

to check when second function is called, I have got the error:

Error   C2664   '_Ty my_forward<T>(int &&) noexcept': cannot convert argument 1 from 'int' to 'int &&'

Does anybody know in which case second overloaded function (in my terms my_forward) is called ? Or may be some good example for it ? By the way my compiler is MSVC 2015

Thanks, all for help !!

Template parameters to constexpr

I am trying to pass a more "generic" const input parameter to a constexpr implementation for fibonacci. When I replace the template parameter with an int, things are hunky-dory again.

#include<iostream>
template <typename T>
constexpr auto fib_ce(T n) {
   return (n>1) ? fib_ce(n-1)+fib_ce(n-2) : 1;
}

int main() {
   std::cout<<fib_ce(4)<<"\n";
}

This is the error I get:

g++ -std=c++14 -o constexpr_fib constexpr_fib.cpp 
constexpr_fib.cpp:4:19: fatal error: recursive template instantiation exceeded maximum depth of 256
   return (n>1) ? fib_ce(n-1)+fib_ce(n-2) : 1;

              ^

How do I provide a template argument to a constexpr, that can take inputs like long, int, unsigned long, etc etc for this constexpr

samedi 25 février 2017

"undefined reference to" Error when trying to make a makefile in Linux on my raspberry pi [duplicate]

I am trying to port a Pong program I made in Visual Studios to my raspberry pi. I got everything working perfect In visual studios using a MSP Micro controller.

The Program uses Pigpio on the Pi to connect to the ADC chip. And Open CV for the pong game.

Now I have wired up the MCP3008 ADC and made a new PiControl class instead of my old Control Class.

I started with about 50 errors and I'm slowly getting less and less. I have spent countless hours searching this site and many others to fix all my errors. I would appreciate any help.

The Base Class makes a canvas for the open CV, the ControlPi Class gets two ADC readings from two potentiometers, and the Pong class implements the aspects of the Pong game

Here is my code for 4618_Lab5.cpp :

#include <stdint.h>
#include "stdafx.h"
#include <string>
#include <iostream>
#include <time.h>
#include "Pong.h"
#include "Base4618.h"
#include "ControlPi.h"


#define PI4618
//#define WIN4618

#ifdef WIN4618
#define chOne 0
#define chTwo 1
#include "Control.h"
#include "Serial.h"
#include "opencv.hpp"
#pragma comment(lib,".\\opencv\\lib\\opencv_world310d.lib")
#endif

#ifdef PI4816
#include "ControlPi.h"
#include <opencv2/opencv.hpp>
#endif


int main(int argc, char **argv)
{
    CPong pong;
    pong.Run();
    return 0;
}

Here is my makefile:

# The compiler to use is for C++
CC=g++
# The compiler options are (all warnings)
CFLAGS=-Wall `pkg-config --cflags opencv` -std=c++11 -c
# The linker options are (all warnings)
LDFLAGS=-Wall `pkg-config --libs opencv` -std=c++11 -lpigpio -lrt -lpthread

all: Pong

Pong: 4618_Lab5.o ControlPi.o Base4618.o Pong.o 
    $(CC) $(LDFLAGS) 4618_Lab5.o ControlPi.o Base4618.o Pong.o -o Pong

4618_Lab5.o: 4618_Lab5.cpp
    $(CC) $(LDFLAGS) 4618_Lab5.cpp

ControlPi.o: ControlPi.cpp
    $(CC) $(LDFLAGS) ControlPi.cpp

Base4618.o: Base4618.cpp
    $(CC) $(LDFLAGS) Base4618.cpp

Pong.o: Pong.cpp
    $(CC) $(LDFLAGS) Pong.cpp

The error message I am getting:

make (in directory: /home/pi/Desktop/Lab6/4618_Template) g++ -Wall pkg-config --libs opencv -std=c++11 -lpigpio -lrt -lpthread 4618_Lab5.cpp /tmp/ccBegQZL.o: In function main': 4618_Lab5.cpp:(.text+0x1c): undefined reference toCPong::CPong()' 4618_Lab5.cpp:(.text+0x28): undefined reference to CPong::Run()' 4618_Lab5.cpp:(.text+0x38): undefined reference toCPong::~CPong()' 4618_Lab5.cpp:(.text+0x4c): undefined reference to `CPong::~CPong()' Compilation failed. makefile:14: recipe for target '4618_Lab5.o' failed collect2: error: ld returned 1 exit status make: *** [4618_Lab5.o] Error 1

Count unique words in a string in C++

I want to count how many unique words are in string 's' where punctuations and newline character (\n) separates each word. So far I've used the logical or operator to check how many wordSeparators are in the string, and added 1 to the result to get the number of words in string s.

My current code returns 12 as the number of word. Since 'ab', 'AB', 'aB', 'Ab' (and same for 'zzzz') are all same and not unique, how can I ignore the variants of a word? I followed the link: http://ift.tt/1ycarDX, but the reference counts unique item in a vector. But, I am using string and not vector.

Here is my code:

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

bool isWordSeparator(char & c) {

    return c == ' ' || c == '-' || c == '\n' || c == '?' || c == '.' || c == ','
    || c == '?' || c == '!' || c == ':' || c == ';';
}

int countWords(string s) {
    int wordCount = 0;

    if (s.empty()) {
    return 0;
    }

    for (int x = 0; x < s.length(); x++) {
    if (isWordSeparator(s.at(x))) {
            wordCount++;

    return wordCount+1;

int main() {
    string s = "ab\nAb!aB?AB:ab.AB;ab\nAB\nZZZZ zzzz Zzzz\nzzzz";
    int number_of_words = countWords(s);

    cout << "Number of Words: " << number_of_words  << endl;

    return 0;

}

Parameter pack expansion questions

I managed to solve a previous question about initializing a static char array, asked here: Initializing a static char based on template parameter

I don't like the need for a secondary function in my solution:

//static char arr[N] = {[0]='0', [1]='x', [N-1]='\0',};
// ideally want this, but not currently implemented in g++

template <char... chars>
struct zero_str {};

template <unsigned N, char... chars>
struct seq_gen { using type = typename seq_gen<N-1, '0', chars...>::type; };

template <char... chars>
struct seq_gen<0, chars...> { using type = zero_str<chars...>; };

template <size_t N>
struct zero_gen { using type = typename seq_gen<N-1, '0', '\0'>::type; };

template <>
struct zero_gen<0> { using type = zero_str<'\0'>; };

template<size_t N> using strsize = typename zero_gen<N>::type;

template<typename T, char... chars>
const char* n2hexHelper(T val, zero_str<chars...>)
{
    thread_local static char hexstr[] = {'0', 'x', chars...};
    /* convert to hex */
    return hexstr;
};

template<typename T>
const char* n2hex(T val)
{
    return n2hexHelper<T> (val, strsize<sizeof(T)*2>() );
}

int main()
{
    std::cout << n2hex(1) << std::endl;
    return EXIT_SUCCESS;
}

Instead, I'd prefer not to need the dummy variable passed to the helper function, and be able to do something like this:

template<typename T, char... chars>
const char* n2HexIdeal(T val)
{
    thread_local static char hexstr[] = {'0', 'x', chars...}; //how to get chars... ?
    /* convert to hex */
    return hexstr;
}

I have two main questions. 1) is something like my ideal case possible with parameter pack expansions? Or is the only way to force the compiler to deduce my char... is to use it as a function parameter? 2) I'm not very familiar with template metaprogramming, so I was wondering if there are any glaring faults or idiomatic missteps with my above solution.

C++ SIMD: Store uint64_t value after bitwise and operation

I am trying to do a bitwise & between elements of two arrays of uint64_t integers and then store the result in another array. This is my program:

#include <emmintrin.h>
#include <nmmintrin.h>
#include <chrono>


int main()
{

  uint64_t data[200];
  uint64_t data2[200];
  uint64_t data3[200];
  __m128i* ptr = (__m128i*) data;
  __m128i* ptr2 = (__m128i*) data2;
  uint64_t* ptr3 = data3;

  for (int i = 0; i < 200; ++i, ++ptr, ++ptr2, ptr3 += 2)
    _mm_store_ps(ptr3, _mm_and_si128(*ptr, *ptr2));

}

However, I get this error:

test.cpp:17:50: error: cannot convert ‘uint64_t* {aka long unsigned int*}’ to ‘float*’ for argument ‘1’ to ‘void _mm_store_ps(float*, __m128)’
     _mm_store_ps(ptr3, _mm_and_si128(*ptr, *ptr2));

For some reason, the compiler thinks I'm copying to an array of floats. Is it possible to do what I am trying to do with arrays of uint64_t?

C++11 move semantic is different between a Lambda and a Function

Take this simple example:

#include <iostream>
struct Data{
    int val = 0;
//Copy ctor
    Data(const Data& a): val(a.val){
        std::cout << "Copy!" << std::endl;
    }
//Move ctor
    Data(Data& a): val(a.val) {
        std::cout << "Move!" << std::endl;
    }
    Data():val(0){}
};

Data a() {
    Data data{};
    std::cout << data.val << std::endl;
    data.val=42;
    return data;
}

auto b=[](){
    Data data{};
    std::cout << data.val << std::endl;
    data.val=42;
    return data;
};

int main(int argc, const char * argv[]) {
    std::cout << "::: Function" << std::endl;
    auto&& d1=a();
    std::cout << d1.val << std::endl;

    std::cout << "::: Lambda" << std::endl;
    auto&& d2=b();
    std::cout << d2.val << std::endl;
    return 0;
}

When it compiles with g++-5 -fno-elide-constructors, the output is as expected:

::: Function
0
Move!
42
::: Lambda
0
Move!
42

The problem is when the Copy ctor is disables, the code compiles fine for function, but not for the lambda:

#include <iostream>
struct Data{
    int val = 0;
//Copy ctor
    Data(const Data&)=delete;

//Move ctor
    Data(Data& a): val(a.val) {
        std::cout << "Move!" << std::endl;
    }
    Data():val(0){}
};

Data a() {
    Data data{};
    std::cout << data.val << std::endl;
    data.val=42;
    return data;
}

auto b=[](){
    Data data{};
    std::cout << data.val << std::endl;
    data.val=42;
    return data;
};
/*
../main.cpp: In static member function ‘static Data<lambda()>::_FUN()’:
../main.cpp:5:1: error: use of deleted function ‘Data::Data(const Data&)’
 };
 ^
../main.cpp:76:5: note: declared here
     Data(const Data& a)=delete;
     ^
*/

int main(int argc, const char * argv[]) {
    std::cout << "::: Function" << std::endl;
    auto&& d1=a();
    std::cout << d1.val << std::endl;

    std::cout << "::: Lambda" << std::endl;
    auto&& d2=b();
    std::cout << d2.val << std::endl;
    return 0;
}

What am I missing here?

Calling std::~basic_string() in gdb

As per @EvanED in http://ift.tt/2lWvdas I created a gdb command newstr to create a new std::string and put it in a gdb convenience variable:

define newstr
set ($arg0)=(std::string*)malloc(sizeof(std::string))
call ($arg0)->basic_string()
# 'assign' returns *this; casting return to void avoids printing of the struct.
call (void)( ($arg0)->assign($arg1) )
end

It works great:

(gdb) newstr $foo "hello world"
(gdb) p $foo->c_str()
$57 = 0xb22e388 "hello world"

I use newstr in other custom gdb commands, so for tidyness I also created delstr:

define delstr
call ($arg0)->~basic_string($arg0)
call free($arg0)
set ($arg0)=(void*)0
end

It works, but the destructor call produces an annoying message:

(gdb) delstr $foo
warning: Using non-standard conversion to match method std::string::~basic_string to supplied arguments
$62 = 0

Can I avoid the "non-standard conversion" message? (I'm using gdb 7.10.)

Custom std::set comparator with compound types

This is related to my previous question regarding templates, that I managed to make work. I tried a more complex example:

template <typename T>
struct Cmp{
    bool operator() (const set<typename set<Node <T>>::iterator, Cmp<T>>, Cmp<T>& lhs, const set<typename set<Node <T>>::iterator, Cmp<T>>, Cmp<T> &rhs) {
        return true;
    }

    bool operator() (const set<typename set<Node <T>>::iterator, Cmp<T>>, Cmp<T>& lhs, const unsigned& rhs) {
        return true;
    }
};

template <typename T>
class Graph {

private:
    set<set<typename set<Node <T>>::iterator, Cmp<T>>, Cmp<T>> cliques = ;
};

Node is a template class. I only instantiate the Graph class once, with <int>, but I get the following compilation error:

error: no match for call to 
(Cmp<int>) (const std::set<std::_Rb_tree_const_iterator<Node<int> >, Cmp<int>, std::allocator<std::_Rb_tree_const_iterator<Node<int> > > >&, const key_type&)
    && _M_impl._M_key_compare(_S_key(_M_rightmost()), __k))

I have seemingly tried about every possible prototypes for the functions in Cmp. The error seems to be that operator() (const set<set<Node<int>>::const_iterator, Cmp<int>>&, const key_type&) is not defined. However, assuming that key_type is the type of the values stored in the set, the override I have provided above should work.

What is missing from my code?

std::is_convertible

First of all, I'm sorry that I don't have a mcve, though, I don't manage to reduce the code without this answer. (And can't run creduce)

My current code is similar to the following:

#include <type_traits>

namespace NS
{
    class C final
        {
        // ...
        };
    static_assert(std::is_convertible<C, C>::value, "Strange bug?");
}

This piece of code is included in over 10 000 different cpp files which get compiled with almost the same command line arguments. (Only differences are in define related to declspec(dllimport/dllexport) and the cpp/obj files)

Every of these cpp files can compile, except for 1, on which the static_assert fails if I try to compile it with clang-cl (Using version 4.0.0 RC2), the code however does compile with MSVC2015.

As I'm out of options hunting down the problem, I would like to know which external factors can influence this static assert, so I can start searching the preprocessed file for them.

Tnx in advance, JVApen

remap template parameters struct

I'm new with templates and was wondering how I could do the following: I have a Fixed point structure that allows for fixed point calculations and is defined as follows:

template<int bits, int offset>
struct Fixed {
      int64_t raw;
      inline Fixed() {}
      ...
}

I'd like to expand this so that I can declare a self defined floating point representation and the compiler translates this to the correct fixed point definition. I tried this as follows:

template<int totBits, int expBits, int expOffset>
struct Fixed<exp2(expBits)+totBits-expBits-2,expOffset-totBits+expBits> {
       inline Fixed() {}
       inline explicit Fixed(double value) {
               Quantization function of floating point here
       }
};

However, this gives me the error: "Template argument involves template parameter(s)".

How can I remap the initial template such that I can do the following: fixed::Fixed<8,3,0> foo; And the compiler sees this as: fixed::Fixed<11,-3> foo;?

I know that when I assign a value to foo I will have to manually quantise it as if it is stored as a floating point: e.g. foo = fixed::Fixed<8,3,0>(243) which will give foo = 240 and foo = fixed::Fixed<8,3,0>(244) will give foo = 248.