mardi 1 septembre 2015

c++11: void in template arguments

I was implementing some stuff in C++, and I came across a situation, I did not know how to handle properly. Consider following example

template<typename F>
struct function_wrapper;

template<typename Return, typename... Input>
struct function_wrapper<Return(Input...)>
{
    function_wrapper(/*...*/) = /* ... */
    std::tuple<Input...> input_args;
    Return return_value;

    void first_calculate_result() { return_value = somehow_manipulate(input_args); }
    Return operator()() { return return_value; }
}

Now, obvious usage is like this

my_function<int(double)> stored_fnc(5.5);
stored_fnc.first_calculate_result();
/* something maybe else */
std::cout << "Result is: " << stored_fnc() << std::endl;

Everything works as expected, as long as function's return type is not void.

My question is, do I have to write partial specification for my_function<void(Input...)>, where I would omit all Return stuff, or is there an easier way? Moreover, why does the C++ standard does not allow me to define void variables?

std::dynamic_pointer_cast of std::shared from base to derived returns NULL

I have a function that accepts a shared pointer of type Base and then std::dynamic_pointer_cast to a derived type. However, the derived pointer is a NULL type and I can't see why. I have made sure to include a virtual destructor in my base class. I do not want to use a static cast as this cannot guarantee that my derived member variables and functions are preserved?

The code is as follows:

Base Class:

class Base
{
public:
    mType get_type()
    {
        return msg_type;
    }

    void set_type(mType type)
    {
        msg_type = type;
    }

    virtual ~cMsg() = default;
protected:
    mType msg_type;
    message msg;
};

Derived Class:

class Derived : public Base
{
public:
    void set_i(int j)
    {
        i = j;
    }

    int get_i()
    {
        return i;
    }
private:
    int i;
};

Function performing cast:

void callback(std::shared_ptr<Base> msg_received)
{
    std::cout<< "Callback called\n";
    auto real_msg = std::dynamic_pointer_cast<Derived>(msg_received);

    if (real_msg != NULL)
    {
        std::cout << "i value is: " << real_msg->get_i() << "\n";
    }

}

Function creating the Derived object and calling the function:

int main()
{  
    Derived test_msg;

    test_msg.set_i(1);    
    test_msg.set_type(mSystem::TEST_MSG);

    std::shared_ptr<Base> msg_ptr = std::make_shared<Base>(test_msg);    

    callback(test_msg);

    return 0;
}

Any help would be appreciated.

What type is an array?

I am asking this question with reference to the following code

#include <iostream>
using namespace std;

class A {
    void foo(){}
};

template <typename T>
void func(T (&a) [1]) {cout << "In array type" << endl;}
template <typename T>
void func(T (*a) [1]) {cout << "In pointer to array type " << endl;}
template <typename T>
void func(T* a) {cout << "in pointer type" << endl;}
template <typename T>
void func(T** a) {cout << "In pointer pointer type" << endl;}
template <typename T>
void func(...) {}

int foo(int a) {return 1;}
int foo1() {return 1;}

int main() {
    A a[1];
    func<A>(&a);    

    return 0;
}

What is the type of an array? From the following code I can tell that when you take the address of an array with the & operator the function call resolves to the one with T (*a) [1] and the call is not ambiguous, but the when I change the code to the following

#include <iostream>
using namespace std;

class A {
    void foo(){}
};

template <typename T>
void func(T (&a) [1]) {cout << "In array type" << endl;}
template <typename T>
void func(T (*a) [1]) {cout << "In pointer to array type " << endl;}
template <typename T>
void func(T* a) {cout << "in pointer type" << endl;}
template <typename T>
void func(T** a) {cout << "In pointer pointer type" << endl;}
template <typename T>
void func(...) {}

int foo(int a) {return 1;}
int foo1() {return 1;}

int main() {
    A a[1];
    func<A>(a);  // <-- CHANGE HERE  

    return 0;
}

I get an error, saying that the call to the function is ambiguous. So the imaginary type_of(a) and T* are equivalent. How then are the types of &a and T** not equivalent?

The way I am trying to explain this to myself is that the type of an array to objects is T (&) [N] and the type of an array of objects of type T is T (*) [N]. And that the standard allows implicit conversion from the first (i.e. from T (&a) [N] to T*) but when you take the address of an array it does not implicitly go from a T (*) [N] to a T**. Am I correct? Or am I inferring what T (*) [N] is wrongly?

Further how do you go about reading the meaning of syntax like this. Is there a document I can refer to?

Thanks!

Does relaxed memory order effect can be extended to after performing-thread's life?

Let's say inside a C++11 program, we have a main thread named A that launches an asynchronous thread named B. Inside thread B, we perform an atomic store on an atomic variable with std::memory_order_relaxed memory order. Then thread A joins with thread B. Then thread A launches another thread named C that performs an atomic load operation with std::memory_order_relaxed memory order. Is it possible that thread C loaded content is different from the content written by thread B? In other words, does relaxed memory consistency here extends to even after the life of a thread?

To try this, I wrote a simple program and ran it with many tries. The program does not report a mismatch. I'm thinking since thread A imposes an order in launch of threads, mismatch cannot happen. However, I'm not sure of it.

#include <atomic>
#include <iostream>
#include <future>

int main() {

    static const int nTests = 100000;
    std::atomic<int> myAtomic( 0 );

    auto storeFunc = [&]( int inNum ){
        myAtomic.store( inNum, std::memory_order_relaxed );
    };

    auto loadFunc = [&]() {
        return myAtomic.load( std::memory_order_relaxed );
    };

    for( int ttt = 1; ttt <= nTests; ++ttt ) {
        auto writingThread = std::async( std::launch::async, storeFunc, ttt );
        writingThread.get();
        auto readingThread = std::async( std::launch::async, loadFunc );
        auto readVal = readingThread.get();
        if( readVal != ttt ) {
            std::cout << "mismatch!\t" << ttt << "\t!=\t" << readVal << "\n";
            return 1;
        }
    }

    std::cout << "done.\n";
    return 0;

}

C++ unwanted type deduction

I have the two following functions:

  template<class F, class... Args>
  auto runAt(F&& function, const std::chrono::steady_clock::time_point& timePoint, Args&&... args)
    -> std::future<typename std::result_of<F(Args...)>::type> {
    using return_type = typename std::result_of<F(Args...)>::type;
    std::future<return_type> futureResult;

    auto packagedTask = std::make_shared<std::packaged_task<return_type()> >
    (std::bind(std::forward<F>(function), std::forward<Args>(args)...));
    futureResult = packagedTask->get_future();

    this->addTask(Task([this, packagedTask]() {
        (*packagedTask)();
      }), timePoint);
    return futureResult;
  }

  void runAt(const Task& task,
             const std::chrono::steady_clock::time_point& timePoint);

In my main.cpp file, I created a Task object, assigned a function to it and pushed it into my scheduler. runAt are scheduler's functions.

This is the code:

... // Task initialization
scheduler.runAt(task, std::chrono::steady_clock::now());

The problem is that the templated function is called instead of the one taking a Task as parameter. I understand that both functions are valid since the first parameter is templated and the variadic argument object is empty.

I have two questions:

1) How to call the second method (consider that the return types are not the same)

2) Not very important but I'm curious to know how this does not fail during the compilation

  auto packagedTask = std::make_shared<std::packaged_task<return_type()> >
    (std::bind(std::forward<F>(function), std::forward<Args>(args)...));

Wrapping each type in a variadic template in a templated class

Given a variadic template Types..., I would like to store A<> for each of the types in the pack. This could be done in a tuple of A<>'s, but I'd need to programmatically derive the type of said tuple.

Is such a thing even possible in c++11/14/17?

template <class T> class A { };

template <class... Types>
class B
{
   // A tuple of A<>'s for each type in Types...
   std::tuple<A<Type1>, A<Type2>, ...> data;
};

object destructed before move operation

#include <iostream>
static int i=0;
using namespace std;
class Movable
{
public:
    Movable ():mId(++i){
        cout<<"constructing it "<<mId<<endl;
    };
    Movable (const Movable&)=delete;
    Movable (Movable&)=delete;
    void operator=(Movable&)=delete;
    void operator=(const Movable&)=delete;

    Movable (const Movable&& aObject)
    {
        cout<<"Moving it constant "<<mId<<endl;
//      mId=++i;
    };
    Movable (Movable&&aObject)
    {
        cout<<"Moving it "<<mId<<endl;
    };
    Movable &operator=( Movable&&aObject)
    {
        cout<<"Moving it assignment "<<mId<<endl;
        return *this;

    }
    Movable &operator=(const Movable&&aObject)
    {
        cout<<"Moving it assignment constant "<<mId<<endl;
        return *this;

    }
    ~Movable ()
    {
        cout<<"destroying it "<<mId<<endl;
    }

    int getId() const {
        return mId;
    }

private:
    int mId;
};

Movable&& CreatenNewMovable ()
{
    Movable lM;
    return std::move(lM);
}

int main() {
    Movable a;

    a=CreatenNewMovable();

    return 0;
}

The output result of this code is

constructing it 1 constructing it 2 destroying it 2 Moving it assignment 1 destroying it 1

I'm a little bit confused how is it possible to destroy the temp object then move it to second. Is that an undefined behavior ? m I missing something about the move operation?