samedi 1 août 2015

Forwarding lvalues and rvalues best practice

I have a function that constructs an object from its parameters, defined like so:

template<class T, class ... Args>
void construct(Args && ... args){
    T(std::forward<Args>(args)...);
}

I also have two helper functions that pass into construct.

tempalte<class T, class ... Args>
void add(Args && ... args){
    construct<T>(std::forward<Args>(args)...);
}

tempalte<class T>
void add(T t){
    construct<T>(std::move(t));
}

The first overload of add constructs with parameters, and the second is supposed to take in either an lvalue (in which case it should invoke the copy ctor) or an rvalue (which should invoke the move ctor). My question is, is this the best way to go about doing this? I pass by value for the second overload because I can either copy construct or move construct. I am also wondering if move construction will work correctly if I pass in an rvalue to the second overload, i.e. will the std::forward coupled with the std::move work as I expect it to.

Emscripten fatal error: string not found

I am compiling a c++ app for use on the web with emscripten. The app uses the stdlib and needs to use c++11

I can compile my code just fine with clang. Here is the makefile:

LIB := include/simulator
SIM_LIB :=  include/simulator
CLANG := clang++ -std=c++11 -stdlib=libc++ -c -g -I $(LIB)
LINK := clang++ `sdl-config --cflags --libs` -lSDL_ttf -lSDL_image -lSDL_gfx -std=c++11 -stdlib=libc++ -v -g -I $(LIB)
SRC := src
BIN := bin
TEST := tests

simulatormake: main.o sim.o world.o robot.o spiking_nnet.o distance_sensor.o garden.o
    $(LINK) -o run sim.o world.o robot.o spiking_nnet.o distance_sensor.o garden.o $(SRC)/main.cpp


sim.o: $(SRC)/sim.cpp $(SIM_LIB)/sim.h $(SIM_LIB)/drawable.h $(SIM_LIB)/world.h
    $(CLANG) $(SRC)/sim.cpp 

robot.o: $(SRC)/robot.cpp $(SIM_LIB)/robot.h $(SIM_LIB)/point.h $(SIM_LIB)/drawable.h $(SIM_LIB)/modulo.h $(SIM_LIB)/distance_sensor.h $(SIM_LIB)/agent.h $(SIM_LIB)/world.h $(SIM_LIB)/spiking_nnet.h
    $(CLANG) $(SRC)/robot.cpp

garden.o: $(SRC)/garden.cpp $(SIM_LIB)/garden.h $(SIM_LIB)/point.h $(SIM_LIB)/drawable.h
    $(CLANG) $(SRC)/garden.cpp

world.o: $(SRC)/world.cpp $(SIM_LIB)/world.h $(SIM_LIB)/robot.h $(SIM_LIB)/garden.h $(SIM_LIB)/point.h $(SIM_LIB)/drawable.h
    $(CLANG) $(SRC)/world.cpp

spiking_nnet.o: $(SRC)/spiking_nnet.cpp $(SIM_LIB)/spiking_nnet.h
    $(CLANG) $(SRC)/spiking_nnet.cpp

distance_sensor.o: $(SRC)/distance_sensor.cpp $(SIM_LIB)/distance_sensor.h $(SIM_LIB)/modulo.h $(SIM_LIB)/drawable.h $(SIM_LIB)/agent.h
    $(CLANG) $(SRC)/distance_sensor.cpp

agent.h: drawable.h

drawable.h: point.h

robot.h: point.h drawable.h

point.h: 

test_sim: sim.o world.o distance_sensor.o robot.o spiking_nnet.o garden.o
    $(LINK) -o $(BIN)/test_sim sim.o world.o distance_sensor.o spiking_nnet.o robot.o garden.o $(TEST)/test_sim.cpp
    gdb bin/test_sim

test_robot: robot.o sim.o world.o distance_sensor.o garden.o spiking_nnet.o
    $(LINK) -o $(BIN)/test_robot robot.o world.o distance_sensor.o garden.o spiking_nnet.o $(TEST)/test_robot.cpp sim.o
    gdb bin/test_robot

test_garden: garden.o
    $(LINK) -o $(BIN)/test_garden garden.o $(TEST)/test_garden.cpp
    gdb bin/test_garden

test_world: robot.o world.o sim.o garden.o distance_sensor.o spiking_nnet.o
    $(LINK) -o $(BIN)/test_world world.o robot.o sim.o garden.o distance_sensor.o spiking_nnet.o  $(TEST)/test_world.cpp
    gdb bin/test_world

test_spiking_nnet: spiking_nnet.o sim.o
    $(LINK) -o $(BIN)/test_spiking_nnet $(TEST)/test_spiking_nnet.cpp spiking_nnet.o sim.o  
    gdb bin/test_spiking_nnet

test_distance_sensor: distance_sensor.o robot.o garden.o
    $(LINK) -o $(BIN)/test_distance_sensor $(TEST)/test_distance_sensor.cpp distance_sensor.o  robot.o garden.o
    gdb bin/test_distance_sensor

clean:
    rm *.o

When I run emmake make I get the following error:

include/simulator/sim.h:5:10: fatal error: 'string' file not found
#include <string>
         ^
1 error generated.
make: *** [simulatormake] Error 1

C++11 std::function const overload ambiguity

I'm having a problem with a part of a larger program where something that I'd say is not ambiguous is considered ambiguous by both g++ and clang++

#include <functional>
#include <string>

struct Foo {
    Foo(int) {}
    Foo(std::string) {}
    operator int () const { return 42; }
    operator std::string () const { return ""; }

    void foo(std::function<void(Foo&, int)>f);
    void foo(std::function<void(const Foo&, int)>f) const; // xxx

    void foo(std::function<void(const std::string&, Foo&)>f);
    void foo(std::function<void(const std::string&, const Foo&)>f) const;

    void bar() const {
        this->foo([](const Foo&, int){}); // xxx
    }
};

I'd expect the invocation of ::foo made in bar to be unambiguously resolved to the const version marked with xxx, while instead both compilers complain that the overload resolution is ambiguous:

g++ -std=c++11 -c -Wall amb.cpp 
amb.cpp: In member function ‘void Foo::bar() const’:
amb.cpp:18:40: error: call of overloaded ‘foo(Foo::bar() const::<lambda(const Foo&, int)>)’ is ambiguous
         this->foo([](const Foo&, int){});
                                        ^
amb.cpp:12:10: note: candidate: void Foo::foo(std::function<void(const Foo&, int)>) const
     void foo(std::function<void(const Foo&, int)>f) const;
          ^
amb.cpp:15:10: note: candidate: void Foo::foo(std::function<void(const std::basic_string<char>&, const Foo&)>) const
     void foo(std::function<void(const std::string&, const Foo&)>f) const;
          ^

Why it's not clear which version I want to call? How can I work around this problem?

How to change the name of .exe on runtime

Persay, if I wanna change the .exe on runtime of my program (Like its original name would be: someexe.exe and after you have closed it will change to something random or similiar)

I've seen it happen before and I'm very much interested in implementing it just for fun!

Thanks :)

Min/Max, Mean and Median of columns

I have a complex task and I am struck with it. Below is the sample of the data that i have in a text file. I have to calculate min/max, mean and median of each column. There are over 1000 rows and 50-100 columns in each row. Some columns only contain special characters '?', we don't have to calculate any value for them, just output zero for those columns in the end result. And we have to output a. min/max b. mean (mean = (sum of available values) / number of available values) c. median of every column into another txt file in a single row(output below).

7.84626,0.00121498,?,?,?,?,0.595974,1722821,40877036,73,601,130,45,73,1481,1479,2153,4922.35,116792,6.13849,7.86395,0.00847591,0.00737798 6.18782,0.000136137,?,?,?,?,0.595974,1722821,40877036,73,601,130,45,73,1481,1479,2153,4922.35,116792,6.13849,7.86395,0.00847591 7.86844,0.00187588,?,?,?,?,0.595974,1722821,40877036,73,601,130,45,73,1481,1479,2153,4922.35,116792,6.13849,7.86395,0.00847591,0.00737798 6.12701,0.0010252,?,?,?,?,0.595974,1722821,40877036,73,601,130,45,73,1481,1479,2153,4922.35,116792,6.13849,7.86395,0.00847591,0.00737798

can someone help me with this task?

Output: c1, c2, c3, c4, c5, c6, c7, c8,c9,c10,c11.....c(n) min - - - - - - - - - - - max - - - - - - - - - - - mean - - - - - - - - - - - median - - - - - - - - - - -

'Foo' in namespace 'bar' does not name a type for object member in header file

As a preface, I'm using eclipse c++ as an IDE. And I'm using the c++0x standard. (So I can use mutex's) I'm very new to C++ but have done some C before and am very familiar with Java programming. Also, I know .h is usually not a type for C++ files.

I'm trying to include a private object member of stellad::KeyHook in my class stellad::Dispatcher and I get the following errors when building:

Building file: ../src/KeyHook.cpp
Invoking: GCC C++ Compiler
g++ -std=c++0x -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/KeyHook.d" -MT"src/KeyHook.d" -o "src/KeyHook.o" "../src/KeyHook.cpp"
In file included from ../src/KeyHook.h:10:0,
                 from ../src/KeyHook.cpp:8:
../src/Dispatcher.h:23:11: error: ‘KeyHook’ in namespace ‘stellad’ does not name a type
  stellad::KeyHook keyhook;
           ^
src/subdir.mk:21: recipe for target 'src/KeyHook.o' failed
make: *** [src/KeyHook.o] Error 1

A lot of lines have been removed to reduce noise, such as unnecessary includes, prototypes and function declarations.

Dispatcher.h

/*
 * Dispatcher.h
 */

#ifndef DISPATCHER_H_
#define DISPATCHER_H_

#include "KeyHook.h"

namespace stellad {

class Dispatcher {
private:
    ..
    stellad::KeyHook keyhook;
public:
    Dispatcher();
    virtual ~Dispatcher();
    ..
};

} /* namespace stellad */

int main(int argc, const char* argv[]);
#endif /* DISPATCHER_H_ */

KeyHook.h

/*
 * KeyHook.h
 */

#ifndef KEYHOOK_H_
#define KEYHOOK_H_
#include "Dispatcher.h"

namespace stellad {

class KeyHook{
private:
    ..

public:
    KeyHook();
    virtual ~KeyHook();
    ..
};


} /* namespace stellad */

#endif /* KEYHOOK_H_ */

Multiple indexes query in Boost Multi-Index

I'm writing a software that stores GenericOrder (containing a quantity, a price, a way and a timestamp) as shared_ptr.
I've read Boost documentation and succeed to define a MultiIndexOrderContainer using three indexes: way, timestamp and price.
But I don't find a way to iterate on specific orders using multiple indexes at the same time.

#include <memory>

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/identity.hpp>
#include <boost/multi_index/member.hpp>

using namespace ::boost;
using namespace ::boost::multi_index;

enum class Way
{
    UNDEFINED,
    BUY,
    SELL
};

template <typename QuantityType, typename PriceType>
struct GenericOrder
{
    explicit GenericOrder(const Way way, const QuantityType& quantity, const PriceType& price, const long long& timestamp)
        : way_(way), quantity_(quantity), price_(price), timestamp_(timestamp)
    {
    }

    ~GenericOrder() = default;
    GenericOrder(const GenericOrder&) = delete;
    GenericOrder& operator=(const GenericOrder&) = delete;

    Way way_;
    QuantityType quantity_;
    PriceType price_;
    long long timestamp_ = -1;
};

// Aliases
using QuantityType = int;
using PriceType = int;
using OrderType = GenericOrder<QuantityType, PriceType>;
using PointerType = std::shared_ptr<OrderType>;

struct way {};
struct timestamp {};
struct price {};

using MultiIndexOrderContainer = multi_index_container<PointerType,
    indexed_by<
    ordered_non_unique<tag<way>, member<OrderType, decltype(OrderType::way_), &OrderType::way_ >>,
    ordered_non_unique<tag<timestamp>, member<OrderType, decltype(OrderType::timestamp_), &OrderType::timestamp_ >>,
    ordered_non_unique<tag<price>, member<OrderType, decltype(OrderType::price_), &OrderType::price_>>
    >
>;

int main()
{
    MultiIndexOrderContainer c;

    // Inserting some orders
    c.insert(std::make_shared<OrderType>(Way::BUY, 10, 15, 0));
    c.insert(std::make_shared<OrderType>(Way::BUY, 10, 14, 1));
    c.insert(std::make_shared<OrderType>(Way::BUY, 10, 13, 2));
    c.insert(std::make_shared<OrderType>(Way::SELL, 10, 16, 3));
    c.insert(std::make_shared<OrderType>(Way::SELL, 10, 17, 4));
    c.insert(std::make_shared<OrderType>(Way::SELL, 10, 18, 5));

    return 0;
}

I would like to iterate on:

  1. On buying orders with a specific price sorted by timestamp
  2. Cheapest order price from selling orders
  3. Costliest order price from buying orders

How can I achieve that ?