mercredi 30 novembre 2016

C++ code working on terminal but not with codeblocks

I have the following c++ code :

set<pair<int,int> > setCouple = c.cartesianProduct(d);
    typename set<pair<int,int> >::iterator it;

    for(it =setCouple.begin(); it!= setCouple.end(); ++it) {
        cout << get<0>(*it)<< ", " << get<1>(*it)  << endl;
    }
}

This code is perfectly compiling and running when i compile it with the following command line :

clear;clear;g++ -Wall -Weffc++ -std=c++11 *.cpp -o a

But when i want to build it in codeblock (on debian) i have this error :

error: ‘template struct std::pair’ used without template parameters|

And this error as well :

error: no match for ‘operator<<’ (operand types are ‘const std::pair’ and ‘const char [3]’)|

When i intalled debian i selected the gcc compiler.

Why do i have these 2 error only when i want to comile and run on CodeBlock ? In the future i would like to code on an IDE for C++, will i have these kind of problem (code that works on command line but not in IDE) frequently ?

How to automatically call a method or generate code if a subclass derived from a base class?

I have some classes that describe abilities / behaviours, such as flying, or driving etc. Each of these classes has a specific method that must be called to load some data - For example, Flyable has loadFlyData, Drivable has loadDriveData. For each class the method name is unique.

I have many derived classes that may inherit from one or more of these behaviour classes. Each of these derived classes has a method called loadData, in which we should call all the parent behaviour classes methods such as loadFlyData, loadDriveData etc.... Is there a way to automatically generate this method using metaprogramming ? Since there are many derived classes, it may be more maintainable if I can generate these methods using metaprogramming...

Behaviour classes : (An object class may have any of these behaviours, and will have to call that classes "load" method...

class Flyable{

  void loadFlyData(){
  }
};

class Drivable{
  void loadDriveData(){
  }
};

All object classes derive from Object:

class Object{
  virtual void loadData(){
  }
};

A derived class:

class FlyingCar : public Object, public Flyable, public Drivable{
  virtual void loadData()override{
        //How to automatically generate code so that the next two lines are called:
    loadFlyData();
    loadDriveData();
  }
};

Why doesn't SFINAE work as expected?

#include <iostream>
#include <type_traits>

using namespace std;

template<typename T>
constexpr auto is_pure_input_iterator(int) ->
conditional_t
<
    is_convertible_v
    <
    iterator_traits<T>::iterator_category,
    input_iterator_tag
    >,
    true_type, true_type
>;

template<typename>
constexpr false_type is_pure_input_iterator(...);

int main()
{
    cout << boolalpha 
        << decltype(is_pure_input_iterator<istream_iterator<int>>(0))::value
        << endl;

    return {};
}

The expected output should be: true, but the actual one is false.

What's wrong in my code?

Pattern to avoid Cyclic calls

I have Policy class as below:

interface IPolicy
{
public:
virtual void func1() = 0;
}

class CPolicy : public IPolicy
{
public:
void func1() override { // do something }
}

And I have Utility Class as

class Util {
public:
void func1() {
if( policy != nullptr ) policy->func1(); // customized behavior

// default behavior
}

}

Now problem is, consider policy implementation have some condition and if that condition fails, policy calls default implementation ( this is one of the scenario, there can be multiple combinations )

class CPolicy : public IPolicy
{
public:
void func1() override { 
 if( condition ) 
 {
    // customized logic
 }
 pDefaultUtil->func1();
}
}

Now if you see this implementation it will endup in cyclic calls.

To solve such problem, I introduced another function in IPolicy contract.

interface IPolicy
{
public:
virtual void func1() = 0;
virtual bool ShouldUsePolicy() = 0;
}


class CPolicy : public IPolicy
{
public:
void func1() override { 
 if( condition ) 
 {
    // customized logic
 }
 usePolicy = false;
 pDefaultUtil->func1();
usePolicy = true;
// other logic continues.
}

bool ShouldUsePolicy() override { return usePolicy; }
private:
bool usePolicy { true };
}

and Util class is modified as :

class Util {
public:
void func1() {
if( policy != nullptr && policy->ShouldUsePolicy() ) policy->func1(); // customized behavior

// default behavior
}

}

With these changes, everything will work as expected, but I am not happy with this design. I don't want to depend on whether Policy is setting usePolicy variable properly or not. If any call comes from Policy to Default implementation then I should be able to ignore policy.

Is there any good pattern / solution for such problems?

Understanding how to delete nodes on a Binary Tree

So i am currently studying how to delete nodes on a binary tree although i cannot get over one misunderstanding. i have check the code multiple times and it does work every time. this code comes from Tony Gaddis' C++ From Control Structures through Objects book.

void intBinTree::remove(int num)
{
    deleteNode(num, root);
}

void intBinTree::deleteNode(int num, treeNode*& nodePtr)
{
    if (num < nodePtr->value)
        deleteNode(num, nodePtr->left);
    else if (num > nodePtr->value)
        deleteNode(num, nodePtr->right);
    else
        makeDeletion(nodePtr);
}

void intBinTree::makeDeletion(treeNode*& nodePtr)
{
    treeNode* tempNodePtr = nullptr;

    if (nodePtr == nullptr)
        cout << "Cammot delete empty node" <<  endl;
    else if (nodePtr->right == nullptr)
    {
        tempNodePtr = nodePtr;
        nodePtr = nodePtr->left;
        delete tempNodePtr;
    }
    else if (nodePtr->left == nullptr)
    {
        tempNodePtr = nodePtr;
        nodePtr = nodePtr->right;
        delete tempNodePtr;
    }
    else
    {
        tempNodePtr = nodePtr->right;

        while (tempNodePtr->left)
            tempNodePtr = tempNodePtr->left;

        tempNodePtr->left = nodePtr->left;
        tempNodePtr = nodePtr;
        nodePtr = nodePtr->right;
        delete tempNodePtr;
    }
}

What i am failing to grasp is around the MakeDeletion function.

void intBinTree::makeDeletion(treeNode*& nodePtr)
{
    treeNode* tempNodePtr = nullptr;

    if (nodePtr == nullptr)
        cout << "Cammot delete empty node" <<  endl;
    else if (nodePtr->right == nullptr)
    {
        tempNodePtr = nodePtr;
        nodePtr = nodePtr->left; //where the book says it reattaches child
        delete tempNodePtr;
    }
    else if (nodePtr->left == nullptr)
    {
        tempNodePtr = nodePtr;
        nodePtr = nodePtr->right; //where the books says it reattaches child
        delete tempNodePtr;
    }
    else
    {
        tempNodePtr = nodePtr->right;

        while (tempNodePtr->left)
            tempNodePtr = tempNodePtr->left;

        tempNodePtr->left = nodePtr->left;
        tempNodePtr = nodePtr;
        nodePtr = nodePtr->right; //where the book says it reattaches subtree
        delete tempNodePtr;
    }
}

At first glance it seems like all it does is simply move pointers and leaves subtrees severed. but somehow it works flawlessly and i want to understand how.

Any help would be appreciated.

How to replicate map, filter and reduce behaviors in C++ using STL?

I suppose we can use std::transform to replicate the map behavior in C++ like this :

std::vector<int> in = { 1 , 2 , 3 ,4 }; 
std::vector<int> out(in.size()); 

std::transform(in.being() , in.end() , out.begin() , [](const int & val)
{
    return val+1;
});

I guess a better way would be to use the back inserter.'

std::vector<int> out2;

std::transform(in.begin() , in.end() , std::back_inserter(out2) , [](const int & val){
      return val + 1;
});

// out will be { 2 , 3 ,4 ,5 }

Am I right ? How do I do the filter and reduce operations in C++ using STL ?

Accessing static properties of a pointer type

I am trying to call a static method of a type in a tuple, but the tuple uses pointers, not the type itself. This means that when I use tuple_element I am getting a pointer type which I can not use to call the static method.

Does anyone know how to either convert a pointer type to its non-pointer equivalent, or access a static property of a pointer type?

struct Example
{
    static int example()
    {
        return 0;
    }
};

typedef Example* PointerType;

int main()
{
    PointerType::example(); // Nope
    (*PointerType)::example(); // Nope
    (typename *PointerType)::example(); // Nope
    (PointerType*)::example(); // Nope
}

How to apply permutation to std::map values

I have a std::vector<T> and a std::map<U, std::size_t>, where the map acts as a different way to index the vector, i.e. the value in a key-value pair of the map is the index of a vector element. I can guarantee that not only the keys, but also the values of the map are unique.

Now when I apply a std::sort to the vector, that obviously changes the indices under which elements can be found, and I'd like to update my map accordingly.

I have found this answer for applying a permutation to a second vector. What I want to do is apply this permutation to the values of the map.

The following code does work, but is of course terribly inefficient

template <typename T, typename U>
std::vector<T> apply_permutation(const std::vector<T>& vec,
                                 std::map<U, std::size_t>& m,
                                 const std::vector<std::size_t>& p)
{
    std::vector<T> sorted_vec(vec.size());
    std::transform(p.begin(), p.end(), sorted_vec.begin(),
                   [&](std::size_t i){ return vec[i]; });
    for (std::size_t i(0); i != p.size(); ++i)
        for (auto it = m.begin(); it != m.end(); ++it)
            if (it->second == p[i])
                it->second = i;

    return sorted_vec;
}

I'm looking for a more efficient way to keep the vector and map in sync.

how to infer the return value type from std::function?

I'd like to make the return value type generic using std::function, but it does not work, code: debuggable code can be found: http://cpp.sh/5bk5

class Test { public: template < typename R, typename F = std::function<R()> > R f(F&& op) { op(); }; void t() { int a = 10; f([this, a]() { return "chars"; }); }; }; int main() { t::Test test; test.t(); return 0; }

How to find min/max in std::map like in std::set ?

Since both set and map are ordered containers, can the min and the max be found in 0(1) time ?

// for std::set
// std::set<int> s;
auto min = *s.begin();

auto max = *s.rbegin();

How do I obtain the max and min in O(1) from a std::map ? Other questions here seem to suggest to iterate through the map, but can't we use the ordered properlt of std::map to obtain the result faster ?

Strange behaviour of default template-argument in a template-templae-parameter

Consider this C++11 program:

#include <iostream>

template <class A, class B = char> struct Cont {
    Cont () { std::cout << sizeof(B); }
};

template <template<class, class = int> class C, class E> class Wrap1
{
    C<E> ce;
};

template <template<class, class = int> class C, class... E> class Wrap2
{
    C<E...> ce;
};

int main ()
{
    Wrap1<Cont, void> w1;
    Wrap2<Cont, void> w2;
}

When compiled with either gcc or clang, the output is 41.

Is this behaviour according to the standard? Where exactly does the standard specify it (for both Wrap1 and Wrap2)?

This question is inspired in part by this other question.

Why std::vector iterator is invalidated after the erase() call?

The C++ reference clearly state that calling std::vector::erase(it) on iterator will invalidate all iterators pointing to and after the erased element. http://ift.tt/1tl2KTy

I do understand why such iterators became non-dereferenceable after the erase call, but i am curious why they need to became invalid, what implementation details require it?

For instance standard says that std::vector must be implemented with elements stored contiguously and that elements can be accessed not only through iterators, but also using offsets on regular pointers to elements so it seems logical that iterators for such container will probably be implemented as pointers - but then how pointers could became invalidated?

Writing formatted output to two files at the same time

For an assignment I have to write a class that offers the same facilities as ostream, but outputs to two files at the same time.

Currently I have the following code (in-class implementations for brevity):

#ifndef BISTREAM_H_
#define BISTREAM_H_

#include <iostream>
#include <fstream>

class BiStream : public std::ostream
{
    std::ofstream d_firstFile;
    std::ofstream d_secondFile;
    public:
        BiStream(std::ofstream& one, std::ofstream& two)
        :
            d_firstFile(std::move(one)),
            d_secondFile(std::move(two)) 
        {}
        friend std::ostream& operator<<(BiStream& out, char const *txt)
        {
            out.d_firstFile << txt;
            out.d_secondFile << txt;
            return out;
        }
};
#endif

Then I can use this in the following way:

#include "bistream.h"

using namespace std;

int main()
{
    ofstream one("one");
    ofstream two("two");

    BiStream ms(one, two);

    ms << "Hello World" << endl;    // Write to files and flush stream
}

If I run the resulting program, it correctly prints "Hello World" to both files, but no newline is added to either files.

Furthermore, statements like (after including iomanip of course)

ms << std::hex << 5 << '\n';

result in no text printed in the files. As a last example:

ms << "test" <<"Hello World" << endl;  

Only prints "test" to the files. This all implies that my overload insertion operator only writes the first argument to the file...

What is the best way to approach this problem? The exercise hints at a second class that inherits from std::streambuf, but std::streambuf is something that I don't understand and searching for explanations on the internet hasn't made it any clearer.

Thanks!

How similar are Boost filesystem and the standard C++ filesystem libraries?

I need a filesystem library for use with a C++11-capable compiler or a C++14-capable one - so it can't be be from C++17. Now, I know that the new filesystem library is based based on Boost's library of the same name; but - are they similar enough for me to use the Boost library and then seemlessly switch to the standard version at a later time, without changing more than, say, a using statement? Or are there (minor/significant) differences between the two? I know that for the case of variant, the Boost and standard library versions differ quite a bit.

Bizzare nullref in C++

I have a small piece of C++ code that is making me insane. Whenever it runs, it throws a null reference exception in a very unexpected place.

void CSoundHandle::SetTarget(CSound* sound)
{
  assert(_Target == nullptr);
  if (sound == nullptr) { return; }

  _Target = sound;

  // This is the code that throws the exception.  It doesn't seem possible, as
  // we should not be able to get here if 'sound' is null.
  _Target->Stop();
}

So what the heck is going on? The message in the output window is:

this->_Target-> was nullptr.
0xC0000005: Access violation reading location 0x00000014

I have confirmed in disassembly that it is not taking place inside of the Stop function as well. How is this possible?

Empty braces around std::make_index_sequence

In this example on CppR:

template<typename Array, std::size_t... I>
decltype(auto) a2t_impl(const Array& a, std::index_sequence<I...>)
{
    return std::make_tuple(a[I]...);
}

template<typename T, std::size_t N, typename Indices = std::make_index_sequence<N>>
decltype(auto) a2t(const std::array<T, N>& a)
{
    return a2t_impl(a, Indices());
}

template<typename Func, typename Tup, std::size_t... index>
decltype(auto) invoke_helper(Func&& func, Tup&& tup, std::index_sequence<index...>)
{
    return func(std::get<index>(std::forward<Tup>(tup))...);
}

template<typename Func, typename Tup>
decltype(auto) invoke(Func&& func, Tup&& tup)
{
    constexpr auto Size = std::tuple_size<typename std::decay<Tup>::type>::value;
    return invoke_helper(std::forward<Func>(func),
                         std::forward<Tup>(tup),
                         std::make_index_sequence<Size>{});
}

there are these lines, which confuse me a lot:

std::make_index_sequence<N>
std::make_index_sequence<Size>{}

Why are the curly braces added at the end at times (and omitting them causes a compile error) and why are they sometimes not?

clang::ast_type_traits::DynTypedNode::get() cant infer template argument 'T'

i have this code snippet:

ASTContext::DynTypedNodeList NodeList = ASTC->getParents(*DRE); ast_type_traits::DynTypedNode ParentNode = NodeList[0]; /*some code here to determine if the NodeKind is ImplicitCastExpr*/ const ImplicitCastExpr* ParentICE = ParentNode.get();

basically, its getting the parent of a match-node and then if its an ImplicitCastExpr(), i want to get the node as one and do some further checks. when i try to compile the code, for DynTypedNode::get(), i get this:

mutator-lvl0.cpp:1644:30: error: no matching member function for call to 'get' ParentICE = ParentNode.get(); ~~~~~~~~~~~^~~ /home/bloodstalker/llvm/llvm/llvm/tools/clang/include/clang/AST/ASTTypeTraits.h:233:12: note: candidate template ignored: couldn't infer template argument 'T' const T *get() const {

here's the declaration from the header:

template <typename T> const T *get() const { return BaseConverter<T>::get(NodeKind, Storage.buffer); }

what am i doing wrong?

How to implement a subset iterator for a class with N number of vectors in it

If I had a class that holds N number of equally sized vectors. How would I go about implementing a standard iterator template that would iterate between 1 and N number of the vectors together. I wrote a small example demonstrating the problem.

#include <bitset>
#include <tuple>
#include <type_traits>
#include <vector>

//Since std::get<>() for types isn't in c++11, I use this meta-function to determine the index
//of a Type in a list of Types, starting from 0. ex: IndexOf<C,  A, B, C>::value = 2
template <typename T, typename... Ts>
struct IndexOf;

template <typename T, typename... Ts>
struct IndexOf<T, T, Ts...> : std::integral_constant<std::size_t, 0> {};

template <typename T, typename U, typename... Ts>
struct IndexOf<T, U, Ts...> : std::integral_constant<std::size_t, 1 + IndexOf<T, Ts...>::value> {};

//Used to determine the slot we're interesting in.
using Handle = const std::size_t;

template<typename... Types>
class DataManager
{
    static constexpr std::size_t TypeCount = sizeof... (Types);
    using Flags = std::bitset<TypeCount>; //BitMask to determine if the handle has a certain piece of data initialized

    std::size_t count, capacity;
    std::tuple<std::vector<Types>..., std::vector<Flags>> vectors; //Tuple of vectors, holding the types and flags.
public:
    DataManager(std::size_t n) : count(0), capacity(n),
    vectors(std::make_tuple(std::vector<Types>(n)..., std::vector<Flags>(n)))
    {}

    template <typename Type, typename... Args>
    void add(Handle handle, Args&&... args) { //Initializes the type in the handle slot of the vector
        Flags& flags = std::get<TypeCount>(vectors)[handle];    //Flag the bit, notify that handle
        flags.set(IndexOf<Type, Types...>::value);              //has that piece of data initialized

        std::get<IndexOf<Type, Types...>::value>(vectors)[handle] = Type{ args... };
    }

    template <typename Type>
    Type& get(Handle handle) { //Returns the Type in handle slot of the vector
        return std::get<IndexOf<Type, Types...>::value>(vectors)[handle];
    }

    template <typename Type>
    bool has(Handle handle) { //Returns true if the Type is initialized, by checking the bitset
        Flags& flags = std::get<TypeCount>(vectors)[handle];
        return flags.test(IndexOf<Type, Types...>::value);
    }

    Handle push_back() {
        return count++;
    }
};

Which I currently use like this to access data:

//Simple Data
struct D0 { int x, y;    };
struct D1 { float  n, m; };
struct D2 { int x, y, z; };

int main()
{
    DataManager<D0, D1, D2> manager(100);
    Handle h0 = manager.push_back();

    std::cout << manager.has<D0>(h0) << std::endl;   //prints false, h0 doesn't have D0 initialized
    manager.add<D0>(h0, 75, 20);                     //initialize D0 for h0

    std::cout << manager.has<D0>(h0) << std::endl;   //prints ture, h0 is now initialzed
    std::cout << manager.get<D0>(h0).x << std::endl; //prints 75
}

How could I add iterator functionality to the DataManager class, that would only iterate over selected data like this?

 int main() 
 {
     ...
     for (D0 d1, D3 d3 : manager) {
         ... //Iterate over all D0s and D3s between 0 and count
     }
     //or 
     for(DataManager<D0>::iterator it = v.begin(); it != v.end(); ++it {
         ... //Iterate over just D0s between 0 and count - 10
     }
 }

Exclude class member by specialization

I have base class template, on that I'm making some another class, which are specialized versions of my base class. I know how to exclude some methods from particular specialization case, but is there any possibility to make that for class's members? Example code, of what I want to achieve:

template<typename T>
class Base {
  This variable exists only when T==integer VARIABLE;
}

template <Typename T>
WithVariable = using Base<int>;

template <Typename T>
Without = using Base<double>

I think that I should use std::enable in some way, but using it makes possible to make VARIABLE of type void, when I don't want that variable. That is still not the situation I want to achieve.

Having issues splitting/formatting a string into a vector based on multiple criteria

I need to split a series of strings that are formatted like the following 2 strings:

<verb> sigh <adverb> ; portend like <object> ; die <adverb> ;

<start> The <object> <verb> tonight. ;

into a vector in which the first nonlimiter (ex:) is the first element of the vector, and then the rest of the string is broken up into elements by the semicolons. So the first example string should be broken up like this when I'm finished:

newvec.at(0)= <verb>
newvec.at(1) = sigh <adverb>
newvec.at(2) = portend like <object>
newvect.at(3) = die <adverb>

I was provided with the following function to break up strings into vectors using regexs as delimiters and it worked fine when I previously needed it, but I'm having trouble figuring out how to use it in this case if I even can.

/**
 * Splits the input string based on the (string) regular expression.
 *
 * @param input the string to split.
 * @param regex a string for the regular expression to use to split.
 * @param delim if true, then the regex chars will be returned in the split,
 *              if false, the regex chars are removed.
 * @return a vector of strings that is the input string split based on the
 *         given regular expression.
 */
vector<string> split(const string &input, const string &regex, bool delim = true) {
    std::regex re(regex);

    std::sregex_token_iterator first, last;
    if (delim) {
        first = sregex_token_iterator{input.begin(), input.end(), re};
    } else {
        // the -1 removes the delimiter
        first = sregex_token_iterator{input.begin(), input.end(), re, -1};
    }
    return vector<string>(first, last);
}

Calling new_vec = split(ex_string, ";", false) in my function will split the string into a vector based on the semicolons (and remove the semicolons), but I'm unsure of how to make the first non limiter the first element of the vector. Any help would be greatly appreciated.

C++ std:.auto_ptr or std::unique_ptr (to support multiple compilers, even old C++03 compilers)?

I'm trying to update some C++ code, I'd like to move toward a more modern code (c++11), but I still need to compile the code with some older compilers (c++03 compliant), because of supported platform constraints.

I know in C++11 compilers std::auto_ptr is deprecated, but because of the older compiler support, I can't just replace them with std::unique_ptr.

Is there a good practice to handle this "old compiler support, but start to move to C++11"?

C++ cout prints " inf " after operations between two big decimal number (long double)

My program takes a vector of long doubles as input (vector<long double>) and calculates different solutions using some methods.

Everything works fine untill I try these two numbers: 1.18973e+4932 and 1.18973e+4932.

It outputs the following:

<2: 1.18973e+4932 1.18973e+4932 > Min: 1.18973e+4932 Max: 1.18973e+4932 Range: 0 Midrange: inf Median: inf Mean: inf Variance: inf StdVariance : inf

After some researches, I found out that the value is exceeding the space in memory available for its own type.

So the question is: is it possible to handle this inside my code? Or the only solution is to input a smaller number?

Dynamic Allocation of Arrays

I'm trying to write a simple flight reservation system for my school assignment. I should dynamically create an array without determining a size. Since I have to keep track of the size of the array, I declared an integer variable named as count in my class. I also have a flight class that has a copy constructor and a couple of getters. Then I wrote the following method

void ReservationSystem::addFlight(const int flightNo, const int rowNo, const int seatNo) {
if (count == 0) {
    Flight *tmp = new Flight(flightNo, rowNo, seatNo);
    listOfFlights = new Flight*[count+1];
    listOfFlights[count] = tmp;
    count++;
} else {
    bool check = true;
    for (int i = 0; i < count && check; i++) {
        if (listOfFlights[i]->getFlightNo() == flightNo) {
            std::cout << "There is already a flight with that flight code" << std::endl;
            check = false;
        }
    }

    if (check) {
        Flight *tmp = new Flight(flightNo, rowNo, seatNo);
        Flight** tmparr = new Flight*[count + 1];

        for (int i = 0; i < count; i++) {
            Flight *f = new Flight(*listOfFlights[i]);
            tmparr[i] = f;
        }

        tmparr[count + 1] = tmp;

        for (int i = 0; i < count; i++) {
            delete listOfFlights[i];
        }

        delete listOfFlights;
        listOfFlights = tmparr;
        count++;
    }


}

}

I also have a showFlight(const int flightCode) method that shows the specific flight:

void ReservationSystem::showFlight(const int flightNo) {
bool check = true;
for (int i = 0; i < count; i++) {
    if (listOfFlights[i]->getFlightNo() == flightNo) {
        std::cout << "Flight " << listOfFlights[i]->getFlightNo() << " has " << listOfFlights[i]->getAvailableSeats()  << " available seats" << std::endl;
        listOfFlights[i]->printSeats();
        check = false;
    }
}

}

This is my default constructor and copy constructor for the Flight class:

Flight::Flight(const int flightNo, const int rowNo, const int seatNo) {
flight = flightNo;
row = rowNo;
seat = seatNo;
available = rowNo * seatNo;
flightPlan = new char*[seatNo];

// initialize the flight plan to all seats available
for(int i = 0; i < seatNo; ++i) flightPlan[i] = new char[rowNo];

for(int i = 0; i < seatNo; ++i) {
    for(int j = 0; j < rowNo; ++j) flightPlan[i][j] = 'o';
}

}

Flight::Flight(const Flight &obj) {
    const int flight = obj.flight;
    const int row = obj.row;
    const int available = obj.available;
    char** flightPlan = obj.flightPlan;

}

But in the line if (listOfFlights[i]->getFlightNo() == flightNo) xcode gives me EXC_BAD_ACCESS error. I think the reason behind this is a malfunction in my addFlight method, because since there is no objects the array points to something null, right? And since it can't reach to getFlightNo() method, it throws this error.

Notice that this is my first time with C++, so I'm a complete n00b and I can be terribly mistaken. Any help would be greatly appreciated.

How compile C++ namespace in g++ without using Object-oriented

I want compile this code with g++ without using Object-oriented

(my mean is that I do not use this std::cout)

method but doesn't compile and i getting error. how can i do that?

my code :

1.cpp :

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

using namespace std;

int main()
{   
 myfunc();
}

1.h :

#include <iostream>
using namespace std;
int myfunc()
{   
 cout << "test";
}

i use this for g++ compile :

g++ -o t2 1.cpp

and run t2 with

sudo ./t2

CPPUNIT: do we really need one function per test?

Consider this CPPUNIT test class meant to do the same test (doTest) but with different arguments:

class MyTest : public CPPUNIT_NS::TestFixture
{
  CPPUNIT_TEST_SUITE( MyTest );
  CPPUNIT_TEST( test1 );
  CPPUNIT_TEST( test2 );
  CPPUNIT_TEST( test3 );
  CPPUNIT_TEST_SUITE_END();

public:
  MyTest();

  void test1() { doTest(1); }
  void test2() { doTest(2); }
  void test3() { doTest(3); }

  void doTest( int param );
};

Is there no way to change that to avoid having to declare test1, test2 and test3, with something like:

class MyTest : public CPPUNIT_NS::TestFixture
{
  CPPUNIT_TEST_SUITE( MyTest );
  CPPUNIT_TEST_PARAM( doTest, 1 ); // CPPUNIT_TEST_PARAM does not exits, it's just to illustrate my need
  CPPUNIT_TEST_PARAM( doTest, 2 ); // CPPUNIT_TEST_PARAM does not exits, it's just to illustrate my need
  CPPUNIT_TEST_PARAM( doTest, 3 ); // CPPUNIT_TEST_PARAM does not exits, it's just to illustrate my need
  CPPUNIT_TEST_SUITE_END();

public:
  MyTest();

  void doTest( int param );
};

Class template specialization oddity

While trying to implement a few things relying on variadic templates, I stumbled accross something I cannot explain. I boiled down the problem to the following code snippet:

template <typename ... Args>
struct A {};

template <template <typename...> class Z, typename T>
struct test;

template <template <typename...> class Z, typename T>
struct test<Z, Z<T>> {
    static void foo() {
        std::cout << "I'm more specialized than the variadic spec, hehe!" << std::endl;
    }
};

template <template <typename...> class Z, typename T, typename ... Args>
struct test<Z, Z<T, Args...>> {
    static void foo() {
        std::cout << "I'm variadic!" << std::endl;
    }
};

int main() {
    test<A, A<int>>::foo();
}

Under gcc, it produces an error because it considers both specializations to be equally specialized when trying to instantiate test<A, A<int>>:

main.cpp: In function 'int main()':

main.cpp:25:24: error: ambiguous template instantiation for 'struct test<A, A<int> >'

         test<A, A<int>>::foo();

                        ^~

main.cpp:11:12: note: candidates are: template<template<class ...> class Z, class T> struct test<Z, Z<T> > [with Z = A; T = int]

     struct test<Z, Z<T>> {

            ^~~~~~~~~~~~~

main.cpp:18:12: note:                 template<template<class ...> class Z, class T, class ... Args> struct test<Z, Z<T, Args ...> > [with Z = A; T = int; Args = {}]

     struct test<Z, Z<T, Args...>> {

However, clang deems the first specialization "more specialized" (through partial ordering?) as it compiles fine and prints:

I'm more specialized than the variadic spec, hehe!

A live demo can be found on Coliru. I also tried using gcc's HEAD version and got the same errors.

My question here is: since these two well-known compilers behave differently, which one is right and is this piece of code correct C++?

Strange behavior between debug and release in Gcc5.3.0

Situation

I use GCC 5.3.0 provided by Mingw on Window 7, and gtest to implement and run unit tests.

In my project, I have a hierarchy of computers, which implements the interface Computer as below :

class Dataset; // Not

// Interface Computer
class Computer {
public:
    // Destructor virtual to enable vmap
    virtual ~Computer() noexcept = default;

    // Pure virtual fonctions
    virtual bool preCompute(Dataset &datas) const = 0;
    virtual void compute(Dataset &datas) const = 0;


};

I provide an abstract implementation of this interface as ChainableComputer, which implements another interface (Chainable) and a default implementation of precompute. See below.

class ChainableComputer : public Computer, public Chainable {
    public:
         bool preCompute(Dataset &dataset) const  override;
};

Those classes are in a namespace, called core, and packaged in core.dll

In another dll, i have implementation of ChainableComputer in another namespace domain.

Some of the implementation are simple, and don't have any thing to do in preCompute, so, they implements compute with the same way :

class SomeComputerImpl  : public ChainableComputer{
/// ...
void compute(Dataset &datas) const override final{
       auto result = preCompute(datas);
       if(!result){
          throw;
       }
}
};

This code was spreading so i decided to refactor and add a protected method in Computer :

class Computer  {
/// ...
protected:
    // Helper function for some implementations of Computer
    void doPrecomputeOrThrow(Dataset &datas) const{
       auto result = preCompute(datas);
       if(!result){
          throw;
       }
    } 
}

I don't wan't this behavior to be the default for computer, but it give me the possibility to change implementation of these computer as below :

class SomeComputerImpl  : public ChainableComputer{
/// ...
void compute(Dataset &datas) const override final{
       doPrecomputeOrThrow(Dataset &datas);
}
};

It compiles and works well in the application and in the unit test... if i compile and run in Release mode.

If I choose Debug, the compiling works, the application work, but the tests don't.

I try to understand what it could happen, but I cannot figure out what could be wrong. I guess it has something to with the linker, and the fact that the interface, an abstract implementation and the concrete implementation are in separates DLL, and that we run this stuff in another executable...

What i already try

  1. Implement a ChainableComputer directly in the test => works as expected
  2. Plays with inline or __attribute__(always_inline) on doPrecomputeOrThrow=> no effect
  3. Implementing doPrecomputeOrThrow in namespace (passing Computer * as argument), in core.dll => no effect
  4. Implementing doPrecomputeOrThrow in namespace (passing Computer * as argument), in domain.dll => works as expected
  5. Implementing doPrecomputeOrThrow as template in class or in namespace, with Computer as template parameter (see below) => works as expected
  6. Implementing doPrecomputeOrThrow as template in class, with Dataset as template parameter (see below) => no effect

    /// Template which works, as member of Computer (static or not), or /// in namespace template void doPrecomputerOrThrows(AComputer * c, Dataset& datas);

    /// Template which doesn't work, as member of Computer template void doPrecomputerOrThrows(ADataset& datas);

The Question

There is someone who have an idea of what happens ?

Is there a way to disable auto declaration for non regular types?

C++11's auto keyword is great.

However in my opinion if a type is Not Regular (see for example, What is a "Regular Type" in the context of move semantics?) the usage of auto becomes tricky.

Is there a way to disable the auto declaration for such type?

Suppose one has a ref class that emulates a reference

double 5.;
ref<double> rd = d; // `ref` behaves like a reference, so it is not a regular type
ref<double> rd2 = rd; // `ref` can be (syntactically) copy constructible, (it is not regular for other reason)
auto r = rd; // now r is not `double`, but worst it is `ref<double>`.

(in real life it would be a more complicated class, the important point is that the class at hand it is not regular.)

The only way I found auto r = rd not to work (give a compile error) is to make the class non copyable, however I need the class to have copy constructor (with a special semantics, but a copy constructor still).

Is there a way to disable a syntax auto r = rd somehow? when decltype(rd) is not regular.

Note: This is not a very artificial problem, one could see that this type of problem is at the core of std::vector<bool>::reference (which is also a reference wrapper). Disabling (somehow) the syntax auto b = v[10] wouldn't solve the problem of std::vector<bool> but it will make bad usage harder.

Am I missing something? Should I change some other part of the design? Should the non-regular classes have a type trait that would help the compiler determine a more general auto (for example deduce bool for auto b = v[10] where std::vector<bool> v.)

C++ Initializing a vector inside a struct definition

I'm reading through Programming Principles and Practice C++, and came across the following piece of code which I don't think was well explained

struct Day {
    vector<double> hour{vector<double>(24,-777) };
};

What is happening here? I usually use this initializer when I need a vector of a certain length with default values:

vector<double> hour(24, -777);

However, way of initializing does not work inside the struct. Looking for an explanation behind the initializers.

I'm using MS Visual Studio 2015

Image processing using OpenCV on OpenGL graphics

As title says, I want to know if there is a way to process graphics using OpenCV created by OpenGL?
I am displaying thousands of points in real-time using OpenGL. Now I want to create clusters for those points and later point-tracking.
I have found this but couldn't understand it well.
Apart from that on this page a guy mentioned "OpenCV generally operates on real image data, and wouldn't operate on graphics generated by OpenGL."
Is it true?

Reading in a new line after cin>> doesn't work

I have problems processing a newline read from stdin:

#include <iostream>
#include <string>
...

using namespace std;

int main() {

    ...

    unsigned int maxelems;

    cout << "Maximal number of elems that can be taken in one move: ";

    if (!(cin >> maxelems)) {

        cout << "Bye!" << endl;
        exit 1;
  }

  string pl1_str;

  cin.ignore();

  cout << "Player 1 (hu=human, ra=random, opt=optimal):" << endl;

  if (!(getline(cin, pl1_str))) {

      cout << "Bye1!" << endl; return 1;

  }

  if(pl1_str =="hu")
        //do smth
    else if(pl1_str =="ra")
        //do smth
    else if(pl1_str=="opt")
       //do smth
    else {
        cout << pl1_str << "Bye2!" << endl; exit 1;
    }

    ...
}

When I run this, the cin on maxelems and the flushing with cin.ignore() works.

When I get to:

Player 1 (hu=human, ra=random, opt=optimal):

and I enter:

hu<Enter>

The end of line seems not to be reached. When I press Enter again:

hu<Enter><Enter>

the application ends with "Bye1!" which is not what I want.

Now if I insert another cin.ignore():

...
cout << "Player 1 (hu=human, ra=random, opt=optimal):" << endl;
cin.ignore();
...

and I enter:

hu<Enter>

the line is processed, but the application terminates with:

u Bye2!

Ok, cin.ignore() cuts of the "h" , but why is the line suddenly processed? How can I assign "hu" to pl1_str?

C++11 Pointers Arrays and Pointers & Pointers to a string

Struggling with Pointers if its not too much to ask can someone run me through this thanks !

1.Consider the method sum, below, which computes the sum of values in an array of ints.

int sum(int a[], int size)
{
 int total = 0;
 for (int i=0; i <size; i++)
 {
 total = total + a[i];
 }
 return total;
}

Now that you know that the int a[] is effectively a pointer, modify the method so that it can accept a pointer to the array a and modify the method body so that it increments the pointer, in the knowledge that a point p initially pointd to a[0].

2."Given the string "A string." Print on a single line to the console, the letter located at the
index 0, the pointer position of this letter and the letter ‘t’ from the String. Update the pointer to pointer +2. Finally, on a separate line, print the pointer and the letters r and g

from the string (using the pointer)."

Ever since getting onto pointers I have been struggling ! is anyone able to help me out ?

Thanks !

Rocksdb background threads are working after deleting db instance

My start up method:

vector<ColumnFamilyDescriptor> columnFamilies = ...
DBOptions dbOptions(options);
std::vector<int32_t> ttls = ...
DBWithTTL* _db;
std::vector<ColumnFamilyHandle*> _handles;
Status status = DBWithTTL::Open(dbOptions, WORKING_DIRECTORY, columnFamilies, &_handles, &_db, ttls, false);

My shutdown method:

for (auto handle : _handles) {
    delete handle;
}
delete _db->GetBaseDB();

But after shutdown is completed, I'm still getting merge requests with stack under rocksdb::DBImpl::BGWorkCompaction(void * arg), which of course fail because all column family handles were disposed of.

How can I mark any compaction or flushing to stop? Deleting db instance doesn't seem to be enough.

mardi 29 novembre 2016

addition on std::atomic

I am trying to perform an addition on a double atomically in a loop using a compare and exchange scheme with this function:

namespace my
{
    template<typename value_type>
    value_type atomic_add(std::atomic<value_type>& operand, value_type value_to_add)
    {
        value_type old = operand.load(std::memory_order_consume);
        value_type desired = old + value_to_add;
        while (!operand.compare_exchange_weak(old, desired, std::memory_order_release, std::memory_order_consume))
            desired = old + value_to_add;

        return desired;
    }
}

This is used in my code like so:

[ size of containers = 62, scalar = 318.0, values in containers between 0.0 and 55.0, all values are of type double ]

for(size_t i = 0; i < container.size(); i++)
{
    my::atomic_add<double>(Q, container2[i] - std::pow(container3[i], 2) / scalar);
}

The output is 0.57784502195324539.

However, replacing all my_atomic with the += operator, and replace all std::atomic<double> with double gives 0.52something, which is closer to what I was expecting.

Any idea why this is happening?

Thank you.

Facing Runtime error in an online judge

program need to show the binary value of a number and total number of 1.

Badly looking for a solution of runtime error.

When I run and test the program with different test cases , it looks good. But , when I submit this code to uva as c++ or c++11 , it shows runtime error. Not only this program, but also some other problems too. Here is the body of one program.

long long int a[100],i,n=0;
    for(i=0; ;i++,n++)
    {
        cin >> a[i];
        if(a[i]==0)
            break;
    }
    for(i=0;i<n;i++)
    {
        long long int r[100],t=0,j=0,one=0;
        while(a[i]!=0) {
            r[j]=a[i]%2;
            a[i]/=2;
            if(r[j]==1)
                one++;
            j++;
            t++;
        }
        for(j=t-1;j>=0;j--)
            cout << r[j];
        cout <<" One's "<< one << endl;

C++ MIneSweeper [on hold]

`Can any one help me complete this . I know this is simple but I don't understand exactly what hey are asking. But the goal is to generatemap, displaymap, and gamewon. Here is the instructions: Complete a partially created MineMopper (OC do not steal) game.

In this game, you will be presented with a 10X10 board containing all Xs The objective is to "dig" / select each spot that is not a mine. When all spots that are not mines are selected, the game is won If a mine is selected, the game is lost.

I have provided much of the code, I want you to complete three functions For each function I have provided a prototype along with some comments describing what I want the function to do. None of these three functions in the solution require more than 10 lines. Those functions to complete are: generateMap displayMap gameWon

You should not need to change any other code, but you may want to change the unit tests to test more comprehensively.

Here is the code given:
#include //cin cout #include //ofstream ifstream #include //srand rand

using namespace std; 

//make sure you use a set seed for this assignment
//that will make the random numbers generated predictable.
//between runs, which makes autograding possible.
//if you were running this for fun, you'd want to use
//a value from time.h's time function
//like:
//int RANDSEED = time(NULL);
const int RANDSEED = 5;
const bool TEST = false;

const float BOMBPROB = 0.1f;

//use these two constants in lieu of passing around
//int size to all the functions that take 
//bool* bombarr
//as an argument.
const int ROWSIZE = 10;
const int MAPSIZE = 100;

void runMain(ostream& outstr, istream& istr);
void runTests();

       **Question 1**
***//TASK1 generateMap***
//this will fill out an array bombarr with 
//a random selection of bombs (true) and not bombs (false)
//for each element in bombarr, which is of length MAPSIZE
//it will be true if the returned value from
//randFloat() is less than the constant BOMBPROB
//this will also fill out the char array charMap 
//also of length MAPSIZE with all capital X characters
//to indicate unknown spots.
void generateMap(bool* bombarr, char* charMap);


    **Question 2**
***//TASK2 displayMap***
//this will iterate through char map, printingzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
//ten members from the array, and then a new line
//this process will be repeated ten times to create a
//ten by ten grid.  You will print out to outstr
//not cout.
void displayMap(char* charMap, ostream& outstr);

//PROVIDED:
//the following function can be used for two purposes simultaneously.
//return:
//   -1 if the user clicked on a bomb.
//   0-8 if the user didn't click on a bomb, depending on how
//   many bombs are nearby.
int clickResult(bool* bombarr, int xloc, int yloc);

This is the 3rd question! //TASK3 gameWon //A game is won if all the not-bomb spaces are //"checked" or "dug" or "selected" //a selected spot will either be a bomb, ending //the game in a separate manner //or it will be a numeric value 0-8. //an unchecked spot will be a 'X' //so if you iterate through both arrays //in common in one for loop //you should look for any location where //a not-bomb is still an 'X' //indicating that the game is still not won //so return false //if all not-bombs are not 'X's //then the game is over and this function should //return true bool gameWon(bool* bombarr, char* charMap);

//returns a random value from 0.0 to 1.0
float randFloat(){
  return static_cast<float>(rand()) / static_cast<float>(RAND_MAX);
}

int main(){
  //don't alter the following line
  //or call srand in your own functions.
  srand(RANDSEED);
  if(TEST){
    runTests();
  }
  else{
    runMain(cout, cin);
  }
}

void runTests(){
  ifstream testinput1;
  ofstream testoutput1;
  testinput1.open("testinput1.txt");
  testoutput1.open("testoutput1.txt");
  runMain(testoutput1, testinput1);
  testinput1.close();
  testoutput1.close();

  ifstream testo;
  ifstream testcheck;
  testo.open("testoutput1.txt");
  testcheck.open("testcheck1.txt");
  string test, check;
  int i = 0;
  bool noerror = true;
  while(testo >> test && testcheck >> check){
    if(test.compare(check) != 0){
      cout << "ERROR on line:" << i << endl;
      noerror = false;
    }
    i++;
  }
  testo.close();
  testcheck.close();
  if(noerror){
    cout << "No Error Found!\n";
  }
}

void runMain(ostream& outstr, istream& instr){
  bool bombarr[MAPSIZE];
  char charMap[MAPSIZE];
  int x,y;
  generateMap(bombarr, charMap);

  while(!gameWon(bombarr, charMap)){
    displayMap(charMap, outstr);
    outstr << "Enter zero based x and y location to dig:";
    instr >> x >> y;
    while(x >= ROWSIZE || y >= ROWSIZE || x < 0 || y < 0){
      outstr << "x,y values must be 0-9 inclusive:";
      instr >> x >> y;
    }
    int r = clickResult(bombarr, x, y);
    if(r == -1){
      outstr << "Game Lost....\n";
      return;
    }
    //else is unnecessary here, do you understand why?

    //char '0' is numeric 48, '1' is 49, etc.
    char numchar = (r + 48);
    //this next line is tricky, understanding it
    //is important, as you will be doing something
    //similar when writing functions.
    *(charMap+(x+ROWSIZE*y)) = numchar;
  }
  outstr << "Game Won!\n";
}

//this might not be the most efficient way to do the following
//i could also picture two nested for loops
//moving from -1 to 1
int clickResult(bool* bombarr, int x, int y){
  if(*(bombarr + (x + ROWSIZE*y))){
    return -1;
  }
  int rval = 0;
  int xl = x - 1;
  int xh = x + 1;
  int yl = y - 1;
  int yh = y + 1;
  if(xl >= 0){
    if(yl >= 0){
      rval += *(bombarr + (xl + ROWSIZE*yl));
    }
    rval += *(bombarr + (xl + ROWSIZE*y));
    if(yh < ROWSIZE){
      rval += *(bombarr + (xl + ROWSIZE*yh));
    }
  }
  if(xh < ROWSIZE){
    if(yl >= 0){
      rval += *(bombarr + (xh + ROWSIZE*yl));
    }
    rval += *(bombarr + (xh + ROWSIZE*y));
    if(yh < ROWSIZE){
      rval += *(bombarr + (xh + ROWSIZE*yh));
    }
  }
  if(yl >= 0){
    rval += *(bombarr + (x + ROWSIZE*yl));
  }
  if(yh < ROWSIZE){
    rval += *(bombarr + (x + ROWSIZE*yh));
  }
  return rval;
}

size of a class object

I have wrritten the following class

class ClientData1
 {
 public:
int accountNumber;

 double balance;
 char lastName[15];
 char firstName[14];
 };
int main()
{
    ClientData1 c;  
cout<<"sizeof( ClientData )"<<sizeof( ClientData1 )<<endl;
cout<<"sizeof( accountNumber  )  =="<<sizeof( c.accountNumber )<<endl;;
cout<<"sizeof( lastName )  =="<<sizeof( c.lastName )<<endl;
cout<<"sizeof( firstName )  =="<<sizeof( c.firstName )<<endl;
cout<<"sizeof( balance )  =="<<sizeof(c.balance )<<endl;

    return 0;
}

the output is 
sizeof( ClientData )=48
sizeof( accountNumber)=4
sizeof( lastName ) =15
sizeof( firstName ) = 14  
sizeof( balance )= 8

But according the fact that size of a class object is the sum of the sizes of all of its data members, size of clientdata should be 41.. why size is 48...plz help

unique_ptr with vector: error: call to implicitly-deleted copy constructor of XXX

I want to manage a two dimensional array as below:

std::vector<std::unique_ptr<int []>> vec(5, nullptr);
vec[0] = std::make_unique<int []>(3);
vec[1] = std::make_unique<int []>(4);
...

However I get an error:

error: call to implicitly-deleted copy constructor of 'std::__1::unique_ptr< int [], std::__1::default_delete< int []> >'

Trying to print out values from an instantiated class in C++. Getting a random value as a result

So I'm doing a lab for one of Microsoft's courses on EDX, and they wanted me to create a class constructor called, "Person", and then instantiate an object using the constructor and print out the values. The issue I'm having, is that when I try to to print out the values, I'm getting the common, "random memory", value that you get when you haven't given a variable any data, and can't figure out why I'm getting this issue. PLEASE help!

Here's the code from my main() function, instantiating and printing out the values.

<pre>
      Person *pPerson = new Person("Bob", "Schwimmer", 49, 57, 201);
      cout << "His name is: " << pPerson->GetFirstName() << " " << pPerson->GetLastName() << endl;
      cout << "He is " << pPerson->GetAge() << endl;
      cout << "He weighs (in lbs) " << pPerson->GetWeight() << endl;
      cout << "He is " << pPerson->GetHeight() << " feet tall." << endl;
<code>

And here's my class constructor:

    class Person
{
private:
    string firstName;
    string lastName;
    int age;
    int height;
    int weight;


public: Person(string fName, string lName, int age, int height, int weight) { fName = firstName; lName = lastName; age = age; height = height; weight = weight; } ~Person() { cout << "Deconstructor has been called" << endl; } string GetFirstName() { return this->firstName; }; string GetLastName() { return this->lastName; }; int GetAge() { return this->age; }; int GetHeight() { return this->height; }; int GetWeight() { return this->weight; }; void SetFirstName(string fName) { fName = this->firstName; };

};

cmake: why doesn't CMAKE_CXX_STANDARD seem to work here?

Here's an MCVE:

Project(Test)
cmake_minimum_required(VERSION 3.1)

include(CheckCXXSourceCompiles)

set (CMAKE_CXX_FLAGS "-std=c++11 ${CMAKE_CXX_FLAGS}")
#set (CMAKE_CXX_STANDARD_REQUIRED TRUE)
#set (CMAKE_CXX_STANDARD 11)
#set (CMAKE_CXX_EXTENSIONS FALSE)

check_cxx_source_compiles("
#include <atomic>

int main() {
  std::atomic<int> u{5};
  return u;
}" HAVE_STDLIB_ATOMIC)

if (NOT HAVE_STDLIB_ATOMIC)
  message(FATAL_ERROR "Did not find std::atomic support!")
endif()

When I use the CMAKE_CXX_FLAGS version, it works fine, but when I use the new CMAKE_CXX_STANDARD flags which we are supposed to use now, it doesn't work, I get the following build errors:

$ cmake ..
-- The C compiler identification is GNU 5.4.1
-- The CXX compiler identification is GNU 5.4.1
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Performing Test HAVE_STDLIB_ATOMIC
-- Performing Test HAVE_STDLIB_ATOMIC - Failed
CMake Error at CMakeLists.txt:20 (message):
  Did not find std::atomic support!


-- Configuring incomplete, errors occurred!
See also "/home/chris/cmake_test/build/CMakeFiles/CMakeOutput.log".
See also "/home/chris/cmake_test/build/CMakeFiles/CMakeError.log".

The error log indicates it's not using the -std=c++11 flag:

$ cat /home/chris/cmake_test/build/CMakeFiles/CMakeError.log 
Performing C++ SOURCE FILE Test HAVE_STDLIB_ATOMIC failed with the following output:
Change Dir: /home/chris/cmake_test/build/CMakeFiles/CMakeTmp

Run Build Command:"/usr/bin/make" "cmTC_42a05/fast"
/usr/bin/make -f CMakeFiles/cmTC_42a05.dir/build.make CMakeFiles/cmTC_42a05.dir/build
make[1]: Entering directory '/home/chris/cmake_test/build/CMakeFiles/CMakeTmp'
Building CXX object CMakeFiles/cmTC_42a05.dir/src.cxx.o
/usr/bin/c++     -DHAVE_STDLIB_ATOMIC   -o CMakeFiles/cmTC_42a05.dir/src.cxx.o -c /home/chris/cmake_test/build/CMakeFiles/CMakeTmp/src.cxx
In file included from /usr/include/c++/5/atomic:38:0,
                 from /home/chris/cmake_test/build/CMakeFiles/CMakeTmp/src.cxx:2:
/usr/include/c++/5/bits/c++0x_warning.h:32:2: error: #error This file requires compiler and library support for the ISO C++ 2011 standard. This support must be enabled with the -std=c++11 or -std=gnu++11 compiler options.
 #error This file requires compiler and library support \
  ^
/home/chris/cmake_test/build/CMakeFiles/CMakeTmp/src.cxx: In function ‘int main()’:
/home/chris/cmake_test/build/CMakeFiles/CMakeTmp/src.cxx:5:3: error: ‘atomic’ is not a member of ‘std’
   std::atomic<int> u{5};
   ^
/home/chris/cmake_test/build/CMakeFiles/CMakeTmp/src.cxx:5:15: error: expected primary-expression before ‘int’
   std::atomic<int> u{5};
               ^
/home/chris/cmake_test/build/CMakeFiles/CMakeTmp/src.cxx:6:10: error: ‘u’ was not declared in this scope
   return u;
          ^
CMakeFiles/cmTC_42a05.dir/build.make:65: recipe for target 'CMakeFiles/cmTC_42a05.dir/src.cxx.o' failed
make[1]: *** [CMakeFiles/cmTC_42a05.dir/src.cxx.o] Error 1
make[1]: Leaving directory '/home/chris/cmake_test/build/CMakeFiles/CMakeTmp'
Makefile:126: recipe for target 'cmTC_42a05/fast' failed
make: *** [cmTC_42a05/fast] Error 2

Source file was:

#include <atomic>

int main() {
  std::atomic<int> u{5};
  return u;
}

My cmake version is:

$ cmake --version
cmake version 3.5.1

CMake suite maintained and supported by Kitware (kitware.com/cmake).

I can't figure out why cmake doesn't use the std=c++11 flag here, according to the docu, CMAKE_CXX_STANDARD is supposed to work since version 3.1.

Anyone know what's wrong here?

C++11 issue with GTest

I am writing unit tests for an application. I have some exceptions in a constructor, so I wrote this:

TEST(Tablier, ConstructeurParamInvalide2)
{
    ASSERT_THROW(Tablier t_tablier{10, 65} , PreconditionException);
}

When I write this, it seems the macro ASSERT_THROW is not satisfied and the test fails. Here is the macro expansion:

switch (0) case 0: default: \
  if (::testing::internal::ConstCharPtr gtest_msg = "") { \
    bool gtest_caught_expected = false; \
    try { \
      if (::testing::internal::AlwaysTrue()) { Tablier t_tablier{10; }; \
    } \
    catch (65} const&) { \
      gtest_caught_expected = true; \
    } \
    catch (...) { \
      gtest_msg.value = \
          "Expected: " "Tablier t_tablier{10" " throws an exception of type " \
          "65}" ".\n  Actual: it throws a different type."; \
      goto gtest_label_testthrow_76; \
    } \
    if (!gtest_caught_expected) { \
      gtest_msg.value = \
          "Expected: " "Tablier t_tablier{10" " throws an exception of type " \
          "65}" ".\n  Actual: it throws nothing."; \
      goto gtest_label_testthrow_76; \
    } \
  } else \
    gtest_label_testthrow_76: \
      return ::testing::internal::AssertHelper(::testing::TestPartResult::kFatalFailure, "/home/eric/Programming/cpp/Puissance4/pxTestsUnitaires/tests/test_Tablier.cpp", 76, gtest_msg.value) \
    = ::testing::Message()

Notice the Tablier t_tablier{10; }; Instead, if I write this:

TEST(Tablier, ConstructeurParamInvalide2)
{
    ASSERT_THROW(Tablier t_tablier(10, 65) , PreconditionException);
}

The macro works fine and the test passes. My project and compiler are configured for C++11, and many other tests pass using C++11 syntax. Any idea what could be the issue?

Regards

How do const references as return values work in C++

I am learning C++ again after a while and have a problem understanding const references as return values. So here is what I've got: a class, Foo, which holds a std::list as member:

class Foo
{
    std::list<int> mList;
    Foo() { mList.insert(mList.end(), { 1, 2, 3 }); }
    size_t size() const { return mList.size(); }
};

Creating a foo object from class Foo and calling foo.size() returns 3, which is fine. Now I want to retrieve this list mList, with two requirements:

  • I don't want to allow the caller to modify the original list; and
  • I don't want to create a copy of each list member when retrieving the list.

So after reading a bit on this topic I decided to return a const reference to the list. Thus I added the following method to Foo:

const std::list<int>& getList() const { return mList; }

What I expected was that this would return a reference to the list mList, so that I can access the original data within this list. But since it's a const reference, I also expected that I would not be able to modify the returned list/reference.

However, playing with this a bit I found out the following:

Foo foo;
cout << foo.size() << endl;  // returns 3
std::list<int> l = foo.getList();
l.clear();
cout << foo.size() << endl;  // returns 3 again

Now this surprises me and leeds me to two questions:

  1. Since the 2nd cout returns 3 again, the call to clear() obviously does not modify the original foo.mList object. But why is that the case if I returned a reference? Is there a copy happening during the return?
  2. Why am I allowed to call l.clear() in the first place, if I have received a const (!) reference?

QTableWidget get vertical header label

In the code below:

setCentralWidget(&tableWidget);
tableWidget.setRowCount(5);
qDebug() << tableWidget.verticalHeaderItem(1)->text();

Why don't I get the text lable as output?

Call template function with non-type parameters explicit and type parameters implicit

I want to create a template function that has both type template parameters, which can be deduced from the parameters passed to the function, and non-type template parameters, that will be placed explicitly. It seems like the compiler can deduce what each type is, but if I specify the non-type template parameter it wants all the template parameters. Can I specify just the non-type template parameters, or is it an all or nothing deal?

#include <iostream>
#include <typeinfo>

template <typename T, bool bPrint=true>
void f(T var) {
  if (bPrint)
    std::cout <<  typeid(var).name() << std::endl;
}

int main() {
  f(3); //works
  f<false>(3); //error: template argument deduction/substitution failed
}

reinterpret_cast creating a trivially default-constructible object

cppreference states that:

Objects with trivial default constructors can be created by using reinterpret_cast on any suitably aligned storage, e.g. on memory allocated with std::malloc.

This implies that the following is well-defined code:

struct X { int x; };
alignas(X) char buffer[sizeof(X)];    // (A)
reinterpret_cast<X*>(buffer)->x = 42; // (B)

Three questions follow:

  1. Is that quote correct?
  2. If yes, at what point does the lifetime of the X begin? If on line (B), is it the cast itself that is considered acquiring storage? If on line (A), what if there were a branch between (A) and (B) that would conditionally construct an X or some other pod, Y?
  3. Does anything change between C++11 and C++1z in this regard?

Facing error in running the programming

I am trying to run this program, taking vertices of a triangle as inputs. But i am facing errors. Can someone help me with this ?

What I am trying to do create a point class, inherit in a triangle class and accept the vertices of triangle as inputs.

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

#Defines a class Point.
class Point
{
    private:
        float x;
        float y;
    public:
        int read_Point(Point &P)
        {   
            std::cin >> P.x >> P.y;
        }
};

#Defines a class Triangle
class Triangle : public Point
{
    private:
        std::vector<Point> P;
    public:
        int make_triangle()
        {
            P=std::vector<Point>(3);
            read_Traingle();
            return 0;
        }
        void read_Traingle()
        {
            read_Point(P[1]);
            read_Point(P[2]);
            read_Point(P[3]);
        }
};

int main()
{
    Triangle Tri;
    Tri.make_triangle();
    return 0;
}

Can I EnterCriticalSection(s) in thread A then LeaveCriticalSection(s) in thread B?

So i have SEND_SLOT struct:

struct SEND_SLOT
{
    SEND_BUFFER buffer;
    uint16 index;
    CRITICAL_SECTION slotLock;
};

and a connexion struct:

struct connexion
{
    ...
    SEND_SLOT sendSlots[3];
    ...
}

and in thread A i do:

if(TryEnterCriticalSection(&sendSlots[i]))
{  //Post send request...
   WSASend(...);
}

and in thread B i do:

while(...)
{
   ...
   //request finished, data sent, and i get the index to the SEND_SLOT
   LeaveCriticalSection(&sendSlots[index]);
   ...
}

So i'm trying to lock the SEND_SLOT i in thread A and later i want to unlock it, maybe from and other thread, but its not working, each time i try to post new send it locks the first slot even if it hash already been locked and no LeaveCriticalSection has been issued. WHY?

using-declaration for friend function

In C++11 it is possible to make a public member of a private base class accessible to the outside (public) with a using declaration. For example

class A {
private:
    int i = 2;
public:
    void f() { i = 3; }

    friend bool operator==(const A& l, const A& r) { return l.i == r.i; }
};

class B : private A {
public:
    using A::f;
};

int main() {
    B b, b2;
    b.f();
}

b.f() is possible because of the using A::f in the definition of B.

Is it possible write a similar declaration which would make the up-cast from B& to A& possible for the friend function operator==(A&, A&), so that b == b2 can be called in main()?

vector of Base unique_ptr to derive

I am trying below code to create a vector of Base class and dynamically allocate of derived class.

#include <memory>
#include <vector>
#include <iostream>
#include <algorithm>

class Base {

public:
  Base(int value) : item(value) {}
  int item;
};

class Derived : public Base {

public:
  Derived() : Base(0) {}
};

class Fac {
public:
  int count;
  std::vector<std::unique_ptr<Base>> m_BaseObj;

  void add(int data) {
    count++;
    m_BaseObj.push_back(std::unique_ptr<Base>(new Derived()));
    int index = (m_BaseObj.size() - 1);
    std::cout << "Index=" << index << std::endl;
    m_BaseObj[index].get()->item = data;
  }

  void display() {
    for (auto &Obj : m_BaseObj) {
      std::cout << Obj.get()->item << "  ";
    }
    std::cout << std::endl;
  }
  void deleteList() {
    int it;
    std::cout << "Enter item to delete:";
    std::cin >> it;
    int index = 0;
    m_BaseObj.erase(std::remove_if(m_BaseObj.begin(), m_BaseObj.end(),
                                   [it](const std::unique_ptr<Derived> &e) {
                                     return it == e->item;
                                   }),
                    m_BaseObj.end());
  }
};

int main() {
  Fac obj;
  int ch;
  obj.count = 0;
  while (1) {
    std::cout << "1. Add  2. Remove 3. Display\n";
    std::cin >> ch;
    switch (ch) {
    case 1:
      int data;
      std::cout << "Data: ";
      std::cin >> data;
      obj.add(data);
      obj.display();
      break;
    case 2:
      obj.deleteList();
      obj.display();
      break;
    case 3:
      obj.display();
      break;
    default:
      std::cout << "Invalid choice\n";
      exit(0);
    }
  }
}

Here is the compile error while allocating for derive class. If I create for Derive than the code seems to work correctly.

    In file included from /usr/include/c++/4.8/algorithm:62:0,
                 from vector.cpp:4:
/usr/include/c++/4.8/bits/stl_algo.h: In instantiation of â_FIter std::remove_if(_FIter, _FIter, _Predicate) [with _FIter = __gnu_cxx::__normal_iterator<std::unique_ptr<Base>*, std::vector<std::unique_ptr<Base> > >; _Predicate = Fac::deleteList()::__lambda0]â:
vector.cpp:53:64:   required from here
/usr/include/c++/4.8/bits/stl_algo.h:1150:33: error: no match for call to â(Fac::deleteList()::__lambda0) (std::unique_ptr<Base>&)â
         if(!bool(__pred(*__first)))
                                 ^
vector.cpp:52:48: note: candidate is:
         m_BaseObj.begin(), m_BaseObj.end(), [it](const std::unique_ptr<Derived>& e)
                                                ^
vector.cpp:52:83: note: Fac::deleteList()::__lambda0
         m_BaseObj.begin(), m_BaseObj.end(), [it](const std::unique_ptr<Derived>& e)

Is this a good way of using std::shared_ptr

Can this code be considered good design?

It compiles and works fine, both with GCC and Visual Studio. The slot object ends up really small, neatly packed and easy to reason about.

However, how much the casting will slow down my program in the end?

If I ended up using boost::any or boost::variant I would still put them in a std::shared_ptr because I do need it to be a smart pointer.

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

using std::cout;
using std::endl;

enum class slot_t {
    number_t,
    string_t
};

class slot {
public:
    slot_t type;
    std::shared_ptr<void> data;
    slot(slot_t const p_type, double long const & p_data)
        : type {p_type}
        , data {std::make_shared<double long>(p_data)}
    {}
    slot(slot_t const p_type, std::string const & p_data)
        : type {p_type}
        , data {std::make_shared<std::string>(p_data)}
    {}
    std::string get_type() const {
        std::ostringstream output;
        switch (type) {
            case slot_t::string_t: output << "String: " << as<std::string>(); break;
            case slot_t::number_t: output << "Number: " << as<double long>(); break;
        }
        return output.str();
    }
    template <typename t>
    t as() const {
        return *std::static_pointer_cast<t>(data);
    }
};

int main() {
    slot hello {slot_t::number_t, 123};
    slot world {slot_t::string_t, "Hello, world!"};

    cout << hello.as<double long>() << endl;
    cout << world.as<std::string>() << endl;

    cout << hello.get_type() << endl;
    cout << world.get_type() << endl;
    return 0;
}

In C++11 is there anyway to get the general template class from a template class with specified template arguments?

(e.g. get std::list from std::list<some_value_type>)

Consider the following code:

#include <list>
#include <string>

std::string combine(int val, std::string str)
{
    return std::to_string(val) + str;
}

template <class T, class U>
auto foo(const T &container, const U &val)
    -> std::list<U>
{
    using RetType = std::list<U>;
    RetType result;

    for(auto item : container) {
        result.push_back(combine(item, val));
    }

    return result;
}

int main()
{
    std::list<int> numbers = {1, 2, 3, 4, 5};
    std::list<std::string> result = foo(numbers, std::string(" potato"));
    return 0;
}

This compiles, but I want it to work differently. I'd like foo to return the same kind of container as was passed into its first argument, but with its value type changed to that of the second argument, i.e. type U.

So if foo is passed in std::list<int> as its first argument and std::string as its second argument, it returns std::list<std::string>. Alternatively, if foo is passed in std::vector<int> as its first argument and std::string as its second argument, it returns std:: vector<std::string>. And so on.

Basically I want to replace both instances of std::list<U> with something that accomplishes the above, possibly using the facilities of <type_traits>.

Is there anyway to do this in C++11? The only solution I've found is to create overloaded versions of foo for every container type I want to use, but I'd much prefer if there was a general way to do it that covered all container types.

QTableWidget vertical header show specific column contents

I would like the vertical header of the QTableWidget presenting the contents of a specific column, let's say 1st or 2nd.

Should I insert the same values in the header? Or, may be, is there some trick to show a column as a header?

After all I would like to lock the vertical header (first column) while scrolling to right side.

How do I make Visual Studio display "auto" types

So, when I use auto keyword in VS2015 with something simple, like this:

As you can see, it shows the variable's type, but, when I try something a bit more complex (or defined in another file?), it freaks out and gives me some not-so-useful information:

Although VS is still able to determine top's type:

So, I wonder if there is a way to make this wonderful IDE show those complex/defined somewhere else types?

"Splitting" a matrix in constant time

I am trying to implement Strassen's algorithm for matrix multiplication in C++, and I want to find a way to split two matrices into four parts each in constant time. Here is the current way I am doing so:

for(int i = 0; i < n; i++){
    for(int j = 0; j < n; j++){
        A11[i][j] = a[i][j];
        A12[i][j] = a[i][j+n];
        A21[i][j] = a[i+n][j];
        A22[i][j] = a[i+n][j+n];
        B11[i][j] = b[i][j];
        B12[i][j] = b[i][j+n];
        B21[i][j] = b[i+n][j];
        B22[i][j] = b[i+n][j+n];
    }
}

This approach is obviously O(n^2), and it adds n^2*log(n) to the runtime, as it is called for each recursive call.

It seems that the way to do this in constant time is to create pointers to the four sub-matrices, rather than copy over the values, but I am having a difficult time figuring out how to create those pointers. Any help would be appreciated.

In c++ how do I successfully chain classes together while sharing variables in the following example?

In c++ how do I successfully chain classes together while sharing variables in the following example?

Clock timer;

std::cout << timer.getElapsedTime().inSeconds();
std::cout << timer.getElapsedTime().inMilliseconds();

If I try to compile I get 'start' not declared in this scope. If I try to inherit class Clock with: ' class ElapsedTime: public Clock ' I get Error expected class name before '{' token.

How do I write the code successfully?

class ElapsedTime
{
    double inSeconds() const
    {
        return (std::clock() - start) / (double) CLOCKS_PER_SEC);
    }

    double inMilliseconds() const
    {
        return ((std::clock() - start) / (double) CLOCKS_PER_SEC) * 1000;
    }
};


class Clock
{
public:

    Clock()
    {
        start = std::clock();
    }

    ElapsedTime const & getElapsedTime() const {
        return ???object_here;
    }

    double reset()
    {
        duration = (std::clock() - start ) / (double) CLOCKS_PER_SEC;
        start = std::clock();
        return duration;
    }

protected:
    std::clock_t start;

private:
    double duration;

};

Template specialization for T and function-object that returns T

Is there any way to template a function so that it can accept either a T in the generic case, or to a specialization if the template argument resolves to something that is callable, such as a functor, function pointer or std::function?
For example, I would want something like this:

template<typename T>
void use_this(T obj) {
  obj->do_stuff();
}

template<>
void use_this<???>(??? func) {
  use_this(func());
}

use_this(MyObj); // should call first one
use_this([MyObj](){ return MyObj; }); // should call the second one

standard c++ for test_and_set_bit

I am trying to use the highest bit(it is unused) as a lock for each element in an array so I can compress the memory to the fullest.

The test_and_set_bit of linux kernel looks promising, but I want to make it platform unrelated. And to now, I find the best way to achieve this is gcc __sync_fetch_and_OP.

Is there a more elegant way to achieve this? Thanks in advance. :-)

How I can use std::bind to bind class member function as function pointer?

I have Base and Dervided classes. In the Base class I have a typedef for specific function pointer (I think this is function pointer, im not sure):

typedef void (responseHandler)(BaseClass* instance,int resultCode, char* resultString);

And in the same base class I have several function which accepts this typedef:

unsigned sendDescribeCommand(responseHandler* responseHandler, Authenticator* authenticator = NULL);

In my custom derived class from this Base class I have my response handler function, like this:

void continueAfterDESCRIBE(RTSPClient* rtspClient, int resultCode, char* resultString);

How I can use this method as input for sendDescribeCommand? I tried this: DerivedClass->sendDescribeCommand(DerivedCLass->continueAfterDescribe, MyAuth), but this did not build with error: "error C3867: 'DerivedClass::continueAfterDESCRIBE': non-standard syntax; use '&' to create a pointer to member"

I also tried to use std::bind:

auto responseCallback = std::bind(&DerivedClass::continueAfterDESCRIBE, DerivedClassInstance); DerivedClass->sendDescribeCommand(responseCallback, ourAuthenticator); It also give me an error: no suitable conversion from std::bind to my response handler.

I know there is a way to make my method static, but Im curious if there is another way?

C++ meta function that determines if a type is callable for supplied arguments

I am trying to implement a C++ template meta function that determines if a type is callable from the method input arguments.

i.e. for a function void foo(double, double) the meta function would return true for callable_t<foo, double, double>, true for callable_t<foo, int, int> (due to compiler doing implicit cast) and false for anything else such as wrong number of arguments callable_t<foo, double>.

My attempt is as follows, however it fails for any function that returns anything other than void and I can't seem to fix it.

I am new to template reprogramming so any help would be appreciated.

#include <iostream>
#include <type_traits>
#include <utility>
#include <functional>

namespace impl
{

template <typename...>
struct callable_args
{
};

template <class F, class Args, class = void>
struct callable : std::false_type
{
};

template <class F, class... Args>
struct callable<F, callable_args<Args...>, std::result_of_t<F(Args...)>> : std::true_type
{
};

}

template <class F, class... Args>
struct callable : impl::callable<F, impl::callable_args<Args...>>
{
};

template <class F, class... Args>
constexpr auto callable_v = callable<F, Args...>::value;


int main()
{
    {
        using Func = std::function<void()>;
        auto result = callable_v<Func>;
        std::cout << "test 1 (should be 1) = " << result << std::endl;
    }

    {
        using Func = std::function<void(int)>;
        auto result = callable_v<Func, int>;
        std::cout << "test 2 (should be 1) = " << result << std::endl;
    }

    {
        using Func = std::function<int(int)>;
        auto result = callable_v<Func, int>;
        std::cout << "test 3 (should be 1) = " << result << std::endl;
    }

    std::getchar();

    return EXIT_SUCCESS;
}

I am using a compiler that supports C++ 14.

In c++ what do you call a member function that follows a member function and how do I write one?

In c++ what do you call function that follows a member function and modifies the return value and how do I write one?

In other words how do I successfully write:

std::cout << box.getVolume().inCubicFeet();

std::cout << box.getVolume().inCubicCentimeters();

Iterator in permutation value order

I have a simple struct for permutation:

struct Permutation
{
   vector<string> items; // ["val_0", "val_1", "val_2", "val_3", "val_4"]
   vector<short> permutationValue;  // Let's say value is [4, 2, 0, 1, 3]
}

I want to be able to use it in range loop, like that

for(string item: permutation){
{ 
    cout << item << endl;
}

end expected output should be:

val_4
val_2
val_0
val_1
val_3

What methods should I implement in Permutation class to achive it?

SDL2 Android - Build with LLVM/Clang

I am trying to port an application on android, and major parts of the source are written in c++11 so I need to build the source with LLVM/clang instead of GCC, because GCC 4.6 which is the last supported version has a bug and doesn't support major features.

Is there a known problem with SDL2 on android and LLVM/Clang?

Is there a workaround?

pre-increment vs post-increment on std::atomic

The common rule of thumb is to prefer using pre-increment on STL iterators in cases where the value is not immediately evaluated (i.e. you just want to increment the object/iterator). This is because in general the implementation of pre-increment is more efficient than post increment.

But what about std::atomic? If I run static analysis (using PVS studio) I get a warning saying that pre-increment should be more efficient, but when I look at the implementation of pre-increment (on Visual Studio 2015) it looks less efficient than post-increment?

Is there a general rule for using pre-increment over post-increment on STL atomic values or would it be implementation specific?

How to store a const char* [] in std :: string?

const char * tag1[]={"abc","xyz"};

how to convert tag1 in std::string?

std::string tag2(tag1)

it simply copies tag1[0] to tag2.

Any ideas or workaround?

Does c++11 lambda really support closure? There's a semantic conflict in function variable

I personally feel that C++11 lambda has some conflict with C/C++ function in that, a function local variable's life ends with function, but in FP, lambda is an object thus its variables has life cycle as long as the lambda.

I've got a small test

#include<stdio.h>
int main()
{
  auto f=[](int input){
    int local=3;
    return [=](int x){return input+local+x;};
  };
  auto f1=f(3);
  auto f2=f(4);

  printf("%d,%d\n",f1(2),f2(2));
  return 0;
}

g++ -std=c++11, it prints "8,9"

It's my expectation for FP, but for C language scope, its behavior should be "undefined", because both "input" and "local" dies after the "f" declaration.

So question:

For both input parameter and internal variable, does lambda object store them somewhere to make sure, they are still available after lambda definition? Or my test is undefined behavior?

Thanks.

lundi 28 novembre 2016

Will there be any leak in below C++ shared_ptr usage?

Will the memory allocation covered by smart pointer is guaranteed to be freed up in event of an exception thrown such as below? I tried executing the code putting breakpoint at shared_ptr destructor but i did not see it getting called. I think the memory should be cleaned up by itself. Am i right or it wont be cleaned up?

void test(std::shared_ptr<int> sptr)
{
    throw "exception";
}
int main()
{
    std::shared_ptr<int> ptr(new int(1));
    test();
}

Getting errors trying to return a 2D array from a function [duplicate]

This question already has an answer here:

I'm working on a program to find pathways in undirected graphs, and I'm using a specific function to return a 2D array of ints. The problem is, though, that I can't figure out how to make one of the dimensions' size determined at run time. When I try to leave the function declaration as

int prim(int in[][3], int nsteps, int nedges);

I get this error:

error: incompatible types in assignment of ‘int’ to ‘int [(((sizetype)(((ssizetype)(nvertex + -1)) + -1)) + 1)][3]’
     ov = prim(v, nvertex-1, nedge);

Changing it to

int prim[][3](int in[][3], int nsteps, int nedges);

gives me this error instead:

p5.cpp:23:4: error: expected unqualified-id before ‘[’ token
int[][3] prim(int in[][3], int nsteps, int nedges);
   ^

I can't figure out for the life of me how to get this to work. I'd appreciate some help. Here's relevant snippets of the code:

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

int crimMin(int in[][3], int nsteps, int nedges);

int crimMax(int in[][3], int nsteps, int nedges);

int prim(int in[][3], int nsteps, int nedges);

int main(int argc, char** argv){

Skipped most of main, this is the relevant portion

else if (x == cmax){
for (i = 0; i < nvertex-1; i++){
    if (v[i][2] == 1) v[i][2] = 0;
    else if (v[i][2] == 0) v[i][2] = 1;
}
ov = prim(v, nvertex-1, nedge);
for (i = 0; i < nvertex-1; i++){
    if (ov[i][2] == 1) ov[i][2] = 0;
    else if (ov[i][2] == 0) ov[i][2] = 1;
}
for (i = 0; i < nvertex-1; i++){
    cout << ov[i][0] << " " << ov[i][1] << " ";
    if (ov[i][2] == 1) cout << "C" << endl;
    else if (ov[i][2] == 0) cout << "W" << endl;
}
return 0;

Then later down at my definition...

int prim(int in[][3], int nsteps, int nedges){
    int step = 0, curr = 0;
    int i;
    int out[nsteps][3];
    int unvisited[nsteps];
    for (i = 0; i < nsteps; i++) unvisited[i] = 1;{
    //Building the output...
    }
    return out;
}

Add members of initializer_list to std::list in C++

I know that one can initialize a std::list from an initializer_list in a constructor, like so:

class Foo
{
    std::list<int> list;
    Foo(std::initializer_list<int> init)
    {
        list = init;
    }
};

However, is there also a way to later add all elements of an initializer_list to the list, without creating a new list object, and without using a loop or iterator? So in other words: Can I use a member function of std::list directly? I tried with insert(), but failed because of invalid parameter types.

So in my example above I am looking for something like this:

list.insert(init);  // or something similar

Any ideas?

Is there a recommended way to test if a smart pointer is null?

I'm trying to check if a std::shared_ptr is null. Is there a difference between doing

std::shared_ptr<int> p;
if (!p) { // method 1 }
if (p == nullptr) { // method 2 }

How do you typedef a function pointer type with parameter pack arguments

What's the syntax to typdef a parameter pack into a function pointer?

I want to be able to typedef a function pointer, but the compiler complains when I do something like this

template< class ...Args >
struct method { typedef typename void(*type)(void*, Args...); };

with a message along the lines of error: expected nested-name-specifier before 'void'

`std::unordered_map

I have

std::unordered_map<std::string, std::shared_ptr<ClassA>> symbolTable = std::unordered_map<std::string, std::shared_ptr<ClassA>>();

void setVariable(std::string variableName, std::shared_ptr<TypeStruct> value) {
    symbolTable.insert(std::make_pair(variableName, value));
}

But I get

EXC_BAD_ACCESS (code=EXC_I386_GPFLT)

When I try to use this. Any thoughts as to why? Is there a problem with pushing std::shared_ptr into the map?

Universal Reference: Cannot convert parameter from 'int' to 'int &&'

I am running all code below in VS 2015 Community Edition.

I am getting error in my code when I attempt to implement a suggestion that was suggested to me in Code Review. The part that I am having trouble with is changing the arguments to TryPush to be TryPush(T&& val).

#pragma once

#include <atomic>
#include <memory>


template <typename T> class RingBuffer {
public:

   /*
   Other functions
   */

    void Push(T val) {
        while (!TryPush(val));
    }

private:

   /*
   Other functions
   */

    //Private Member Functions
    bool TryPush(T && val) {
        const std::size_t current_write = write_position.load(std::memory_order_acquire);
        const std::size_t current_read = read_position.load(std::memory_order_acquire);
        const std::size_t next_write = increment_index(current_write);

        if (next_write == current_read) { return false; }

        _ring_buffer_array[current_write] = std::move(val);
        write_position.store(next_write, std::memory_order_release);

        return true;
    }

    std::size_t increment_index(std::size_t index) {
        return (index + 1) % _buffer_capacity;
    }

    //Private Member Variables
    std::atomic<std::size_t> read_position = 0;
    std::atomic<std::size_t> write_position = 0;

    std::size_t _buffer_capacity;
    std::unique_ptr<T[], RingBufferFree> _ring_buffer_array;
};

Whenever I attempt to compile this code I get the following error bool RingBuffer::TryPush(T &&)': cannot convert argument 1 from 'int' to 'int &&. What confuses me is that if change the code to

#pragma once

#include <atomic>
#include <memory>


template <typename T> class RingBuffer {
public:

   /*
   Other functions
   */

    void Push(T && val) {
        while (!TryPush(val));
    }

private:

   /*
   Other functions
   */

    //Private Member Functions
    bool TryPush(T val) {
        const std::size_t current_write = write_position.load(std::memory_order_acquire);
        const std::size_t current_read = read_position.load(std::memory_order_acquire);
        const std::size_t next_write = increment_index(current_write);

        if (next_write == current_read) { return false; }

        _ring_buffer_array[current_write] = std::move(val);
        write_position.store(next_write, std::memory_order_release);

        return true;
    }

    std::size_t increment_index(std::size_t index) {
        return (index + 1) % _buffer_capacity;
    }

    //Private Member Variables
    std::atomic<std::size_t> read_position = 0;
    std::atomic<std::size_t> write_position = 0;

    std::size_t _buffer_capacity;
    std::unique_ptr<T[], RingBufferFree> _ring_buffer_array;
};

It compiles and runs. I was under the impressions from Scott Meyer's blog post that TryPush(T && val) is a Universal reference and I should be able to use it as is shown in the first code snippet and then move the value into the array thus ensuring the code works regardless of whether an lvalue or rvalue is passed into the function. It seems to work if it the public facing Push method and thus I am sort of confused as to what is going on. I must be missing something here and was wondering if anybody could clarify what exactly it is. Thanks.

How can I make standalone cpp files in Visual Studio 2015 Community Edition?

Everytime I have to make a new cpp file first I make a new project then add a main.cpp file in source files. Is there a more efficient way like making a new empty file and saving it directly as .cpp?

Compilation failure when deducing the return type of an auto function in an unevaluated context

I have some machinery get_return_type that can be used in an unevaluated context to deduce the return type of a function without needing to supply the argument types:

template <typename Result, typename... Args>
Result get_return_type(Result (*)(Args...));

int example(double, char, bool);

// will be int
using result_type = decltype(get_return_type(example));

However if the function is a template, and its return type is auto, all version of GCC I've tried fail to compile. Clang works perfectly.

namespace TemplatedFunctionReturningAutoTest
{
    template <typename T>
    auto foo(T v) { return v; }

    // GCC complains that Result type cannot be deduced in
    // template substitution of get_return_type
    static_assert(std::is_same<int, decltype(get_return_type(foo<int>))>::value, "");
}

Here it is on godbolt (gcc 6.2): http://ift.tt/2fFGd4A

If you switch to clang 3.x it works fine! It feels like GCC is reluctant to instantiate the body of the function to figure out its return type.

Is this a GCC bug, or is there something in the standard that prevents this from working?

undefined reference to... terminal error, doesn't excise in eclipse

i have this code attached. when I compile and run it with eclipse, it has no problems. but in terminal, with my makeFile (attached) it gives me this error:

bin/FigureCard.o: In function `FigureCard::FigureCard(Shape const&, Figure const&)':
/home/shaike131/workspace/check/src/FigureCard.cpp:16: undefined reference to `Card::Card(Shape)'

bin/FigureCard.o: In function `FigureCard::FigureCard(FigureCard&)':
/home/shaike131/workspace/check/src/FigureCard.cpp:18: undefined reference to `Card::getShape2()'

/home/shaike131/workspace/check/src/FigureCard.cpp:18: undefined reference to `Card::Card(Shape)'

bin/FigureCard.o: In function `FigureCard::operator=(FigureCard&)':
/home/shaike131/workspace/check/src/FigureCard.cpp:22: undefined reference to `Card::getShape2()'

/home/shaike131/workspace/check/src/FigureCard.cpp:22: undefined reference to `Card::setShape(Shape)'

bin/FigureCard.o: In function `FigureCard::getShape()':
/home/shaike131/workspace/check/src/FigureCard.cpp:43: undefined reference to `Card::getShape2()'

bin/FigureCard.o: In function `FigureCard::comperator(Card*)':
/home/shaike131/workspace/check/src/FigureCard.cpp:71: undefined reference to `typeinfo for Card'

bin/FigureCard.o: In function `FigureCard::~FigureCard()':
/home/shaike131/workspace/check/src/../include/FigureCard.h:12: undefined reference to `Card::~Card()'

bin/FigureCard.o:(.rodata._ZTI10FigureCard[_ZTI10FigureCard]+0x10): undefined reference to `typeinfo for Card'
bin/NumericCard.o: In function `NumericCard::NumericCard(Shape const&, int const&)':
/home/shaike131/workspace/check/src/NumericCard.cpp:18: undefined reference to `Card::Card(Shape)'

bin/NumericCard.o: In function `NumericCard::NumericCard(NumericCard&)':
/home/shaike131/workspace/check/src/NumericCard.cpp:19: undefined reference to `Card::getShape2()'

/home/shaike131/workspace/check/src/NumericCard.cpp:19: undefined reference to `Card::Card(Shape)'

bin/NumericCard.o: In function `NumericCard::operator=(NumericCard&)':
/home/shaike131/workspace/check/src/NumericCard.cpp:24: undefined reference to `Card::getShape2()'

/home/shaike131/workspace/check/src/NumericCard.cpp:24: undefined reference to `Card::setShape(Shape)'

bin/NumericCard.o: In function `NumericCard::getShape()':
/home/shaike131/workspace/check/src/NumericCard.cpp:32: undefined reference to `Card::getShape2()'

bin/NumericCard.o: In function `NumericCard::comperator(Card*)':
/home/shaike131/workspace/check/src/NumericCard.cpp:65: undefined reference to `typeinfo for Card'

bin/NumericCard.o: In function `NumericCard::~NumericCard()':
/home/shaike131/workspace/check/src/../include/NumericCard.h:16: undefined reference to `Card::~Card()'

bin/NumericCard.o:(.rodata._ZTI11NumericCard[_ZTI11NumericCard]+0x10): undefined reference to `typeinfo for Card'

bin/Hand.o: In function `Hand::addCard(Card&)':

thanks. Shai

FigureCard class:

#include "../include/Card.h"
#include "../include/FigureCard.h"
#include <iostream>
#include <string>
using namespace std;
#include <sstream>
#include <memory>


FigureCard :: FigureCard(const Shape &shape,const Figure &figure):Card(shape),figure(figure){}

FigureCard :: FigureCard(FigureCard& other):Card(other.getShape2()), figure(other.figure){}
FigureCard& FigureCard:: operator= (FigureCard& other){

    if(this!=&other){
        this->setShape(other.getShape2());
        figure=other.figure;
    }
    return *this;
}

char FigureCard:: getFigure(){
    char s;
    switch(figure)
    {
        case Jack: s='J';break;
        case Queen: s='Q';break;
        case King : s='K';break;
        case Ace :  s='A';break;
    }

return s;
}

char FigureCard:: getShape(){
    char s;
    switch(this->getShape2())
    {
    case Club: s='C';break;
    case Diamond: s='D';break;
    case Heart : s='H';break;
    case Spade :  s='S';break;
    }

return s;
}


Figure FigureCard::getFigure2(){
    return this->figure;
}


string FigureCard:: toString()
    {
    string s(1,this->getFigure());
        s=s+this->getShape();
    return s;
    }

    int FigureCard:: comperator(Card* other){
    int ans=0;
    if (this->getType().size()==(other->getType().size())){  //if it's both FigureCard
        char figure1=this->getFigure();
        FigureCard*    fg = dynamic_cast<FigureCard*>(other);
        char figure2=fg->getFigure();

        if(figure1=='A'){
            if(figure2!='A')
                ans=1;//a is A and b is lower
        }
        else if(figure2=='A')
            ans=-1;//b is A and a is lower
        else if(figure1=='K'){
            if(figure2!='K')
                ans=1;//a is K and b is lower
        }
        else if(figure2=='K')
            ans=-1;//b is K and a is lower
        else if(figure1=='Q'){
            if(figure2!='Q')
                ans=1;//a is Q and b is lower
        }
        else if(figure2=='Q')
            ans=-1;//b is Q and a is lower


        if(ans==0){//the figures of first and second are the same
            char shape1=this->getShape();
            char shape2=other->getShape();
            if(shape1>shape2)
                ans=1;
            else if(shape1<shape2)
                ans=-1;

        }
    }

    else
        ans=1; //first card is FigureCard card and second card is NumericCard
    return ans;
    }

string FigureCard:: getType(){
    return "FigureCard";
}

NumericCard.cpp

    /*
 * NumericCard.cpp
 *
 *  Created on: Nov 28, 2016
 *      Author: shaike131
 */


#include "../include/Card.h"
#include <iostream>
#include <string>
using namespace std;
#include <sstream>
#include <memory>
#include "../include/NumericCard.h"


NumericCard :: NumericCard(const Shape &shape,const int &number):Card(shape),number(number){}
NumericCard :: NumericCard(NumericCard& other):Card(other.getShape2()), number(other.number){}
NumericCard& NumericCard:: operator= (NumericCard& other){

    if(this!=&other){
        this->number=other.number;
        this->setShape(other.getShape2());

    }
    return *this;
}

char NumericCard:: getShape(){
    char s;
    switch(this->getShape2())
    {
    case Club: s='C';break;
    case Diamond: s='D';break;
    case Heart : s='H';break;
    case Spade :  s='S';break;
    }

return s;
}



string  NumberToString ( int Number )
  {
     ostringstream ss;
     ss << Number;
     return ss.str();
  }
string NumericCard:: toString()
    {
    string s = NumberToString(number);

    s=s+this->getShape();

    return s;
    }


int NumericCard:: comperator(Card* other){
    int ans=0;
    if(this->getType().size()==other->getType().size()){  //if it's both numbers
        int num1=this->getNumber();
        NumericCard*    num = dynamic_cast<NumericCard*>(other);
        int num2=num->getNumber();
        if(num1>num2)
            ans=1;
        else if(num1<num2)
            ans=-1;
        else{
            char shape1=this->getShape();
            char shape2=other->getShape();
            if(shape1>shape2)
                ans=1;
            else if(shape1<shape2)
                ans=-1;
        }
    }
    else // if first card is NumericCard and second card is FigureCard
        ans=-1;
    return ans;
    }


string NumericCard:: getType(){
    return "NumericCard";
}
int NumericCard:: getNumber(){
    return this->number;
}

Card:

#include "../include/Card.h"
#include <iostream>
#include <string>
using namespace std;
#include <sstream>
#include <memory>


Card::Card(Shape Pshape):shape(Pshape){}
Card::Card(){}

Card::~Card() {
}

Shape Card::getShape2(){
    return this->shape;
}


void Card::setShape(Shape shape){
    this->shape=shape;
}

makeFile:

   # All Targets
all: check

# Tool invocations
# Executable "check" depends on the files CyberDNS.o,CyberExpert.o,CyberPC.o,CyberWorm.o,Cyber.o.

check: bin/Card.o bin/FigureCard.o bin/NumericCard.o bin/Deck.o bin/Player.o bin/link.o bin/linkedList.o bin/Game.o bin/Hand.o bin/check.o
    g++ -o bin/Card.o  bin/FigureCard.o bin/NumericCard.o bin/Deck.o bin/Player.o bin/link.o bin/linkedList.o bin/Game.o bin/Hand.o bin/check.o
# Depends on the source and header files

bin/Card.o: src/Card.cpp
    g++ -g -Wall -c -Linclude -o bin/Card.o src/Card.cpp
# Depends on the source and header files

bin/FigureCard.o: src/FigureCard.cpp
    g++ -g -Wall -c -Linclude -o bin/FigureCard.o src/FigureCard.cpp
# Depends on the source and header files

bin/NumericCard.o: src/NumericCard.cpp
    g++ -g -Wall -c -Linclude -o bin/NumericCard.o src/NumericCard.cpp
# Depends on the source and header files


bin/Deck.o: src/Deck.cpp
    g++ -g -Wall -c -Linclude -o bin/Deck.o src/Deck.cpp
# Depends on the source and header files

bin/Player.o: src/Player.cpp
    g++ -g -Wall -c -Linclude -o bin/Player.o src/Player.cpp
# Depends on the source and header files

bin/link.o: src/link.cpp
    g++ -g -Wall -c -Linclude -o bin/link.o src/link.cpp    
# Depends on the source and header files 

bin/linkedList.o: src/linkedList.cpp
    g++ -g -Wall -c -Linclude -o bin/linkedList.o src/linkedList.cpp

bin/Game.o: src/Game.cpp
    g++ -g -Wall -c -Linclude -o bin/Game.o src/Game.cpp

bin/Hand.o: src/Hand.cpp
    g++ -g -Wall -c -Linclude -o bin/Hand.o src/Hand.cpp

bin/check.o: src/check.cpp
    g++ -g -Wall -c -Linclude -o bin/check.o src/check.cpp

#Clean the build directory
clean: 
    $(RM) bin/*     
All:
    bin/check bin/Card.o bin/FigureCard.o bin/NumericCard.o bin/Deck.o bin/Player.o bin/link.o bin/linkedList.o bin/Game.o bin/Hand.o bin/check.o