vendredi 29 mai 2015

How can i declare enum variable inside a class using forward declaration

The following declaration syntax doesn't work inside a class, but it is acceptable for "outside class" declaration according to c++11. Could you give me some advices how can i implement such a logic if it possible of course.

class A
{
    private:

    enum class colors : unsigned char;

    colors c;

    public:

    A()
    {

    }

    virtual ~A()
    {

    }

    private:

    enum class colors : unsigned char
    {
        red,
        blue,
        green
    };
};

Read lines from console output in the current Console

My program is executing another. Both run in the same Console. Program 2 is writing text in the console. So Programm 1 should read and process it. There is no other Solution for me, because i don't own program 2, so i can't modify it. So the idea is that the output of program 2 is still visible. By now the programs both work multithreaded alongside eachother, so this part is fine. So my question is, how do i read lines from the console? A small example how this sould work:

string readMyLine(){
    //Solution Here
}    
main(){
        cout<<"Hello this is a line"<<endl;
        string line = readMyLine(); //line should be "Hello this is a line"
        cout<<"The previus Line was "<<line<<endl;
    }

Well the idea is not to use pipes, rather than reading directly from the console like shown in my example; I had a Idea but it won't work. It returns a pointer, which doesn't help me much...

string ReadConsoleLine(COORD rectStart, COORD rectEnd) {
    HANDLE     hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
    PCHAR_INFO buffer = new CHAR_INFO[(rectEnd.X - rectStart.X) * (rectEnd.Y - rectStart.Y)];
    COORD      buffer_size = { (rectEnd.X - rectStart.X), (rectEnd.Y - rectStart.Y) };
    COORD      buffer_index = { 0, 0 };
    SMALL_RECT read_rect = { rectEnd.X, rectEnd.Y, rectEnd.X, rectEnd.Y};
    ReadConsoleOutput(hStdOut, buffer, buffer_size, buffer_index, &read_rect);
    stringstream Out;
    Out << buffer;
    return Out.str();
}

I use std::atomic to protect access to float variables that may be assessed from multiple threads. This works well on x86, but crashes on ARMv7 (RPi2).

I'm compiling on x86 with VS2012, Xcode and GCC4.9.2 with no problems. Code that use the atomic values when I compile for ARMv7 (also GCC4.9.2) crashes with 'Bus Error' (which you get when data is not properly aligned on ARM).

Is this a bug in GCC or am I doing something wrong?

thrust exception bulk_kernel_by_value in transform_reduce

I'm working on a optimization problem which contains various math functions which resembles in similar form, so I warp them in a FunctionObj

template <typename T>
struct FunctionObj
{
    T a;
     FunctionObj(): a(1)
    {
    }
};

And defines a FuncEval to evaluate

template <typename T>
__host__ __device__  inline T FuncEval(const FunctionObj<T> &f_obj, T x)
{
    return f_obj.a+x;
}

What I really want to do is sum {func(x)}, so I defines a FuncEvalF functor to make use of thrust::tranform_reduce

template <typename T>
struct FuncEvalF
{
    const FunctionObj<T>& f_obj;
    __host__ __device__ inline FuncEvalF(const FunctionObj<T>& in_f_obj) :f_obj(in_f_obj)
{

}
    __host__ __device__ inline T operator()(T x)
    {
        return FuncEval(f_obj, x);
    }
};

template <typename T>
__host__ __device__ inline T BatchFuncEval(const FunctionObj<T>  &f_obj, int size, const T *x_in);
template<>
inline float BatchFuncEval< float>(const FunctionObj<float>  &f_obj, int size, const float *x_in)
{
    return thrust::transform_reduce(thrust::device, thrust::device_pointer_cast(x_in), thrust::device_pointer_cast(x_in + size), FuncEvalF<float>(f_obj), static_cast<float>(0), thrust::plus<float>());
}

Finally in the main.cu I call the transform_reduce

auto func = FuncEvalF<float>(FunctionObj<float>());
    float result = 0;
    try
    {
        result = thrust::transform_reduce(thrust::device, thrust::device_pointer_cast(dev_a), thrust::device_pointer_cast(dev_a + 10000), func, static_cast<float>(0), thrust::plus<float>());

    }
    catch (std::exception e)
    {
        printf("%s in thurst \n ", e.what());
    }

Here the exception comes : bulk_kernel_by_value, even I change the 10000 to 10. Thing only goes better when I change the defintion of FuncEval to

return x;

The program would output the right but meaningless answer . I can't help asking what's wrong with my code ? Thank you for your attention.

jeudi 28 mai 2015

Linkage of explicit class template instantiation

Are multiple instantiations of the same class template with the same type allowed in different compilation units? What about function templates?

A sample code is as follow:

test.hpp

template <typename T>
class A
{
    public:
        T out();
};

template <typename T>
T A<T>::out()
{
    return T(1);
}

test1.cpp

#include "test.hpp"
template class A<int>;
int testFn()
{
    return A<int>().out();
}

test2.cpp

#include "test.hpp"
template class A<int>;
extern int testFn();
int main()
{
    return testFn() == A<int>().out();
}

If I run

g++ -std=c++11 test1.cpp test2.cpp -o test

it compiles without complaining duplicated definitions.

I was refering to an old draft of standard [1], and assuming linkage part doesn't change too much (except for anonymous namespaces). The class template has external linkage by 3.5.4 and 14.0.4. If that's the case, I would reason that g++ should complain duplicated definitions of A::out(). Am I missing something here?

What if test.hpp defines a function template without "static" or "inline" instead?

Thank you.

[1] http://ift.tt/1JaUT74

Error on implicit cast from std:unique_ptr to bool

I am using Allegro to create a simple game. When I try to validate that my pointer to the display is not null I get a compiler error telling me

error C2664: 'void validate(bool,std::string)' : cannot convert argument 1 from 'std::unique_ptr< ALLEGRO_DISPLAY,main::< lambda_996846ce92067e506da99cad36e610cf>>' to 'bool'

Here is my code

#include <iostream>
#include <memory>
#include <string>

#include <allegro5\allegro.h>

using namespace std;

const int WIDTH = 512;
const int HEIGHT = 512;

void validate(bool ptr, string errorMessage) {
    if (!ptr) {
        cerr << errorMessage << endl;
        exit(-1);
    }
}

int main() {
    auto deleter = [](ALLEGRO_DISPLAY* d) { al_destroy_display(d); };
    unique_ptr<ALLEGRO_DISPLAY, decltype(deleter)> display;

    validate(al_init(), "Failed to initialize Allegro");
    display = unique_ptr<ALLEGRO_DISPLAY, decltype(deleter)>(al_create_display(WIDTH, HEIGHT), deleter);
    validate(display, "Failed to create display");

    return 0;
}

If I pass validate "!display" instead of "display" it works. I realize I could call validate with display.get(), but I wanted to know why it isn't working when I pass a smart pointer.

When we implement lock-free data structures, why do we need to manage memory?

When we implement lock-free data structures, why do we need to manage memory? Consider the following stack example, why does the "delete old_head" statement in the pop function , as the book say, cause problems to other threads? I don't see chances that "dereferencing a dangling pointer" can happen, and I run the code several times, not getting any error.

template<typename T>
class lock_free_stack
{
private:
    struct node
    {
        std::shared_ptr<T> data;
        node* next;
        node(T const& data_) :
            data(std::make_shared<T>(data_))
        {}
    };
    std::atomic<node*> head;

public:
    void push(T const& data)
    {
        node* const new_node = new node(data);
        new_node->next = head.load();
        while (!head.compare_exchange_weak(new_node->next, new_node));
    }

    std::shared_ptr<T> pop()
    {
        node* old_head = head.load();
        while (old_head &&
            !head.compare_exchange_weak(old_head, old_head->next));
        auto res = old_head ? old_head->data : nullptr;
        delete old_head;
        return res;
    }
};