mardi 31 mai 2016

Match template parameter to template type

How would I write template or constexpr code such that match is true only if Ts contains an instance of A?

template <std::uint32_t, int, int>
struct A;

template <typename... Ts>
struct X
{
    constexpr bool match = ???;
};

Standard library function to create array of indices whose corresponding value is a given number

I've got a C-style array called board that contains some char's. I'm trying to create a std::array or std::vector (either would be fine, although std::array would be preferable) to store all the indices of board that are a certain value (in my case, 0).
This code I wrote is functional and works well:

std::vector<int> zeroes;
zeroes.reserve(16); //board has 16 elements, so zeroes.size() will never be larger than 16.
for (int i = 0; i < 16; ++i)
{
    if (board[i] == 0)
    {
        zeroes.push_back(i);
    }
}

However, from past experience, whenever a std function exists that could replace part of my code, it is turser and hence stylistically preferred and also faster. My function seems like a fairly basic operation - I know there is a standard function* to access the index of an array that contains a value when that value only occurs once** in the array. So, is there a standard function to create an array of the indices that contain a value, assuming that more than one such index exists?
Thanks a lot!


* Technically, two nested function calls: int x = std::distance(board, std::find(board, board + 16, 0));. See the accepted answer here.
** Well, it still works if more than one index with the desired value is present, but it returns only the first such index, which isn't very useful in my context.

Converting const auto & to iterator

A number of posts I've read lately claim for(const auto &it : vec) is the same as using the longer iterator syntax for(std::vector<Type*>::const_iterator it = vec.begin(); it != vec.end(); it++). But, I came upon this post that says they're not the same.

Currently, I'm trying to erase an element in a for loop, after it is used, and wondering if there is any way to convert const auto &it : nodes to std::vector<txml::XMLElement*>::iterator?

Code in question:

std::vector<txml2::XMLElement *> nodes;
//...
for (const auto &it : nodes)
{
    //...       
   nodes.erase(it);
}

I pretty sure I could just rewrite std::vector<txml2::XMLElement*> as a const pointer, but would prefer not to since this code is just for debugging in the moment.

Malloc error :incorrect checksum for freed object

I am unable to figure it out. As, why I am getting the error

malloc: *** error for object 0x7fd812403a80: incorrect checksum for freed object - object was probably modified after being freed.
*** set a breakpoint in malloc_error_break to debug

Following is the snippets of the code. If I comment out the function call to method 'pre_compute_nCr', then the code works as expected. However, its only calling function 'pre_compute_nCr', it pops the above mentioned error. In the code, 'binom_obj (i,j)' returns the value of 'i choose k'

  void pre_compute_nCr (int n, std::vector<std::vector<uint64_t>>& n_chos_k) {

        n_chos_k[0].push_back(0);
        for (int i = 1; i < n; ++i) n_chos_k[i].resize(i, 0);

        jaz::Binom<int> binom_obj;

        for (uint64_t i = 1; i < n; ++i) {
            for (uint64_t j = 0; j <= i; ++j) {
                n_chos_k[i][j] = binom_obj(i, j);
            }  // for j  
        } // for i
    }


    int dynamicProgramming(int n, XX xx_obj) {

        std::vector<std::vector<uint64_t>> n_chos_k;
        n_chos_k.resize(n);
        pre_compute_nCr(n, n_chos_k);


        return 0;
    }

Writing shorter datatypes to memory doesn't affect runtime?

I've been comparing the write times for several datatypes, and I've noticed something I find highly baffling. Firstly, here is my code:

#include <iostream>
#include <array>
#include <ctime>

#define its 1000000
#define len 1000

int main()
{
    std::array<int, len> int_arr;
    std::array<char, len> char_arr;
    std::array<bool, len> bool_arr;
    std::clock_t begin = std::clock();
    for (int i = 0; i < its; ++i)
    {
        std::fill(int_arr.begin(), int_arr.end(), 0);
    }
    std::clock_t end = std::clock();
    double elapsed = double(end - begin) / CLOCKS_PER_SEC;
    std::cout << "int_arr " << elapsed << std::endl;
    begin = std::clock();
    for (int i = 0; i < its; ++i)
    {
        std::fill(char_arr.begin(), char_arr.end(), 0);
    }
    end = std::clock();
    elapsed = double(end - begin) / CLOCKS_PER_SEC;
    std::cout << "char_arr " << elapsed << std::endl;
    begin = std::clock();
    for (int i = 0; i < its; ++i)
    {
        std::fill(bool_arr.begin(), bool_arr.end(), false);
    }
    end = std::clock();
    elapsed = double(end - begin) / CLOCKS_PER_SEC;
    std::cout << "bool_arr " << elapsed << std::endl;
}

This code compares the times taken to write to arrays containing different datatypes (the repeated fills are to make the runtimes meaningfully measurable). I would expect char and bool to take roughly the same amount of time, since the computer still has to write the full byte into RAM. Furthermore, since int takes 4 bytes, I would expect it to run four times as slowly.
I compiled the above code with the -O3 optimizer flag and with -std=c++11. Contrary to my expectations, the result varies greatly! As expected, char and bool take the same amount of time as each other consistently (and also the same amount of time between runs). However, approximately half the time int is only twice as slow (in this case, a factor of 2.19):

int_arr 0.043705
char_arr 0.01995
bool_arr 0.022835

And the other half of the time, it is four times as slow (in this case, a factor of 3.91):

int_arr 0.076907
char_arr 0.01965
bool_arr 0.019354

Furthermore, it is never in between! What on earth is going on here? An explanation would be greatly appreciated!

C++ global variable that can be changed only in one method, possible?

I'm looking for a way to have an int variable that persists value across method calls. From this perspective a class member will be good.

But I would like that int variable to be changed in only one particular method.

How do I make that?

I tough about

void MyClass::my_method(){
    static int var = 0;
    var++;
}

But, I would like var = 0; to be executed only the first time.

nullptr not declared even with C++11 and C++14 enabled

I just installed CodeLite and the latest version of the TDM-GCC compiler. It supports both C++11 and C++14. However, when I write a program using nullptr it is still telling me that 'nullptr' was not declared in this scope .

enter image description here

What else do I have to do in order for nullptr to be accepted by the compiler?

Thanks!

Is std::get_time broken in g++ and clang++?

I was working with some time functions today and noticed that the standard conversion using %r (or %p) does not seem to work for input via std::get_time() on g++ or clang++. See this live code version for g++ and clang++. It does seem to work as expected under Windows with VC++ (see this closely related question). Also note that the effect is the same whether or not the imbue line is included. The locale on my Linux machine is set to "en_US.UTF-8" if it matters.

#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <ctime>

int main(){
    std::tm t{};
    std::stringstream ss{"1:23:45 PM"};
    ss.imbue(std::locale(std::cin.getloc(), 
             new std::time_get_byname<char>("en_US")));
    ss >> std::get_time(&t, "%r");
    if (ss.fail()) {
        std::cout << "Conversion failed\n" << std::put_time(&t, "%r") << '\n';
    } else {
        std::cout << std::put_time(&t, "%r") << '\n';
    }
}

Why does ThreadSanitizer report a race with this lock-free example?

I've boiled this down to a simple self-contained example. The main thread enqueues 1000 items, and a worker thread tries to dequeue concurrently. ThreadSanitizer complains that there's a race between the read and the write of one of the elements, even though there is an acquire-release memory barrier sequence protecting them.

#include <atomic>
#include <thread>
#include <cassert>

struct FakeQueue
{
    int items[1000];
    std::atomic<int> m_enqueueIndex;
    int m_dequeueIndex;

    FakeQueue() : m_enqueueIndex(0), m_dequeueIndex(0) { }

    void enqueue(int x)
    {
        auto tail = m_enqueueIndex.load(std::memory_order_relaxed);
        items[tail] = x;              // <- element written
        m_enqueueIndex.store(tail + 1, std::memory_order_release);
    }

    bool try_dequeue(int& x)
    {
        auto tail = m_enqueueIndex.load(std::memory_order_acquire);
        assert(tail >= m_dequeueIndex);
        if (tail == m_dequeueIndex)
            return false;
        x = items[m_dequeueIndex];    // <- element read -- tsan says race!
        ++m_dequeueIndex;
        return true;
    }
};


FakeQueue q;

int main()
{
    std::thread th([&]() {
        int x;
        for (int i = 0; i != 1000; ++i)
            q.try_dequeue(x);
    });

    for (int i = 0; i != 1000; ++i)
        q.enqueue(i);

    th.join();
}

ThreadSanitizer output:

==================
WARNING: ThreadSanitizer: data race (pid=17220)
  Read of size 4 at 0x0000006051c0 by thread T1:
    #0 FakeQueue::try_dequeue(int&) /home/cameron/projects/concurrentqueue/tests/tsan/issue49.cpp:26 (issue49+0x000000402bcd)
    #1 main::{lambda()#1}::operator()() const <null> (issue49+0x000000401132)
    #2 _M_invoke<> /usr/include/c++/5.3.1/functional:1531 (issue49+0x0000004025e3)
    #3 operator() /usr/include/c++/5.3.1/functional:1520 (issue49+0x0000004024ed)
    #4 _M_run /usr/include/c++/5.3.1/thread:115 (issue49+0x00000040244d)
    #5 <null> <null> (libstdc++.so.6+0x0000000b8f2f)

  Previous write of size 4 at 0x0000006051c0 by main thread:
    #0 FakeQueue::enqueue(int) /home/cameron/projects/concurrentqueue/tests/tsan/issue49.cpp:16 (issue49+0x000000402a90)
    #1 main /home/cameron/projects/concurrentqueue/tests/tsan/issue49.cpp:44 (issue49+0x000000401187)

  Location is global 'q' of size 4008 at 0x0000006051c0 (issue49+0x0000006051c0)

  Thread T1 (tid=17222, running) created by main thread at:
    #0 pthread_create <null> (libtsan.so.0+0x000000027a67)
    #1 std::thread::_M_start_thread(std::shared_ptr<std::thread::_Impl_base>, void (*)()) <null> (libstdc++.so.6+0x0000000b9072)
    #2 main /home/cameron/projects/concurrentqueue/tests/tsan/issue49.cpp:41 (issue49+0x000000401168)

SUMMARY: ThreadSanitizer: data race /home/cameron/projects/concurrentqueue/tests/tsan/issue49.cpp:26 FakeQueue::try_dequeue(int&)
==================
ThreadSanitizer: reported 1 warnings

Command line:

g++ -std=c++11 -O0 -g -fsanitize=thread issue49.cpp -o issue49 -pthread

g++ version: 5.3.1

Can anybody shed some light onto why tsan thinks this is a data race?

Use SFINAE to detect the existence of a templated member function

I learned SFINAE can be used to determine whether a member function exists in a class or not. For example, the following code can be used to check if the method hello is present in a class.

struct has_method_hello {

  using yes = char[1];
  using no  = char[2];

  template <typename U, typename C>
  static constexpr yes& test(decltype(&U::hello));

  template <typename>
  static constexpr no& test(...);

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

}; 

struct Foo {
  void hello() {}
}

std::cout << has_method_hello <Foo> :: value << std::endl;  // 1

However, suppose the hello is templated, how can I modify the trick so it can still function properly?

struct Foo {
  template <typename T>
  void hello(T&) {...}
}

Creating Xcode project from Cmake contains unwanted compiler flags

I've been unable to find a definitive answer, so apologies if the answer is out there.

I use cmake to generate project files as I tend to work cross-platform. On OSX/Xcode, I'm seeing unwanted compiler flags being used, specifically warning enable/disable. I like to compile with as many warnings on as possible, and set warnings as errors.

Consider the following:

File: CMakeLists.txt

cmake_minimum_required( VERSION 3.0 )
project( test )
set( CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} -std=c++14 )
add_compile_options( "-Werror" )
add_compile_options( "-Weverything" )
add_compile_options( "-Wno-c++98-compat-pedantic" )
add_compile_options( "-Wno-padded" )
add_executable( Test main.cpp )
target_link_libraries( Test libstdc++.dylib libc++.dylib )

File: main.cpp

#include <iostream>

int main( int argc, char * const argv[] )
{
    (void)argc;
    (void)argv;
    std::cout << "Kittens." << std::endl;
    return 0;
}

If I then run cmake:

cmake -G Xcode .

(normally I'd use a builds directory, but not here for simplicity).

Then build (from the command line):

cmake --build . --config Debug --target ALL_BUILD

The simple sample will compile. If I now look at the command used to compile main.cpp I see the following:

CompileC test.build/Debug/Test.build/Objects-normal/x86_64/main.o main.cpp normal x86_64 c++ com.apple.compilers.llvm.clang.1_0.compiler
    cd /Users/username/Development/test
    export LANG=en_US.US-ASCII
    /Applications/http://ift.tt/1jmLxI7 -x c++ -arch x86_64 -fmessage-length=101 -fdiagnostics-show-note-include-stack -fmacro-backtrace-limit=0 -fcolor-diagnostics -Wno-trigraphs -fpascal-strings -O0 -Wno-missing-field-initializers -Wno-missing-prototypes -Wno-return-type -Wno-non-virtual-dtor -Wno-overloaded-virtual -Wno-exit-time-destructors -Wno-missing-braces -Wparentheses -Wswitch -Wno-unused-function -Wno-unused-label -Wno-unused-parameter -Wno-unused-variable -Wunused-value -Wno-empty-body -Wno-uninitialized -Wno-unknown-pragmas -Wno-shadow -Wno-four-char-constants -Wno-conversion -Wno-constant-conversion -Wno-int-conversion -Wno-bool-conversion -Wno-enum-conversion -Wno-shorten-64-to-32 -Wno-newline-eof -Wno-c++11-extensions -DCMAKE_INTDIR=\"Debug\" -isysroot /Applications/http://ift.tt/1jCtz97 -fasm-blocks -fstrict-aliasing -Wdeprecated-declarations -Winvalid-offsetof -mmacosx-version-min=10.11 -g -Wno-sign-conversion -I/Users/username/Development/test/Debug/include -I/Users/username/Development/test/test.build/Debug/Test.build/DerivedSources/x86_64 -I/Users/username/Development/test/test.build/Debug/Test.build/DerivedSources -Wmost -Wno-four-char-constants -Wno-unknown-pragmas -F/Users/username/Development/test/Debug -std=c++14 -Werror -Weverything -Wno-c++98-compat-pedantic -Wno-padded -MMD -MT dependencies -MF /Users/username/Development/test/test.build/Debug/Test.build/Objects-normal/x86_64/main.d --serialize-diagnostics /Users/username/Development/test/test.build/Debug/Test.build/Objects-normal/x86_64/main.dia -c /Users/username/Development/test/main.cpp -o /Users/username/Development/test/test.build/Debug/Test.build/Objects-normal/x86_64/main.o

The really annoying thing here is any of the -W options. In my CMakeLists.txt I've clearly said I want all warnings, warnings treated as errors, and whitelisted a couple of warnings.

However, if I strip out all the -W options in the compile command, I see (in addition to what I asked for):

-Wno-trigraphs
-Wno-missing-field-initializers
-Wno-missing-prototypes
-Wno-return-type
-Wno-non-virtual-dtor
-Wno-overloaded-virtual
-Wno-exit-time-destructors
-Wno-missing-braces
-Wparentheses
-Wswitch
-Wno-unused-function
-Wno-unused-label
-Wno-unused-parameter
-Wno-unused-variable
-Wunused-value
-Wno-empty-body
-Wno-uninitialized
-Wno-unknown-pragmas
-Wno-shadow
-Wno-four-char-constants
-Wno-conversion
-Wno-constant-conversion
-Wno-int-conversion
-Wno-bool-conversion
-Wno-enum-conversion
-Wno-shorten-64-to-32
-Wno-newline-eof
-Wno-c++11-extensions
-Winvalid-offsetof
-Wno-sign-conversion
-Wmost
-Wno-four-char-constants
-Wno-unknown-pragmas

Some of those things listed I really do not want disabled. I really want just the -W options I specified in the cmake file being used for compilation, but I can't see who is injecting all these extra things and from where.

Is there any way I can get cmake to tell xcode not to include all these extra -W options from compilation?

Note: using:

cmake 3.5.2

Apple LLVM version 7.3.0 (clang-703.0.31)

C++ Pointer value changes with static_cast

I'm seeing weird behavior trying to combine C++ and C code. I'm using a C++ class within C code, using static_cast with a void* to the class. This is done in the following way.

//C++ code
typedef void* CSPI;
CSPI newCSPI() {
    return static_cast<CSPI>(new XSpi);
}

This function is declared in the header as follows.

//C++ code
extern "C" CSPI newCSPI(void);

I can then call the C++ functions in the C code. An example of the implementation of the other functions is seen below.

//C++ code
void selectCSlave(void* Cspi) {
    static_cast<SPI*>(Cspi)->selectSlave();
}

This function is also declared as extern "C" in the header.

This casting function is implemented as follows.

//C++ code
void SPI::selectSlave(void) {
    // Select the slave by setting the slave select to low
    XGpio_DiscreteWrite(&slaveSelectDevice, 1, 0x00);
}

I'm trying to execute the following block of code. It all succeeds except for the very last line.

//C code
u8 junk, waitstate = 0xff;
/* Select device. */
selectCSlave(spi);

/* Write address and command to device. */
esc_address(address, ESC_CMD_READWS, (uint16_t *) tALevent);
/*transfering the wait-state byte*/
transferC(spi, &waitstate, &junk,1);
/* Here we want to read data and keep MOSI low (0x00) during
 * all bytes except the last one where we want to pull it high (0xFF).
 * Read (and write termination bytes).
 */
transferC(spi, read_termination + (sizeof(read_termination) - len),
        (uint8_t *) buf, len);
/* Un-select device. */
deselectCSlave(spi);

During the deselectCSlave(spi) call, the pointer somehow changes value. Inside the cast function, the pointer still has the same value. Inside the function it is cast to, the value changes. The implementation is exactly the same as selectSlave(), which does work.

I can't see why the value would suddenly change. What am I missing here?

Circularity when using base and derived class as arrays in both

I am trying so make a class which holds a arbitrary value as specified in NBT format. It is a kind of json, but more advanced.

So, I make a class which holds a ListValue(a value without a name) and another one which holds a Value(with name). In the derived class, I lift = operator from base

using ListValue::operator=;

In a third file I have two usings:

using CompoundData = std::vector<Value>;
using ListData = std::vector<ListValue>;

ListValue has a private member as:

union ValueHolder
{
    Byte vByte;
    Short vShort;
    Int vInt;
    Long vLong;
    Float vFloat;
    Double vDouble;
    String* pString;
    CompoundData* pCompound;
} mData;

(I'll add ListData* later)

The problem is I have absolutely no idea how how to include all these headers so it will work with the circularity. I tried several forward declarations and containers as vector or vector with smart pointers for breaking it, but nothing worked for me.

I would be very very grateful if you could help me to give me a(n) idea / solution for my code. Thank you very much.

Ubuntu C++ UDP package don't arravie

I'm want to tinker a bit with c++ and sockets, so I've copied an example server/client to test ist. I've got it compiled, but the server don't receive any message. The client:

/* UDP client in the internet domain */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#include <iostream>

void error(const char *);
int main(int argc, char *argv[])
{
   int sock, n;
   unsigned int length;
   struct sockaddr_in server, from;
   struct hostent *hp;
   char buffer[256];

   if (argc != 3) { 
                printf("Usage: server port\n");
                exit(1);
   }
   sock= socket(AF_INET, SOCK_DGRAM, 0);
   if (sock < 0) error("socket");

   server.sin_family = AF_INET;
   hp = gethostbyname(argv[1]);
   if (hp==0) error("Unknown host");

   /*bcopy((char *)hp->h_addr, 
        (char *)&server.sin_addr,
         hp->h_length);*/
   memcpy((char *)hp->h_addr, 
        (char *)&server.sin_addr,
         hp->h_length);
   server.sin_port = htons(atoi(argv[2]));
   length=sizeof(struct sockaddr_in);
   printf("Please enter the message: ");
   //bzero(buffer,256);
   memset(buffer, 0, 256);
   fgets(buffer,255,stdin);
   n=sendto(sock,buffer,
            strlen(buffer),0,(const struct sockaddr *)&server,length);
   if (n < 0) error("Sendto");
   n = recvfrom(sock,buffer,256,0,(struct sockaddr *)&from, &length);
   if (n < 0) error("recvfrom");
   write(1,"Got an ack: ",12);
   write(1,buffer,n);
   close(sock);
   return 0;
}

void error(const char *msg)
{
    perror(msg);
    exit(0);
}

Server: /* Creates a datagram server. The port number is passed as an argument. This server runs forever */

#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <netdb.h>
#include <stdio.h>

void error(const char *msg)
{
    perror(msg);
    exit(0);
}

int main(int argc, char *argv[])
{
   int sock, length, n;
   socklen_t fromlen;
   struct sockaddr_in server;
   struct sockaddr_in from;
   char buf[1024];

   if (argc < 2) {
      fprintf(stderr, "ERROR, no port provided\n");
      exit(0);
   }

   sock=socket(AF_INET, SOCK_DGRAM, 0);
   if (sock < 0) error("Opening socket");
   length = sizeof(server);
   //bzero(&server,length);
   memset(&server, 0, length);
   server.sin_family=AF_INET;
   server.sin_addr.s_addr=INADDR_ANY;
   server.sin_port=htons(atoi(argv[1]));
   if (bind(sock,(struct sockaddr *)&server,length)<0) 
       error("binding");
   fromlen = sizeof(struct sockaddr_in);
   while (1) {
       n = recvfrom(sock,buf,1024,0,(struct sockaddr *)&from,&fromlen);
       if (n < 0) error("recvfrom");
       write(1,"Received a datagram: ",21);
       write(1,buf,n);
       n = sendto(sock,"Got your message\n",17,
                  0,(struct sockaddr *)&from,fromlen);
       if (n  < 0) error("sendto");
   }
   return 0;
 }

As a port I use 1337 and as the IP for the cleint i tried 127.0.0.1 and localhost. After I wrote a message both programms didn't do anything for ~15 min then I closed the terminals. I used google but didn't find anything (but I'm not sure what I should search).

Deus

Balancing bracket algorithm (Recursion)-New Method

S, I have tried out my own new balancing algorithm using recursion.

The function parses through a string and when a new opening bracket is encountered,it calls itself using the latest encountered bracket as the new comparing bracket (hence fulfills the property of stack LIFO).Now if a closing bracket is encountered and it does not matches with the updated opening bracket,a false is returned and the program is terminated. If a closing matching bracket is encountered,a true is returned and function returns to its last calling instance.This continues till the length of string is parsed. A count function is also included to check the balance of pairs of brackets.

Below is my code.Please suggest me any improvements and bug fixes for making the algorithm better.Try focusing on the given structure and do not suggest alternate data structures such as stack,list,etc.

 int i=0,l=s.length(),count=0; //global variables
 // NULL is supplied in first call of s by calling object

 bool i(String c,char *s)
{
  char *t=s; // stores latest opening bracket encountered through recursion
  for(;i<l;i++) // l is length of string
 {
     if(c[i]=='{' || '(' || '[')
   {
      ++count;
      bool i(c,t);
   }

   else if(c[i]=='}' || ']' || ')')
   {
     if(c[i]==t <matching bracket for s>             
     {
       --count;
       return true;
     }   
     else 
     cout<<"sorry not balanced";
     exit(o); //terminate program after checking failure 
   }//else loop ends

   if(count==0)
   return true;
   else
   return false;
 } // string parsing ends
}    

Google-Breakpad crash dump: did not get error file name, line

I have built Google breakpad as ndk-build build system with -g option.

I have downloaded dump_syms and minidump_stackwalk tools from location.

But when i tried to open minidump on my Linux machine it provide me output as

016-05-31 15:06:33: minidump.cc:4518: INFO: Minidump closing minidump
Operating system: Android
                  0.0.0 Linux 3.10.57+ #1 SMP PREEMPT Tue Jul 7 11:02:04 CST 2015 armv7l
CPU: arm
     ARMv7 ARM part(0x4100c070) features: swp,half,thumb,fastmult,vfpv2,edsp,thumbee,neon,vfpv3,tls,vfpv4,idiva,idivt
     4 CPUs

Crash reason:  SIGABRT
Crash address: 0x402d

Thread 68 (crashed)
 0  libc.so + 0x3d524
     r0 = 0x00000000    r1 = 0x0000424a    r2 = 0x00000006    r3 = 0x00000000
     r4 = 0x9ecd7dd8    r5 = 0x00000006    r6 = 0x00000058    r7 = 0x0000010c
     r8 = 0xb7c94158    r9 = 0xb7c93d80   r10 = 0x00000000   r12 = 0x0000424a
     fp = 0x9ecd754c    sp = 0x9ecd7490    lr = 0xb6e34db5    pc = 0xb6e5b524
    Found by: given as instruction pointer in context
 1  libc.so + 0x179c9
     sp = 0x9ecd74a8    pc = 0xb6e359cb
    Found by: stack scanning
 2  libc.so + 0x1416b
     sp = 0x9ecd74b0    pc = 0xb6e3216d
    Found by: stack scanning
 3  test.so + 0x114dd6
     sp = 0x9ecd74cc    pc = 0xa3566dd8
    Found by: stack scanning
 4  test.so + 0x11483e
     sp = 0x9ecd74d4    pc = 0xa3566840
    Found by: stack scanning
 5  libc.so + 0x124f2
     sp = 0x9ecd74d8    pc = 0xb6e304f4
    Found by: stack scanning
 6  libc.so + 0x154a1
     sp = 0x9ecd74e0    pc = 0xb6e334a3
    Found by: stack scanning
 7  libc.so + 0x4ae3a
     sp = 0x9ecd74e4    pc = 0xb6e68e3c
    Found by: stack scanning
 8  libc.so + 0x141ef
     sp = 0x9ecd74f0    pc = 0xb6e321f1
    Found by: stack scanning
 9  libc.so + 0x4ae3a
     sp = 0x9ecd74f4    pc = 0xb6e68e3c
    Found by: stack scanning
10  test.so + 0x11483e
     sp = 0x9ecd74f8    pc = 0xa3566840
    Found by: stack scanning

I am doing something wrong but did not able to figure it out. to generate sym file i followed below procedure.

$dump_syms $PROJECT_PATH/obj/local/$ABI/test.so > test.so.sym

$head -n1 test.so.sym

$mkdir -p symbols/http://ift.tt/1P0tIMt
$mv test.so.sym  symbols/http://ift.tt/1P0tIMt

$ minidump_stackwalk xxxx.dmp  /symbols

Get the name of a std::function

In the following toy-example, i would like to get the name of a function. The function itself was given as an std::function argument. Is this somehow possible in c++ to get name of a std::function object?

void printName(std::function<void()> func){
    //Need a function name()
    std::cout << func.name();
}

void magic(){};

//somewhere in the code
printName(magic());

output: magic

Otherwise i would have to give the function's name as a second parameter.

"Invalid renderer" with SDL2 & OpenGL

I already used SDL2 before, and now I try to use it with openGL 2.1. But when I try to create a renderer, I get "Invalid renderer". For creating a renderer I already use the same line before for simple SDL2 project, but with openGL it appears to not work properly. Does someone have an idea why ? I tried to change the flags of CreateRenderer, and I have this error for all of them except "SDL_RENDERER_SOFTWARE", but with him I can't grab input properly, and when the mouse cursor goes out the Window I have this error : "Invalid window".

Here is my code :

#include <SDL2/SDL.h>
#include <GL/glut.h>
#include <iostream>

const int WIDTH = 500, HEIGHT = 500;

using namespace std;

SDL_Window* pWindow;
SDL_Renderer* pRenderer;
SDL_Event event;

void initOGL()
{
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(70,(double)WIDTH/HEIGHT,1,1000);

    glEnable(GL_DEPTH_TEST);
    glEnable(GL_TEXTURE_2D);
}

void initSDL()
{
    if (SDL_Init(SDL_INIT_VIDEO) != 0)
    {
        cout << "Video init failed" << endl;
        exit(EXIT_FAILURE);
    }
    cout << "Video initialized" << endl;


    // Window creation
    pWindow = SDL_CreateWindow("Test OGL w/ SDL2", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);
    if (!pWindow)
    {
        cout << "Window creation failed" << endl;
        exit(EXIT_FAILURE);
    }
    cout << "Window created" << endl;

    // Renderer creation
    pRenderer = SDL_CreateRenderer(pWindow, -1, SDL_RENDERER_ACCELERATED);
    if (!pRenderer)
    {
        cout << "Renderer creation failed" << endl;
    }
    cout << "Renderer created" << endl;

    // OGL version
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);

    // OGL context
    SDL_GLContext contexteOGL = SDL_GL_CreateContext(pWindow);
    if (!contexteOGL)
    {
        cout << "Echec création du contexte" << endl;
    }
    cout << "Contexte créé" << endl;
}

int main(int argc, char const *argv[])
{
    initSDL();
    initOGL();
    cout << "SDL_ERROR : " << SDL_GetError() << endl;
    return 0;
}

std::unique_ptr and exception safety

Do I need to wrap std::unique_ptr usage with try/catch in code which should be exception safe?
std::unique_ptr will hold a raw memory block created by ::malloc (with my custom deleter to call ::free).

Can I call a function from the base class which return bool from derived class

I have the following base class:

class node_layer_manager_t : public layer_manager_t
{
protected:
    //Devices
    trx_t        trx;
private:
    std::vector<string>               trx_dump_labels;

public:
    node_layer_manager_t( xml::node_t& params ); 
    ~node_layer_manager_t();

    virtual bool    set_profile(void) override;    
}

I created the following derived class:

class node_layer_manager_with_rad_t : public node_layer_manager_t
{
protected:
    //Devices
    radio_t radio;

public:
    node_layer_manager_with_rad_t(xml::node_t& params );
    ~node_layer_manager_with_rad_t();

    virtual bool    set_profile(void) override;

    virtual void radio_monitoring_job_function(void);

    intervalues_t<double>   radio_tmp;
    ushort          duration_seconds_for_radio_monitoring;
};

I want it so that the set profile will execute the set_profile of the base class and in addition some other action.

Can I just write it this way?

bool node_layer_manager_with_rad_t::set_profile(void)
{
    node_layer_manager_t::set_profile();
    try
    {
        string_t profile_tag = "logs/trx_dump/node:"+get_id();
        dev_tx = profile->get_decendant(profile_tag.c_str());
        cout<<"sarit id= "<< get_id()<<endl;
        success = true;
    }
    catch(...)
    {
        cout<<"sarit  profile error: "<<endl;
        success = false;
    }
    return success;  //**
}

**Or should I reurn the follwing:

return (success success&&node_layer_manager_t::set_profile()); 

How to iterate over a generic vector

I've always found C++ templates inscrutable, and C++ error messages more so. I want to understand it, rather than always feeling confused. Here's the latest bizarre experience:

error: conversion from ‘<unresolved overloaded function type>’ to non-scalar type ‘std::vector<int>::iterator {aka __gnu_cxx::__normal_iterator<int*, std::vector<int> >}’ requested

This doozy comes from the following code:

#include <iostream>
#include <vector>

using namespace std;

template <typename T>
void printVector(const vector<T>& v) {
    for (typename vector<T>::iterator iter = v.begin; iter != v.end; iter++) {
        cout << *iter << endl;
    }
}

int main() {
    vector<int> v{1, 2, 3};
    printVector(v);
    return 0;
}

It has no problem iterating over the vector if I use a C++11 range-based loop. I want to learn how to do it using iterators.

Can someone explain what the error means and how to fix it?

It would also be wonderful if I could get a recommendation of a book that explains templates well.

Creating objects inside a C++ library (like std::cout)

I recently read somewhere that std::cout is an instance of the std::ostream class. I wish to implement a similar kind of thing. I make a class Animal and want to provide an instance of Animal class dog in the library itself like std::cout. I am not sure how to do it but here's a code snippet which hopefully will give you an idea of what I'm trying to achieve.

// lib.h

#ifndef LIB_H
#define LIB_H

#include <string>

class Animal {
public:
    Animal();
    std::string name;
};

Animal dog;
dog.name = "dog";
extern Animal dog;

#endif


// lib.cpp

#include "lib.h"

Animal::Animal() {}

Animal dog;
dog.name = "dog";


// main.cpp

#include "lib.h"
#include <iostream>

int main() {
    Animal my_dog = dog;
    std::cout << my_dog.name << std::endl;
    return 0;
}

This is the error I get when I try this code:

lib.cpp:6:1: error: ‘dog’ does not name a type
 dog.name = "dog";

This kind of code may seem silly, but I still am looking for ways to implement this approach and not its alternatives.

lundi 30 mai 2016

System::Threading::Timer, make it running at the same time as form

I couldn't find any really simple example on how to create a threaded timer to run along my form. The goal of my application is simple, I just want it to check the ping and update the label. I tried the WindowsForms::Timer, but it runs on the same thread as UI, so using UI, while constantly refreshing is not an option.

Bigraph butterfly

How do you make a bigraph butterfly in c++ (i'm using codeblocks compiler).It needs to have 89 nods and every nod in the wing must have the exterior grade equal to the interior grade = 1.There are 2 circuits in the graph no terminal nodes or isolated ones,between a wing's extremities there has to be a road. Thankyou in advance.

My c/c++ implementation with adversarial search on artificial intellgence game playing program

Recently I'm embarking on my self-studying program(using c/c++) implementation of an artificial intelligence Japanese chess(i.e. Shogi) playing program. In order to speed up the efficiency of optimal alpha-beta search expansion,I use the "bitboard" data structure as unsigned 32-bit integer to represent each position on the 5x5 board.While getting an optimal alpha score from the function ABmove(),it simply tell which piece to move to get the maximum game score.

There were six basic pieces on each sides,they are: Pawn x 1 Rook x 1 Bishop x 1 Silver general x 1 Gold general x 1 King x 1 Unlike chess,some of the specific pieces(Pawn,Rook,Bishop and Silver general) can be promoted to another pieces as them move to the end of the opposite side of opponent,and their moves will be different,too.
I'm curious about what function I should call at the begin of main(),and whether should I determine who's turn(there should be a flag,1=my turn and 0=opp's turn,right?).Any response will be welcomed and appreciated:)!

My C/C++ code are as follows:

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

enum pieces{    
PAWN_BLACK = 0,
ROOK_BLACK = 1,
BISHOP_BLACK = 2,
SILVER_GERERAL_BLACK = 3,
GOLD_GENERAL_BLACK = 4,
KING_BLACK = 5,

PAWN_WHITE = 6,
ROOK_WHITE = 7,
BISHOP_WHITE = 8,
SILVER_GERERAL_WHITE  = 9,
GOLD_GENERAL_WHITE = 10,
KING_WHITE =11,

Promoted_Rook_White=12,
Promoted_Bishop_White=13,
Promoted_Silver_General_White=14,
Promoted_Pawn_White=15,

Promoted_Rook_Black=16,
Promoted_Bishop_Black=17,
Promoted_Silver_General_Black=18,
Promoted_Pawn_Black=19,};


struct Bitboard{
int32_t p[20]={
    0x0000020,
    0x0000010,
    0x0000008,
    0x0000004,
    0x0000002,
    0x0000001,

    0x0080000,
    0x0100000,
    0x0200000,
    0x0400000,
    0x0800000,
    0x1000000,

    0x0000000,
    0x0000000,
    0x0000000,
    0x0000000,

    0x0000000,
    0x0000000,
    0x0000000,
    0x0000000,
};
bool isTerminal;};



static const uint32_t mask[20][25] ={   /*PAWN_BLACK_move_mask*/
0x0000020, 0x0000040, 0x0000080, 0x0000100, 0x0000200,
0x0000400, 0x0000800, 0x0001000, 0x0002000, 0x0004000,
0x0008000, 0x0010000, 0x0020000, 0x0040000, 0x0080000,
0x0100000, 0x0200000, 0x0400000, 0x0800000, 0x1000000,
0x0000000, 0x0000000, 0x0000000, 0x0000000, 0x0000000,
/*ROOK_BLACK_move_mask*/
0x010843E, 0x021085D, 0x042109B, 0x0842117, 0x108420F,
0x01087C1, 0x0210BA2, 0x0421364, 0x08822E8, 0x10841F0,
0x010F821, 0x0217442, 0x0426C84, 0x0845D08, 0x1083E10,
0x01F0421, 0x02E8842, 0x04D9084, 0x08BA108, 0x107C210,
0x1E08421, 0x1D10842, 0x1B21084, 0x1742108, 0x0F84210,
/*BISHOP_BLACK_move_mask*/
0x1041040, 0x0082080, 0x0004540, 0x0008A80, 0x0111100,
0x0820802, 0x1041405, 0x008A80A, 0x0115014, 0x0222008,
0x0410044, 0x08280A8, 0x1150151, 0x02A0282, 0x0440104,
0x0200888, 0x0501510, 0x0A02A20, 0x1405041, 0x0802082,
0x0011110, 0x002A200, 0x0054400, 0x00A0820, 0x0041041,
/*SILVER_GERERAL_BLACK_move_mask*/
0x0000060, 0x00000E0, 0x00001C0, 0x0000380, 0x0000300,
0x0000C02, 0x0001C05, 0x000380A, 0x0007014, 0x0006008,
0x0018040, 0x003804A, 0x0070140, 0x00E0280, 0x00C0100,
0x0300800, 0x0701400, 0x0E02800, 0x1C05000, 0x1802000,
0x0010000, 0x0028000, 0x0050000, 0x00A0000, 0x0040000,
/*GOLD_GERERAL_BLACK_move_mask*/
0x0000062, 0x00000E5, 0x00001CA, 0x0000394, 0x0000308,
0x0000C41, 0x0001CA2, 0x0003944, 0x0007288, 0x0006110,
0x0018820, 0x0039440, 0x0072880, 0x00E5100, 0x00C2200,
0x0310400, 0x0728800, 0x0E51000, 0x1CA2000, 0x1844000,
0x0208000, 0x0510000, 0x0A20000, 0x1440000, 0x0880000,
/*KING_BLACK_move_mask*/
0x0000062, 0x00000E5, 0x00001CA, 0x0000394, 0x0000308,
0x0000C43, 0x0001CA7, 0x000394E, 0x000729C, 0x0006118,
0x0018860, 0x00394E0, 0x00729C0, 0x00E5380, 0x00C2200,
0x0310400, 0x0728800, 0x0E51000, 0x1CA2000, 0x1846000,
0x0218000, 0x0538000, 0x0A70000, 0x14E0000, 0x08C0000,
/*PAWN_WHITE_move_mask*/
0x0000000, 0x0000000, 0x0000000, 0x0000000, 0x0000000,
0x0000001, 0x0000002, 0x0000004, 0x0000008, 0x0000010,
0x0000020, 0x0000040, 0x0000080, 0x0000100, 0x0000200,
0x0000400, 0x0000800, 0x0001000, 0x0002000, 0x0004000,
0x0008000, 0x0010000, 0x0020000, 0x0040000, 0x0100000,
/*ROOK_WHITE_move_mask*/
0x010843E, 0x021085D, 0x042109B, 0x0842117, 0x108420F,
0x01087C1, 0x0210BA2, 0x0421364, 0x08822E8, 0x10841F0,
0x010F821, 0x0217442, 0x0426C84, 0x0845D08, 0x1083E10,
0x01F0421, 0x02E8842, 0x04D9084, 0x08BA108, 0x107C210,
0x1E08421, 0x1D10842, 0x1B21084, 0x1742108, 0x0F84210,
/*BISHOP_WHITE_move_mask*/
0x1041040, 0x0082080, 0x0004540, 0x0008A80, 0x0111100,
0x0820802, 0x1041405, 0x008A80A, 0x0115014, 0x0222008,
0x0410044, 0x08280A8, 0x1150151, 0x02A0282, 0x0440104,
0x0200888, 0x0501510, 0x0A02A20, 0x1405041, 0x0802082,
0x0011110, 0x002A200, 0x0054400, 0x00A0820, 0x0041041,
/*SILVER_GERERAL_WHITE_move_mask*/
0x0000040, 0x00000A0, 0x0000140, 0x0000280, 0x0000200,
0x0000803, 0x0001407, 0x000280E, 0x000501C, 0x0002018,
0x0010060, 0x00280E0, 0x00501C0, 0x00A0380, 0x0040300,
0x0200C00, 0x0501C00, 0x0A03800, 0x1407000, 0x0806000,
0x0018000, 0x0038000, 0x0070000, 0x00E0000, 0x00C0000,
/*GOLD_GENERAL_WHITE_move_mask*/
0x0000022, 0x0000045, 0x000008A, 0x0000114, 0x0000208,
0x0000443, 0x00008A7, 0x000114E, 0x000229C, 0x0004118,
0x0008860, 0x00114E0, 0x00229C0, 0x0045380, 0x0082300,
0x0110C00, 0x0229C00, 0x0453800, 0x08A7000, 0x1046000,
0x0218000, 0x0538000, 0x0A70000, 0x14E0000, 0x08C0000,
/*KING_WHITE_move_mask*/
0x0000062, 0x00000E5, 0x00001CA, 0x0000394, 0x0000308,
0x0000C43, 0x0001CA7, 0x000394E, 0x000729C, 0x0006118,
0x0018860, 0x00394E0, 0x00729C0, 0x00E5380, 0x00C2200,
0x0310400, 0x0728800, 0x0E51000, 0x1CA2000, 0x1846000,
0x0218000, 0x0538000, 0x0A70000, 0x14E0000, 0x08C0000,

/*Promoted_Rook_White_move_mask*//*龍王*/
0x010847F, 0x02108FF, 0x04211DF, 0x084239F, 0x108431C,
0x0108FE3, 0x0211FE7, 0x0423BEE, 0x08473FC, 0x10863F8,
0x011FC61, 0x023FCE2, 0x0477DC4, 0x08E7F88, 0x10C7F10,
0x03F8C21, 0x07F9C42, 0x0EFB884, 0x1CFF108, 0x18FE210,
0x1F18421, 0x1F38842, 0x1F71084, 0x1FE2108, 0x1FC4210,
/*Promoted_Bishop_White_move_mask*//*龍馬*/
0x1041062, 0x00820E5, 0x00045CA, 0x0008B94, 0x0111308,
0X0820C43, 0X1041CA7, 0X008B94E, 0X011729C, 0x0226118,
0x0418864, 0x08394E8, 0x11729D1, 0x02E5382, 0x04C2304,
0x0310C88, 0x0729D10, 0x0E52A20, 0x1CA7041, 0x1846082,
0x0219110, 0x053A200, 0x0A74400, 0x14E0820, 0x08C1041,
/*Promoted_Silver_General_White_move_mask*//*成金*/
0x0000022, 0x0000045, 0x000008A, 0x0000114, 0x0000208,
0x0000443, 0x00008A7, 0x000114E, 0x000229C, 0x0226118,
0x0008860, 0x00114E0, 0x00229C0, 0x0045380, 0x0082300,
0x0110C00, 0x0229C00, 0x0453800, 0x08A7000, 0x1046000,
0x0218000, 0x0538000, 0x0A70000, 0x14E0000, 0x08C0000,
/*Promoted_Pawn_White_move_mask*//*金*/
0x0000022, 0x0000045, 0x000008A, 0x0000114, 0x0000208,
0x0000443, 0x00008A7, 0x000114E, 0x000229C, 0x0004118,
0x0008860, 0x00114E0, 0x00229C0, 0x0045380, 0x0082300,
0x0110C00, 0x0229C00, 0x0453800, 0x08A7000, 0x1046000,
0x0218000, 0x0538000, 0x0A70000, 0x14E0000, 0x08C0000,
/*Promoted_Rook_Black_move_mask*//*龍王*/
0x010847F, 0x02108FF, 0x04211DF, 0x084239F, 0x108431C,
0x0108FE3, 0x0211FE7, 0x0423BEE, 0x08473FC, 0x10863F8,
0x011FC61, 0x023FCE2, 0x0477DC4, 0x08E7F88, 0x10C7F10,
0x03F8C21, 0x07F9C42, 0x0EFB884, 0x1CFF108, 0x18FE210,
0x1F18421, 0x1F38842, 0x1F71084, 0x1FE2108, 0x1FC4210,
/*Promoted_Bishop_Black_move_mask*//*龍馬*/
0x1041062, 0x00820E5, 0x00045CA, 0x0008B94, 0x0111308,
0X0820C43, 0X1041CA7, 0X008B94E, 0X011729C, 0x0226118,
0x0418864, 0x08394E8, 0x11729D1, 0x02E5382, 0x04C2304,
0x0310C88, 0x0729D10, 0x0E52A20, 0x1CA7041, 0x1846082,
0x0219110, 0x053A200, 0x0A74400, 0x14E0820, 0x08C1041,
/*Promoted_Silver_General_Black_move_mask*//*成金*/
0x0000062, 0x00000E5, 0x00001CA, 0x0000394, 0x0000308,
0x0000C41, 0x0001CA2, 0x0003944, 0x0007288, 0x0006110,
0x0018820, 0x0039440, 0x0072880, 0x00E5100, 0x00C2200,
0x0310400, 0x0728800, 0x0E51000, 0x1CA2000, 0x1844000,
0x0208000, 0x0510000, 0x0A20000, 0x1440000, 0x0880000,
/*Promoted_Pawn_Black_move_mask*//*金*/
0x0000062, 0x00000E5, 0x00001CA, 0x0000394, 0x0000308,
0x0000C41, 0x0001CA2, 0x0003944, 0x0007288, 0x0006110,
0x0018820, 0x0039440, 0x0072880, 0x00E5100, 0x00C2200,
0x0310400, 0x0728800, 0x0E51000, 0x1CA2000, 0x1844000,
0x0208000, 0x0510000, 0x0A20000, 0x1440000, 0x0880000,};

int position(uint32_t piece)

if(piece == 0x0000001)return 0;
else if(piece == 0x0000002)return 1;
else if(piece == 0x0000004)return 2;
else if(piece == 0x0000008)return 3;
else if(piece == 0x0000010)return 4;
else if(piece == 0x0000020)return 5;
else if(piece == 0x0000040)return 6;
else if(piece == 0x0000080)return 7;
else if(piece == 0x0000100)return 8;
else if(piece == 0x0000200)return 9;
else if(piece == 0x0000400)return 10;
else if(piece == 0x0000800)return 11;
else if(piece == 0x0001000)return 12;
else if(piece == 0x0002000)return 13;
else if(piece == 0x0004000)return 14;
else if(piece == 0x0008000)return 15;
else if(piece == 0x0010000)return 16;
else if(piece == 0x0020000)return 17;
else if(piece == 0x0040000)return 18;
else if(piece == 0x0080000)return 19;
else if(piece == 0x0100000)return 20;
else if(piece == 0x0200000)return 21;
else if(piece == 0x0400000)return 22;
else if(piece == 0x0800000)return 23;
else if(piece == 0x1000000)return 24;}
struct move{
int piece;
uint32_t pos;};

move bestmove;

class Board{
Board *playMove;
move nextMoves;};

struct Effects{
int King=30000;
int Promoted_bishop=84;
int Promoted_rook=80;
int rook=60;
int bishop=54;
int Gold_gereral=74;
int Sliver_general=64;
int pawn=50;};

int AB(Bitboard board, int alpha, int beta, int depth){
if(board.isTerminal)return 0; // Win (super big) or Loser(super small)
if(depth <= 0)return 0;// using board to compute the score
int value;
for(int i = 0; i < 12; i++)
{
    uint32_t mov = mask[i][position(board.p[i])];
    while(mov)
    {
        uint32_t pos = mov & -mov;
        mov &= (mov-1);
        Bitboard child = board;
        //one move
        //black <--> white
        value = -AB(child, -beta, -alpha, depth-1);
        if(value >= beta) return value;
        if(value > alpha) alpha = value;
    }
}
return alpha;}

int ABmove(Bitboard board, int alpha, int beta, int depth){

if(board.isTerminal)return 0; // Win (super big) or Loser(super small)
if(depth <= 0)return 0;// using board to compute the score
int value;
for(int i = 0; i < 12; i++)
{
    uint32_t mov = mask[i][position(board.p[i])];
    while(mov)
    {
        uint32_t pos = mov & -mov;
        mov &= (mov-1);
        Bitboard child = board;
        //one move
        //black <--> white
        value = -AB(child, -beta, -alpha, depth-1);
        if(value >= beta) return value;
        if(value > alpha)
        {
            alpha = value;
            bestmove.piece = i;
            bestmove.pos = pos;
        }
    }
}
return alpha;}

int main(){
Bitboard b[5][5];

/**what should I call?*/

return 0;}

Is it safe to never retrieve the result of a std::future from a std::packaged_task?

Is it safe to create a std::future from a std::packaged_task, which executes on a separate thread, but not always retrieve its result?

#include <future>
#include <thread>

class Result {
  Result() {}
  ~Result() {}
};

void foo() {
  std::packaged_task<Result()> task(..);
  auto future = task.get_future();
  std::thread thread(std::move(task), ...);
  thread.detach();
  if (future.wait_for(std::chrono::milliseconds(timeout_ms)) == std::future_status::ready) {
    auto result = future.get();  <--- Task didn't take too long, retrieve future result
    ...
  }
}  <--- Task is taking too long, just abort and never call future.get()

It seems to work on Clang / libc++: ~Result() is called on the returned result by the std::packaged_task wether or not get() is eventually called on the std::future, but since I couldn't find anything in the C++ docs about this usage pattern, I'd like to make sure it's officially supported.

Empty places at the end of the arrays c ++ [on hold]

enter code here//handlerfunction void HousingRegister::printBythePrice(string *array, float max)const { int index = 0; for (int i = 0; i getRent() <= max) { array[index] = housing[i]->toString(); index++; } } }//mainfunction void printBythePrice(const HousingRegister &house){

float max;
string *arr = new string[house.getnrOfHouses()];
cout << "Enter the price: ";
cin >> max;
house.printBythePrice(arr, max); 
for (int i = 0; i < house.getnrOfHouses(); i++)
{
    cout << arr[i];
}
delete[] arr; //Array delete

}

Why aren't template expressions simplified internally?

The following example doesn't work:

#include <iostream>

template <int index, template <typename> class Head,
        template <typename> class... Tail>
struct TemplateTupleElement {
    template <typename T>
    using Type =
            typename TemplateTupleElement<index - 1, Tail...>::template Type<T>;
};

template <template <typename> class Head, template <typename> class... Tail>
struct TemplateTupleElement<0, Head, Tail...> {
    template <typename T>
    using Type = Head<T>;
};

template <typename T>
class Dummy {
};

template <template <typename> class T>
class TemplateDummy {
public:
    static void print() {
        std::cout << "Template" << std::endl;
    }
};

template <>
class TemplateDummy<Dummy> {
public:
    static void print() {
        std::cout << "Specialization" << std::endl;
    }
};

int main(int argc, char* argv[]) {
    TemplateDummy<TemplateTupleElement<0, Dummy, Dummy>::Type>::print();
    TemplateDummy<TemplateTupleElement<1, Dummy, Dummy>::Type>::print();

    return 0;
}

The output is:

Specialization
Template

but I expected it to be:

Specialization
Specialization

I can understand that internally the compiler (g++ (Ubuntu 5.3.0-3ubuntu1~14.04) 5.3.0 20151204) represents the two template expressions differently:

  1. Dummy
  2. TemplateTupleElement<1, Dummy, Dummy>::Type

Why isn't the second expression "simplified" into the first expression?

Why does this class member variable not change when calling a CUDA kernel function?

In a simple test CUDA application, I have a pointer pointing to a list of class instances, and I copy that data to the GPU. I then run a kernel function many times. The kernel function then calls a __device__ member function for each class instance which increments a variable, profitLoss.

For some reason, profitLoss is not incrementing. Here is the code I have:

#include <stdio.h>
#include <stdlib.h>

#define N 200000

class Strategy {
    private:
        double profitLoss;

    public:
        __device__ __host__ Strategy() {
            this->profitLoss = 0;
        }
        __device__ __host__ void backtest() {
            this->profitLoss++;
        }
        __device__ __host__ double getProfitLoss() {
            return this->profitLoss;
        }
};

__global__ void backtestStrategies(Strategy *strategies) {
    int i = blockIdx.x * blockDim.x + threadIdx.x;

    if (i < N) {
        strategies[i].backtest();
    }
}

int main() {
    int threadsPerBlock = 1024;
    int blockCount = 32;

    Strategy *devStrategies;
    Strategy *strategies = (Strategy*)malloc(N * sizeof(Strategy));
    double *data = (double*)malloc(1000 * sizeof(double));
    double *devData;
    int i = 0;

    cudaSetDevice(0);

    // Allocate memory for strategies on the GPU.
    cudaMalloc((void**)&devStrategies, N * sizeof(Strategy));
    cudaMalloc((void**)&devData, 1000 * sizeof(double));

    // Initialize strategies on host.
    for (i=0; i<N; i++) {
        strategies[i] = Strategy();
    }

    // Copy strategies from host to GPU.
    cudaMemcpy(devStrategies, strategies, N * sizeof(Strategy), cudaMemcpyHostToDevice);

    for (i=0; i<363598; i++) {
        backtestStrategies<<<blockCount, threadsPerBlock>>>(devStrategies);
    }

    // Copy strategies from the GPU.
    cudaMemcpy(strategies, devStrategies, N * sizeof(Strategy), cudaMemcpyDeviceToHost);
    cudaMemcpy(data, devData, 1000 * sizeof(double), cudaMemcpyDeviceToHost);

    // Display results.
    for (i=0; i<N; i++) {
        printf("%f\n", strategies[i].getProfitLoss());
    }

    // Free memory for the strategies on the GPU.
    cudaFree(devStrategies);

    return 0;
}

The output is as follows:

0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
...

I would expect it to be:

363597.000000
363597.000000
363597.000000
363597.000000
363597.000000
363597.000000
363597.000000
363597.000000
...

I believe profitLoss is not incrementing due to the way I have initialized the objects (automatic storage duration), and I'm not sure of a better way to instantiate these objects and cudaMemcpy them over to the GPU:

strategies[i] = Strategy();

Can anyone offer any suggestions on how to fix this issue or what might be the cause? Thank you in advance!

I am learning programming, I came across Look and Say sequence.I tried to code it in c++

Can you please suggest how I could possibly reduce the complexity of this code.Here is the code I wrote in c++.There might be an algorithm for this problem, but I want to improve my coding skills.Thanks.
Eg:1, 11, 21, 1211, 111221, ...

1 is read off as "one 1" or 11.

11 is read off as "two 1s" or 21.

21 is read off as "one 2, then one 1" or 1211

string countAndSay(int n){
    if(n==1)
    return "1";
    int j;
    string s="1";
    string temp="";
    unordered_map<char,int> dict;
    for(int i=1;i<n;i++){
        for(j=0;j<s.length();++j){

            if(dict.find(s[j])==dict.end() && j==0)
                dict[s[j]]=1;    

            else if(dict.find(s[j])==dict.end()){
                temp+=to_string(dict[s[j-1]]);
                temp+=s[j-1];
                dict.clear();
                dict[s[j]]=1;
            }    
            else
                dict[s[j]]+=1;
        }

            temp+=to_string(dict[s[j-1]]);
            temp+=s[j-1];
            dict.clear();
            s=temp;
            temp="";
    }

    return s;
} 

In this example why do I need CRTP?

See Object counter example here: Why it just does not inherit from non-template class counter. Why counter should be template?

template <typename T>
struct counter

alias for multi parameter function template

I am trying to create a template for a multi-parameter function, and then an alias for a particular instantiation. From this really good post:

C++11: How to alias a function?

I found example code that works for a single function parameter and single template parameter:

#include <iostream>
namespace Bar
{
   void test()
   {
      std::cout << "Test\n";
   }

   template<typename T>
   void test2(T const& a)
   {
      std::cout << "Test: " << a << std::endl;
   }
}

void (&alias)()        = Bar::test;
void (&a2)(int const&) = Bar::test2<int>;

int main()
{
    Bar::test();
    alias();
    a2(3);
}

When I try to expand to two function parameters as such:

void noBarTest(T const& a, T const& b)
{
    std::cout << "noBarTest: " << a << std::endl;
}

void(&hh)(int const&, int const&) = noBarTest<int, int>;

I get these errors in Visual Studio:

error C2440: 'initializing' : cannot convert from 'void (__cdecl *)(const T &,const T &)' to 'void (__cdecl &)(const int &,const int &)'

IntelliSense: a reference of type "void (&)(const int &, const int &)" (not const-qualified) cannot be initialized with a value of type ""

I thought I followed the pattern exactly in expanding to 2 arguments.
What's the proper syntax for this?

How to debug an SSL connect error using libcurl in C++ (vs2013)

I recently went about compiling libcurl for use with Vs2013, which turned out to fairly straight forward thanks to some very useful help here on stackoverflow. After some cajoling and more online help, I've even managed to get curl to play nice inside a unique_ptr.

Standard HTTP and HTTPS transactions using curl work fine with google.com. However, a particular site using https (www.slayradio.org) unfortunately results in an 'SSL connect error'.

I have no problem connecting to the domain via https using curl in PHP. But I need it to work in C++ as well.

It seems that CURLOPT_VERBOSE is just the ticket, but turning it on seems to have no effect what so ever. I see no additional output in either the console window, nor the internal IDE output window. I messed around with the CURLOPT_STDERR option trying to specific a concrete file it should output to for a while, until I finally discovered that via the curl FAQ that passing a FILE* pointer to the libcurl DLL (which I do) causes an access violation. I know the FAQ specifically refers to CURLOPT_WRITEDATA and CURLOPT_READDATA, not CURLOPT_STDERR, but I can't imagine the same isn't the case, here.

I've discovered the CURLOPT_ERRORBUFFER setting, which a yields a slightly more helpful output:

Unknown SSL protocol error in connection to www.slayradio.org:443

But I'm still at a loss at what's causing issues.

It'd much appreciate if anyone can tell me if I shouldn't actually be seeing more output by enabling CURLOPT_VERBOSE in the console window?

I'd also be curious to hear if someone can has run into something similar before.

If I can't get Curl to be more verbose, it seems like the only option is to make use of the CURLOPT_DEBUGFUNCTION.

How can I bind a member function to a std::function?

I want to do an array of OIS::Keys (int) and of std::function.

I have this :

struct UserCommands
{
  OIS::KeyCode key;
  std::function<bool(Worms *, const Ogre::FrameEvent& evt)> func;
};

UserInput input;

UserCommands usrCommands[] =
{
  {
    OIS::KC_A, std::bind(&input, &UserInput::selectBazooka)
  },
};

But when I try to compile this I have this compile error :

    In file included from includes/WormsApp.hh:5:0,
                     /src/main.cpp:2:
/includes/InputListener.hh:26:25: error: could not convert ‘std::bind(_Func&&, _BoundArgs&& ...) [with _Func = UserInput*; _BoundArgs = {bool (UserInput::*)(Worms*, const Ogre::FrameEvent&)}; typename std::_Bind_helper<std::__is_socketlike<_Func>::value, _Func, _BoundArgs ...>::type = std::_Bind<UserInput*(bool (UserInput::*)(Worms*, const Ogre::FrameEvent&))>](&UserInput::selectBazooka)’ from ‘std::_Bind_helper<false, UserInput*, bool (UserInput::*)(Worms*, const Ogre::FrameEvent&)>::type {aka std::_Bind<UserInput*(bool (UserInput::*)(Worms*, const Ogre::FrameEvent&))>}’ to ‘std::function<bool(Worms*, const Ogre::FrameEvent&)>’
         OIS::KC_A, std::bind(&input, &UserInput::selectBazooka)
                             ^

What have I done wrong ?

C++ import external variable into private class variable

I'm trying to get a variable declared in the main into the private variables of my class without passing it as an argument for the constructor. I need to link the interrupt controller to multiple hardware interrupts without re initializing the interrupt instance and thus overwriting it.

XScuGic InterruptInstance 

int main(){
    // Initialize interrupt by looking up config and initializing with that config
    ConfigPtr = XScuGic_LookupConfig(INTERRUPT_DEVICE_ID);
    XScuGic_CfgInitialize(&InterruptInstance, ConfigPtr, ConfigPtr->BaseAddr);

    Foo foo;
    foo.initializeSpi(deviceID,slaveMask);

    return 0;
    }

And the implementation of the class Foo:

class Foo{
private:
   XScuGic InterruptInstance // This should be linked to the one in the main
public:
   void initializeSpi(uint16_t deviceID, uint32_t slaveMask); // In here, the interrupt is linked to the SPI device
};

The deviceID and slaveMask are defined in a header which is included.

Is there some way to achieve this?

std::atof or std::stof (c++11) unable to convert properly ("1.24")

I'm a little bit frustrated after I've found this strange atof/stof behavior

double bg = std::stof("1,24");
std::cerr<<"comma: "<<bg<<std::endl;
bg = std::stof("1.24");
std::cerr<<"dot: "<<bg<<std::endl;

when I change the string format, from comma to dot, this is what happens:

comma: 1.24
dot: 1

has anyone encountered this problem? thanks

bart

Is it possible in C++ to access to global template variable throw non template function

I have template class Application

It should be something like singleton, I want to create it once, and get from other files.

//main.cpp
Application<NetworkService, User, Policy> a;
a.run();
//other files
//instead of auto a = Application::getInstance<NetworkService, User, Policy>() I want just
auto a = Application::getInstance()

Is it possible? Maybe in another form, I just don't want to use template specification to access to created early global Application object

Only Constructor is called in this assignment [duplicate]

This question already has an answer here:

Look at this code snippet:

class Bar
{
public:
    Bar() { cout << "CTOR" << endl; }
    Bar(char* str) { cout << "SECOND CTOR" << endl; };
    Bar(const Bar& copy) { cout << "COPY CTOR" << endl; }
    Bar(const Bar&& move) { cout << "MOVE CTOR" << endl; }

    Bar& operator=(const Bar& other) { cout << "ASSIGNMENT" << endl; return Bar(); }
    Bar& operator=(Bar&& other) { cout << "MOVE ASSIGNMENT" << endl; return Bar(); }
};

Bar test()
{
    return Bar();
}

This class has:

  • Default constructor
  • Second constructor taking a char*
  • Copy Constructor
  • Move Constructor
  • Assignment Operator
  • Move Assignment

Now look at this:

int main()
{   
    Bar h = test();
}

The output is just:

CTOR

Why?

I'd have expected another Constructor call for the Bar object I'm constructing in the test() function.

Also, there's no trace of any Assignment operator or Move Assignment.

I don't understand what's going on...

Ftp client in c++ using poco library

I am trying to make FTP client in c++ using POCO library. But i am getting some errors. I search internet for some tutorials but not able to find useful material. Can anyone suggest me procedures to make FTP client in c++ using POJO library.

Edge Boxes: Locating Object Proposals from Edges

I am currently working on Edge Boxes: Locating Object Proposals from Edges Matlab version, paper published by C. Lawrence Zitnick and Piotr Doll´ar. I faced alot of problem while compiling and execute edge box code in matlab i followed following instruction:

#

#

Structured Edge Detection Toolbox V3.0

Piotr Dollar (pdollar-at-gmail.com)

#

#
  1. Introduction.

Very fast edge detector (up to 60 fps depending on parameter settings) that achieves excellent accuracy. Can serve as input to any vision algorithm requiring high quality edge maps. Toolbox also includes the Edge Boxes object proposal generation method and fast superpixel code.

If you use the Structured Edge Detection Toolbox, we appreciate it if you cite an appropriate subset of the following papers:

@inproceedings{DollarICCV13edges, author = {Piotr Doll\'ar and C. Lawrence Zitnick}, title = {Structured Forests for Fast Edge Detection}, booktitle = {ICCV}, year = {2013}, }

@article{DollarARXIV14edges, author = {Piotr Doll\'ar and C. Lawrence Zitnick}, title = {Fast Edge Detection Using Structured Forests}, journal = {ArXiv}, year = {2014}, }

@inproceedings{ZitnickECCV14edgeBoxes, author = {C. Lawrence Zitnick and Piotr Doll\'ar}, title = {Edge Boxes: Locating Object Proposals from Edges}, booktitle = {ECCV}, year = {2014}, }

#
  1. License.

This code is published under the MSR-LA Full Rights License. Please read license.txt for more info.

#
  1. Installation.

a) This code is written for the Matlab interpreter (tested with versions R2013a-2013b) and requires the Matlab Image Processing Toolbox.

b) Additionally, Piotr's Matlab Toolbox (version 3.26 or later) is also required. It can be downloaded at: http://ift.tt/1sGMt2T.

c) Next, please compile mex code from within Matlab (note: win64/linux64 binaries included): mex private/edgesDetectMex.cpp -outdir private [OMPPARAMS] mex private/edgesNmsMex.cpp -outdir private [OMPPARAMS] mex private/spDetectMex.cpp -outdir private [OMPPARAMS] mex private/edgeBoxesMex.cpp -outdir private Here [OMPPARAMS] are parameters for OpenMP and are OS and compiler dependent. Windows: [OMPPARAMS] = '-DUSEOMP' 'OPTIMFLAGS="$OPTIMFLAGS' '/openmp"' Linux V1: [OMPPARAMS] = '-DUSEOMP' CFLAGS="\$CFLAGS -fopenmp" LDFLAGS="\$LDFLAGS -fopenmp"
Linux V2: [OMPPARAMS] = '-DUSEOMP' CXXFLAGS="\$CXXFLAGS -fopenmp" LDFLAGS="\$LDFLAGS -fopenmp" To compile without OpenMP simply omit [OMPPARAMS]; note that code will be single threaded in this case.

d) Add edge detection code to Matlab path (change to current directory first):

addpath(pwd); savepath;

e) Finally, optionally download the BSDS500 dataset (necessary for training/evaluation): http://ift.tt/1PbDvos After downloading BSR/ should contain BSDS500, bench, and documentation.

f) A fully trained edge model for RGB images is available as part of this release. Additional models are available online, including RGBD/D/RGB models trained on the NYU depth dataset and a larger more accurate BSDS model.

#
  1. Getting Started.

    • Make sure to carefully follow the installation instructions above.
    • Please see "edgesDemo.m", "edgeBoxesDemo" and "spDemo.m" to run demos and get basic usage information.
    • For a detailed list of functionality see "Contents.m".
#
  1. History.

Version NEW - now hosting on github (http://ift.tt/1I8WjQl) - suppress Mac warnings, added Mac binaries - edgeBoxes: added adaptive nms variant described in arXiv15 paper

Version 3.01 (09/08/2014) - spAffinities: minor fix (memory initialization) - edgesDetect: minor fix (multiscale / multiple output case)

Version 3.0 (07/23/2014) - added Edge Boxes code corresponding to ECCV paper - added Sticky Superpixels code - edge detection code unchanged

Version 2.0 (06/20/2014) - second version corresponding to arXiv paper - added sharpening option - added evaluation and visualization code - added NYUD demo and sweep support - various tweaks/improvements/optimizations

Version 1.0 (11/12/2013) - initial version corresponding to ICCV paper

#

and here are some errors

edgeBoxesDemo Undefined function or variable 'getPrmDflt'.

Error in edgeBoxes (line 78) o=getPrmDflt(varargin,dfs,1);

Error in edgeBoxesDemo (line 8) opts = edgeBoxes;

syntax template specialization c++

I have two classes: one "student" the second "employee" i have to write template class and in this class to write a function that getting the two > class. i need to activate a specific method of the student class and the employee class i know that

i need to use specialization, how i do it?

>     template<> void print_max<Student>(Student * s, int sizes)  {       
         s->
>     }

Access template's arguments with partial type knowledge

I have some code with deep C++ 11 variadic template's magic usage. I am using specialized classes to identify parts of template tree, which I am naming "tags". Each tag has unique number identifier. I need to find a way how to access tag's identifiers

Here is some small example:

#include <string>
#include <iostream>

template <unsigned long ID, typename PARAM>
class tag_
{
    //getter for ID. Better to exclude it. If possible - move to external helper
    constexpr static unsigned long get_id() {return ID;}
    //PARAM is used in some functions of this class
};

//tag's declarations for future usage
template<typename PARAM>
using tag1 = tag_<1UL, PARAM>;
template<typename PARAM>
using tag2 = tag_<2UL, PARAM>;
template<typename PARAM>
using tag3 = tag_<3UL, PARAM>;

//helper class that can iterate TAGS
template <template<typename> class... TAGS>
struct helper
{};
template <template<typename> class TAG>
struct helper<TAG>
{
    static void print_tag(std::ostream& out)
    {
        out << std::string("Tag");
        out << TAG::get_id();  // Here I can't call: error: 'template<class> class TAG' used without template parameters
    }
};
template <template<typename> class TAG, template<typename> class... TAGS>
struct helper<TAG, TAGS...>
{
    static void print_tag(std::ostream& out)
    {
        out << std::string("Tag");
        out << TAG::get_id();  // Here I can't call: error: 'template<class> class TAG' used without template parameters
        out << std::string(", ");
        helper<TAGS...>::print_tag(out);
    }
};

//this class uses tags for some processing
template <template<typename> class... TAG_LIST>
class tagged
{
public:
    void test1(std::ostream& out)
    {
        out << std::string("This function works good");
    }
    void test2(std::ostream& out)
    {
        helper<TAG_LIST...>::print_tag(out);
    }
};

// this class is re-defined for some types of T
template<typename T, typename PARAM>
class usage
{
public:
    void test1(std::ostream& out)
    {
        details.test1(out);
    }
    void test2(std::ostream& out)
    {
        details.test2(out);
    }

    T details;
    PARAM params;
};

//endpoint
struct finish{};

//definition for future usage
template<template<typename> class T1, template<typename> class T2, template<typename> class T3, typename PARAM>
using multitag = usage<tagged<T1, T2, T3>, PARAM>;

int main(int argc, const char* argv[])
{
    // this way I am construction my objects tree
    multitag<tag1, tag2, tag3, tag1<tag2<tag3<finish>>>> tmp;
    tmp.test1(std::cout); // ok
    std::cout << std::endl;
    tmp.test2(std::cout);  //compile error. I want to get "Tag1, Tag2, Tag3" printed
    std::cout << std::endl;
}

Error using Paho C++ libraries

Good morning,

I'm having some problems while using Paho C++ library. I installed Paho C libraries first following the steps:

git clone http://ift.tt/1TQrdkc
cd org.eclipse.paho.mqtt.c.git
make
sudo make install

After that I did the same with the C++ library:

git clone http://ift.tt/1XIaFO0
cd org.eclipse.paho.mqtt.cpp.git
make

In order to try to check the library, I tried to compile the /src/samples using:

make

I got an error lmqttv3a and mqttpp libraries weren't found so I modified the make file and I got rid of this problem.

Now, while compiling this I have another new error, it seems the compiler is not getting properly the libraries. The new error is:

:~/http://ift.tt/1TQqT54 make g++ -I.. -I/usr/local/lib/src -D_NDEBUG -Wall -std=c++0x -O2 -o asy_publish.o async_publish.cpp -L../lib -L/usr/local/lib/src/linux_ia64 /tmp/cc4UUHz6.o: In function std::_Sp_counted_ptr_inplace<mqtt::message, std::allocator<mqtt::message>, (__gnu_cxx::_Lock_policy)2>::_M_dispose()': async_publish.cpp:(.text._ZNSt23_Sp_counted_ptr_inplaceIN4mqtt7messageESaIS1_ELN9__gnu_cxx12_Lock_policyE2EE10_M_disposeEv[_ZNSt23_Sp_counted_ptr_inplaceIN4mqtt7messageESaIS1_ELN9__gnu_cxx12_Lock_policyE2EE10_M_disposeEv]+0x5): undefined reference tomqtt::message::~message()' /tmp/cc4UUHz6.o: In function _ZNSt12__shared_ptrIN4mqtt7messageELN9__gnu_cxx12_Lock_policyE2EEC1ISaIS1_EJRPKcEEESt19_Sp_make_shared_tagRKT_DpOT0_': async_publish.cpp:(.text._ZNSt12__shared_ptrIN4mqtt7messageELN9__gnu_cxx12_Lock_policyE2EEC2ISaIS1_EIRPKcEEESt19_Sp_make_shared_tagRKT_DpOT0_[_ZNSt12__shared_ptrIN4mqtt7messageELN9__gnu_cxx12_Lock_policyE2EEC5ISaIS1_EIRPKcEEESt19_Sp_make_shared_tagRKT_DpOT0_]+0x5c): undefined reference tomqtt::message::message(std::string const&)' /tmp/cc4UUHz6.o: In function main': async_publish.cpp:(.text.startup+0x121): undefined reference to mqtt::async_client::async_client(std::string const&, std::string const&)' async_publish.cpp:(.text.startup+0x13f): undefined reference to mqtt::async_client::set_callback(mqtt::callback&)' async_publish.cpp:(.text.startup+0x152): undefined reference to mqtt::async_client::connect()' async_publish.cpp:(.text.startup+0x223): undefined reference to mqtt::async_client::publish(std::string const&, std::shared_ptr<mqtt::message>)' async_publish.cpp:(.text.startup+0x2c5): undefined reference to mqtt::async_client::publish(std::string const&, void const*, unsigned long, int, bool)' async_publish.cpp:(.text.startup+0x3ea): undefined reference to mqtt::async_client::publish(std::string const&, std::shared_ptr<mqtt::message>, void*, mqtt::iaction_listener&)' async_publish.cpp:(.text.startup+0x556): undefined reference to mqtt::async_client::publish(std::string const&, std::shared_ptr, void*, mqtt::iaction_listener&)' async_publish.cpp:(.text.startup+0x5d3): undefined reference to mqtt::async_client::get_pending_delivery_tokens() const' async_publish.cpp:(.text.startup+0x6e8): undefined reference to mqtt::async_client::~async_client()' async_publish.cpp:(.text.startup+0x713): undefined reference to `mqtt::async_client::~async_client()' collect2: error: ld returned 1 exit status make: *** [async_publish] Error 1

Can anyone help me?

Thank you very much.

dimanche 29 mai 2016

Converting Java State Machine Example to C++, Stuck on last hurdle

Background

I'm getting back into C++ after a bit of a Haitus. I never was fantastic at C or C++, but I considered myself to have a bit of a working knowledge.

I set off with a simple goal. Convert a Java state-machine example to C++ I Think the problem is in passing a new State<CeilingFanPullChain>, I've added empty stub constructors to the classes that inherit from my template interface (used to get around dependency issue that should probably be solved by altering the design).

As a requirement from myself to myself, I don't want to use pre-processor magic, which is what a lot of online examples seem to use. I also do not want to use a switch statement. I'd like to make this as Object-Oriented as possible.

#include <iostream>
#include <string>

// The CeilingFanPullChain class is now a wrapper
// that delegates to its m_current_state reference.
// Each clause from the "before" case statement is
// now captured in a State derived class.

// For this simple domain, the State pattern is
// probably over-kill.


template <class T>
class State {
public:
    virtual void pull( T &wrapper ) = 0;
};

class CeilingFanPullChain {

private:
    State<CeilingFanPullChain>* m_current_state;

public:
    CeilingFanPullChain() {
        m_current_state = new Off();
    }
    void set_state( State<CeilingFanPullChain>* s ) {
        m_current_state = s;
    }
    void pull() {
        m_current_state->pull( *this );
    }
};

class Off: public State<CeilingFanPullChain> {
public:
    Off() {}
    void pull( CeilingFanPullChain &wrapper ) {
        wrapper.set_state( new Low() );
        std::cout << "   low speed\n";
    }
};

class Low: State<CeilingFanPullChain> {
public:
    Low() {}
    void pull( CeilingFanPullChain &wrapper ) {
        wrapper.set_state( new Medium() );
        std::cout << "   medium speed\n";
    }
};

class Medium: State<CeilingFanPullChain> {
public:
    Medium() {}
    void pull( CeilingFanPullChain &wrapper ) {
        wrapper.set_state( new High() );
        std::cout << "   high speed\n";
    }
};

class High: State<CeilingFanPullChain> {
public:
    High() {}
    void pull( CeilingFanPullChain &wrapper ) {
        wrapper.set_state( new Off() );
        std::cout << "   turning off\n";
    }
};

std::string get_line() {
    std::string line_tmp;
    std::getline(std::cin, line_tmp);
    return line_tmp;
}

int main() {
    CeilingFanPullChain* chain = new CeilingFanPullChain();
    while (true) {
        std::cout << "Press \n";
        get_line();
        chain->pull();
    }
    return 0;
}

Error Output

ceiling-fan.cpp: In constructor ‘CeilingFanPullChain::CeilingFanPullChain()’:
ceiling-fan.cpp:26:31: error: expected type-specifier before ‘Off’
         m_current_state = new Off();
                               ^
ceiling-fan.cpp: In member function ‘virtual void Off::pull(CeilingFanPullChain&)’:
ceiling-fan.cpp:40:32: error: expected type-specifier before ‘Low’
         wrapper.set_state( new Low() );
                                ^
ceiling-fan.cpp: In member function ‘virtual void Low::pull(CeilingFanPullChain&)’:
ceiling-fan.cpp:49:32: error: expected type-specifier before ‘Medium’
         wrapper.set_state( new Medium() );
                                ^
ceiling-fan.cpp: In member function ‘virtual void Medium::pull(CeilingFanPullChain&)’:
ceiling-fan.cpp:58:32: error: expected type-specifier before ‘High’
         wrapper.set_state( new High() );

C++: rvalue reference memory

Since c++ provides references to rvalues i.e. rvalue references which are mainly used to perform move semantics and other memory efficient tasks. But in the following case reference is changing the value of an literal but as we know that literals are read only so how could a reference change the value of some read only variable. Does a rvalue reference allocate it's own memory or it simply changes the value of literal?

#include <iostream>
using namespace std;

int main()
{
    int a = 5;
    int&& b = 3;
    int& c = a;
    b++;
    c++;
    cout << " Value for b " << b << " Value for c " << c << endl;
}

Secondly, when a temporary object is assigned with a reference, reference works with the data of that object. But according to the definition of temporary objects they are deleted as when the expression using them ends. How could the reference act as an alias name to that temporary object if that temporary object is out of memory?

What is the "best" way to overload arithmetic operators in modern C++?

I want to implement a kind of "number-like" mathematical objects (say, elements in a group or a ring) in C++. I'm sure that I'm not the only one dealing with this problem, so there may be abundant amount of discussions about what is the "best" way of overloading arithmetic operators. However, I couldn't find satisfactory answers (although maybe I was too lazy to googling more).

Let's say I want to overload the operator "+" for a class A. The problem is, there are too many different overloads I can think of:

  1. operator+(const A& x, const A& y)
  2. operator+(const A& x, A&& y)
  3. operator+(A&& x, const A& y)
  4. operator+(A&& x, A&& y)
  5. A::operator+=(const A& y) &
  6. A::operator+=(const A& y) &&
  7. A::operator+=(A&& y) &
  8. A::operator+=(A&& y) &&

First question. Do all of these overloads necessary to make operations on instances of A as efficient as, and as much as "being like primitive types" as possible? I think for "ordinary" cases, rvalue-qualified A::operator+= need not (or should not) be overloaded. Is it right? I think all of 1-4 are necessary. For example, for the case 3, since x is being moved, we do not need to allocate a new space to hold the return value, and we can safely reuse the allocation storage reserved for x. Is it right?

Second question. I think all of these overloads may share a lot of codes for most of this kind of cases. How can I minimize the code duplication without sacrificing performance/etc.? Is there any special techniques/idioms to do this? I prefer general and extensible methods, if exist.

What's wrong about this algorithm for solving "Help the Commander in Chief"

Well, I searched trying to find an answer for this problem : http://ift.tt/1wqje1m Actually I found some of them, but I'm still curious about this one which is wrong, Here's the code:

#include <iostream>
#include <cstdio>
#include <vector>
#include <map>

using namespace std;

using size_type = unsigned long long int;
using ushort = unsigned short;

class Node
{
public :
    void addEdge(ushort e) {_edges.push_back(e);}
    const ushort &operator[] (int n) const {return _edges[n];}
    ushort size() const {return _edges.size();}
    void clear() {_edges.clear();}
private :
    vector<ushort> _edges;
};

class Map
{
public :
    Map() : _C{0}, _B{0}, _S{0}, _T{0} {}

    Node& operator[] (const ushort i) {return _Node[i];}
    const Node& operator[] (const ushort i) const {return _Node[i];}

    friend istream &operator>> (istream &is, Map &m);

    ushort C() {return _C;}
    ushort B() {return _B;}
    ushort start() {return _S;}
    ushort end() {return _T;}
private :
    void _reset();
    Node _Node[10000];
    ushort _C, _B, _S, _T;
};

void Map::_reset()
{
    for (ushort i = 0; i < _C; i++)
        _Node[i].clear();
}

istream &operator>>(istream &is, Map &m)
{
    m._reset();
    ushort x, y;
    scanf("%hu %hu %hu %hu", &m._C, &m._B, &m._S, &m._T);
    m._S--; m._T--;
    for (ushort i = 0; i < m._B; i++)
    {
        scanf("%hu %hu", &x, &y);
        x--; y--;
        m[x].addEdge(y);
    }
    return is;
}

size_type paths(Map &m);
void count(Map &m, ushort p, map<ushort, size_type> &h);

int main()
{
    Map m;
    ushort D;
    scanf("%hu", &D);
    while (D--)
    {
        cin >> m;
        printf("%I64u\n", paths(m) % 1000000007LL);
    }
}

size_type paths(Map &m)
{
    if (m.start() == m.end()) return 1;
    map<ushort, size_type> h;
    h[m.end()] = 1;
    count(m, m.start(), h);
    return h[m.start()];
}

void count(Map &m, ushort p, map<ushort, size_type> &h)
{
    for (ushort i = 0; i < m[p].size(); i++)
    {
        if (h.find(m[p][i]) == h.end())
            count(m, m[p][i], h);
        h[p] += h[m[p][i]];
    }
}

I simply try to use memorization to count number of paths, but wherever I go, they talk about topological sort.. etc. why this code fragment is still giving a wrong answer ? why is it not sufficient ?

Thanks - Sam

Extremely slow code execution time

For any given combination 'C' as an input of size 'k'. Following code computes the index of all the subsets of 'k-1' when all the combinations are arranged in lexicographic order. Combination 'C' consists of integers in sorted order from [1 to 'n'].

The following code has snippets borrowed from link1 and also the function 'nCr'-[Couldn't post the link as I had misplace. If anyone can point please let me know I will add it]

On executing the code, it seems to be very inefficient and takes unusually long time. Any help to improve it or point out issues is highly appreciated

#include <iostream>
#include <vector>

int nCr(int n, int r) {
    //Compute the factorials
    int ans = 1;
    r = std::min(r, n - r);
    for (int j = 1; j <= r; j++, n--) {
        if (n % j == 0) {
            ans *= n / j; 
        } else if (ans % j == 0) {
            ans = (ans / j) * n;
        } else {
            ans = (ans * n) / j;
            }
        }   
    return ans;
}



std::vector<int> compute_index (int n, int k, std::vector<int>& combination) {

    std::vector<int> result;
    result.clear();

    for (int ll = 0; ll < combination.size(); ++ll) {
        int index = 0;
        int j = 0;
        if (ll == 0) index = 1;
        for (int i = 0; i != k; ++i)
        {
            int test = combination[i];
            if (test == combination[ll]) {
                test = combination[(ll+1)%combination.size()];
            }
            for (++j; j != test; ++j)
            {
                index += nCr(n - j, k - i - 1);
            }
        }

        std::cout << index + 1 << std::endl;
        result.push_back(index);
    }
    return result;
}

int main()
{
    int n = 5;
    int k = 2;

    std::vector<int> combination  = {1, 2, 3};

    auto result = compute_index(n, k, combination);

    return 0;
}

Command to compile it :

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

C++ extending lifetime of &&

In the following example:

http://ift.tt/1U60v4y

struct D{
    int i;    
    auto test2(int&& j){
        return [&](){       // captured by reference!
            cout << i*(j);
        };
    }    
};

int main()
{
    D d{10};
    {
      auto fn = d.test2(10);
      fn();                     // 1. wrong result here

      d.test2(10)();            // 2. but ok here
    }
}

Why does d.test2(10)(); work?

Should it really work, or thats just my undefined behavior equals correct result?

P.S. After reading this I see only one explanation: in (2) temporary lifetime prolongs till the end of the expression, and call happens in the same expression with && crteation; while (1) actually consists from 2 expressions:

a temporary bound to a reference parameter in a function call exists until the end of the full expression containing that function call: if the function returns a reference, which outlives the full expression, it becomes a dangling reference.

Is this the case?

A* Pathfind wrong checked tiles

I want to implement A* pathfind (C++ & Qt). this is my result: A* Pathfind by wrong checkings

as you can see, there are some wrong tiles that are checked (opened). in my image, red tiles are opened tiles and you can see there are some tiles inside the blue rectangle area that should not be checked because they are far from target. so if I want to have more than 250 pathfinder soldiers in my game, I must optimize soldiers calculations, so I want to know my bug and also some optimizing suggestions. here is my code:

struct asNode
{
        QPoint pos;
        QPoint parent;
        int g;
        int h;
        bool opened;
        bool closed;
        asNode() :
                pos(QPoint(0, 0)), parent(QPoint(-1, -1)), g(0), h(0), opened(false), closed(false)
        {}
        int F()
        {
                return g + h;
        }
        const int distance(const QPoint _Dest) const
        {
                int xd = _Dest.x() - pos.x();
                int yd = _Dest.y() - pos.y();

                // Euclidian Distance
                //int d=static_cast<int>(sqrt(xd*xd+yd*yd));

                // Manhattan distance
                int d = (abs(xd) + abs(yd))*10;
                // Chebyshev distance
                //int d=max(abs(xd), abs(yd));

                return(d);
        }
        bool hasParent()
        {
                return (parent != QPoint(-1, -1));
        }
};


class a_star
{
public:
    a_star(bool _Diagonal=false)
        {
                SetDigonal(_Diagonal);
        }
    void SetDigonal(bool _Value)
        {
                _diagnoal=_Value;
                neighborsLevels.clear();
                if(_diagnoal)
                {
                        neighborsLevels.push_back(QPoint(1,0));
                        neighborsLevels.push_back(QPoint(1,1));
                        neighborsLevels.push_back(QPoint(0,1));
                        neighborsLevels.push_back(QPoint(-1,1));
                        neighborsLevels.push_back(QPoint(-1,0));
                        neighborsLevels.push_back(QPoint(-1,-1));
                        neighborsLevels.push_back(QPoint(0,-1));
                        neighborsLevels.push_back(QPoint(1,-1));
                }
                else
                {
                        neighborsLevels.push_back(QPoint(1,0));
                        neighborsLevels.push_back(QPoint(0,1));
                        neighborsLevels.push_back(QPoint(-1,0));
                        neighborsLevels.push_back(QPoint(0,-1));
                }
        }
    std::list<QPoint> a_star_path_find(std::vector<std::vector<int> > _Grid, QPoint _StartPoint, QPoint _EndPoint)
        {
                //Grid item -1 is blocked tile,0 is movable tile
                std::list<QPoint> finalpath;
                
                const int n = _Grid.size();
                const int m = _Grid[0].size();
                asNode modelMap[n][m];
                std::list<asNode*> opened;
                auto current=&modelMap[_StartPoint.x()][_StartPoint.y()];
                current->pos=_StartPoint;
                current->g = 0;
                current->h = current->distance(QPoint(_EndPoint.x(),_EndPoint.y()));

                current->opened = true;
                opened.push_front(current);
                blueTiles.push_back(current->pos);
                while (!opened.empty())
                {
                        auto itr=opened.begin();
                        current = *(itr);
                        itr++;
                        while( itr!=opened.end())
                        {
                                if((*itr)->F()<current->F())
                                {
                                        current=*(itr);
                                }
                                itr++;
                        }
                        current->closed = true;
                        opened.remove(current);

                        if (current == &modelMap[_EndPoint.x()][_EndPoint.y()])
                        {
                                while (current->hasParent())
                                {
                                        QPoint newStep= current->pos;                                        
                                        finalpath.push_back(newStep);
                                         current = &modelMap[current->parent.x()][current->parent.y()];
                                }
                                std::reverse(finalpath.begin(), finalpath.end());
                                return finalpath;
                        }
                        for (int i = 0; i<neighborsLevels.size(); i++)
                        {
                                int newX = current->pos.x() + neighborsLevels[i].x();
                                int newY = current->pos.y() + neighborsLevels[i].y();
                                if (newX >= 0 && newX<n)
                                {
                                        if (newY >= 0 && newY<m)
                                        {
                                                if (modelMap[newX][newY].closed || _Grid[newX][newY]==-1)//Grid item -1 is blocked tile,0 is movable tile
                                                {
                                                        continue;
                                                }
                                                modelMap[newX][newY].h = modelMap[newX][newY].distance(_EndPoint);
                                                int gScore = current->g + ((newX - current->pos.x() == 0 || newY - current->pos.y() == 0) ? 10 : 14);
                                                if (!modelMap[newX][newY].opened || gScore<modelMap[newX][newY].g)
                                                {
                                                        modelMap[newX][newY].g = gScore;
                                                        modelMap[newX][newY].parent = current->pos;

                                                        if (!modelMap[newX][newY].opened)
                                                        {
                                                                modelMap[newX][newY].pos=QPoint(newX,newY);
                                                                modelMap[newX][newY].opened = true;
                                                                opened.push_front(&modelMap[newX][newY]);
                                                        }
                                                }
                                        }
                                }
                        }
                }
                return finalpath;
        }
private:
    bool _diagnoal;
    std::vector<QPoint> neighborsLevels;
};

thanks...

std::atomic

Having std::atomic<int> how can I atomically load value and reset to 0? So If I do this operation from two threads, only one receive value, another should receive 0.

How do I convert from an unsorted vector to a set?

So I'm trying to convert my vector to a set like this:

 set<int> mySet(myVector.begin(), myVector.end()); 

(My original vector is unsorted and has many duplicates)

How come when I output the contents of my set it still has duplicates and is unsorted?

This is how I output it:

 for(set<int>::iterator x = mySet.begin(); x!=mySet.end(); x++)
       {cout<<*x<<endl;}

Also I would appreciate if someone could give me a good link to find information like this because I honestly tried to find an explanation but couldn't.

unordered_map emplacement fails when switching from GCC 4.9.3 to 5.3.1 (with CUDA)

I'm using the following code (irrelevant parts removed)

template<typename Key, typename T, typename... Args>
class Foo {
    // ... etc. ...

    using grault = T* (*)(Args...);
    std::unordered_map<Key,grault> bar;

    template<typename U> static T* quux(Args... args)
    {
        return new U(std::forward<Args>(args)...);
    }

    template<typename U> baz(const Key& key) {
        emplace(key, &quux<U>);
    }
    // ... etc. ...
}

And my template arguments are: Key=std::__cxx11::string, T=ClassA, Args=<const corge &>, U=SomeSubclassOfA (you only care about they Key, really).

Now, that builds and runs fine with GCC 4.9.3 + CUDA 7.5, but fails with GCC 5.3.1 and CUDA 8.0 RC. The error message is:

/usr/include/c++/5/bits/hashtable.h(1526): error: no instance of overloaded function "std::forward" matches the argument list
            argument types are: (const std::__cxx11::string)
          detected during:
            instantiation of "std::pair<std::_Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>::iterator, __nv_bool> std::_Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>::_M_emplace(std::true_type, _Args &&) [with _Key=std::__cxx11::string, _Value= etc. etc. ... (726): here

Now, I'm guessing this is either due to the GCC version switch, or the CUDA version switch, probably the former. I vaguely remember something about an ABI change w.r.t. strings which can get you into trouble, but don't know if this has anything to do with that.

Notes:

  • Yes, this is part of a factory implementation, but the question is not about that.
  • A (possibly) similar issue was reported for Intel ICC http://ift.tt/1OW6pDF

clang osx march=native approximately 1/3rd speed of no optimisation

I have a project where speed is paramount, so was experimenting with compiler flags to try and get some free performance. I have two builds that are identical except for the additional flag march=native in build 2.

For completeness the flags are:

A) -std=c++14 -g -fno-omit-frame-pointer -O3

B) -std=c++14 -g -fno-omit-frame-pointer -O3 -march-native

Running benchmarks on these builds yields a confusing result:

A) 61s

B) 160s

What can possibly going on here?

Order of destruction and assignment

I am working on an Entity class which needs to provide access to its data members through setter methods, which check that a value is allowed before storing it (checking code not shown). The Select class is one of the types stored and it needs to do some very specific cleaning up when destroyed:

#include<memory>
#include <iostream>

class Select {
    int i, j;

    friend class Entity;

public:
    Select(int a, int b) : i{a}, j{b} { }

    ~Select() {
        cout << "destroying " << i << j << endl;
    }

protected:
    Select() { };
};

class Entity {

    Select select_;

public:
    void select_setter(const Select &select) {
        cout << "to be assigned... " << select.i << select.j << endl;
        select_ = select;
    }

    static shared_ptr<Entity> create(const Select &s) {
        auto sp = make_shared<Entity>(Entity{});
        sp->select_setter(s);
        return sp;
    }
};

This block demonstrates how I want the Entity type to be used:

int main() {
    auto sp = Entity::create({1, 1});    
    sp->select_setter({2, 2});
    sp->select_setter({3, 3});    
    cout << "the end" << endl;
    return 0;
}

Here is the output:

destroying 00
to be assigned... 11
destroying 11
to be assigned... 22
destroying 22
to be assigned... 33
destroying 33
the end
destroying 33

A) Why is e.g. Select 00 destroyed before the code reaches the =-assign statement?

B) Why is 33 destroyed twice, but 00, 11 and 22 only once?