vendredi 30 novembre 2018

Destruction of class object upon interrupt signal

I am developing c++ application and I am stucked on the signal handling problem with c++11. I want to call destructor's for all objects(created on stack as well as on heap) created under my main application on arrival of SIGINT signal.

Please suggest sophisticated solution here. Appriciate for you time.

Thanks and Regards, Ojas

How to view C/C++ library source code on a Linux machine?

When I use a package manager like apt-get or yum on a Linux distro to install gcc and g++, how are they installed? Does the package manager only download header files, dynamic library, and compiler executable? or does it download the whole source code directory and compile them into .so and .a files?

I assume it uses the first approach considering space usage but is there any library source code (STL etc.) that I can view on the operating system?

How to see the expanded code of templates in GCC

I know that compiler expands macros while compiling. In GCC we can see the same if we compile code with -E switch option.

In same way does the templates code be expanded at the compile time. Is there any way to see expanded code of a template? In GCC I tried with -E switch but I did not see any template expanded code? Is there any GCC compiler switch available for same?

C++ ofstream can't open file from variable name (not even after using c_str())

In my code I am trying to create a file and write to it.

std::ofstream saveFile("file.txt");
ofstream << "test" << endl;

Works perfect! But,

std::string fileName = "file.txt"
std::ofstream saveFile(filename.c_str());
ofstream << "test" << endl;

I've tried with and without c_str(), with no luck. There are no errors. But ofstream.good() returns false.

Repeated function calls with a single argument changing in C++

I have a repeated pattern in my code

enum { OUTSIDE_BSPH = 0, INSIDE_BSPH = 1 };
bool bsph = true;
//...
bool = false;

f(OUTSIDE_BSPH, arg1, arg2, arg3, arg4, arg5);
if (bsph) {
  f(INSIDE_BSPH, arg1, arg2, arg3, arg4, arg5);
}

g(OUTSIDE_BSPH, arg6, arg7, arg8);
if (bsph) {
  g(INSIDE_BSPH, arg6, arg7, arg8);
}

h(OUTSIDE_BSPH, arg3, arg4, arg5);
if (bsph) {
  h(INSIDE_BSPH, arg3, arg4, arg5);
}
// ...

that I would like to simplify. Could it be transformed into something like

caller(bsph, f, arg1, arg2, arg3, arg4, arg5);

caller(bsph, g, arg6, arg7, arg8);

caller(bsph, h, arg3, arg4, arg5);

// ...

without using pointers?

Compiling Rcpp package that uses CUDA on Windows 10 and RStudio

I have a program which essentially has 3 parts. R code is used to gather data, which it then processes using a .cpp file and Rcpp, and then the data is analyzed using custom CUDA C++ code.

At this point my analysis is done using C++ code in the .cpp file, and I'm having a lot of difficulty understanding how to compile CUDA with Rcpp in a way that R recognizes and that works on Windows 10.

Rcpp requires the use of g++ to build, and CUDA requires nvcc as far as I'm aware.

I'm basically looking for a simple "hello world" or barebone example of using Rcpp + CUDA.

I've found a few examples on StackOverflow, but they do not seem to work, either due to their age, or maybe because I'm using Windows.

The best example I could find was from 2015, but with help they reported success. I downloaded their most recent repo which contained CUDA files, and then edited the Makevars to fit my system, as you'll find below, but when I tried to run the "check package" command through RStudio, the error log reports:

* installing *source* package 'rcppcuda' ...
** libs
Makevars:35: *** multiple target patterns.  Stop.
ERROR: compilation failed for package 'rcppcuda'

Below you'll find my Makevars, with paths updated for my system.

I would appreciate any help to make Rcpp and CUDA compile, whether your answer uses the code I've mentioned here, or if you have another solution.

Thanks!

CUDA_HOME = "C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v10.0"
R_HOME = "C:\Program Files\Microsoft\R Open\R-3.5.1"
CXX = "C:\Rtools\mingw_64\bin\g++.exe"

# This defines what the shared object libraries will be
PKG_LIBS= -L"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.0\lib\x64" -Wl,-rpath,"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.0\lib\x64" -lcudart -d


#########################################

R_INC = "C:\Program Files\Microsoft\R Open\R-3.5.1\include"
RCPP_INC = "Z:\Documents\R\win-library\3.5\Rcpp\include"

NVCC = "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.0\bin\nvcc.exe"
CUDA_INC = "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.0\include"
CUDA_LIB = "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.0\lib\x64"

LIBS = -lcudart -d
NVCC_FLAGS = -Xcompiler "-fPIC" -gencode arch=compute_30,code=sm_30 -gencode arch=compute_35,code=sm_35 -I$(R_INC)

### Define objects
cu_sources := $(wildcard *cu)
cu_sharedlibs := $(patsubst %.cu, %.o,$(cu_sources))

cpp_sources := $(wildcard *.cpp)
cpp_sharedlibs := $(patsubst %.cpp, %.o, $(cpp_sources))

OBJECTS = $(cu_sharedlibs) $(cpp_sharedlibs)

all : rcppcuda.so

rcppcuda.so: $(OBJECTS)

%.o: %.cpp $(cpp_sources)
        $(CXX) $< -c -fPIC -I$(R_INC) -I$(RCPP_INC)

%.o: %.cu $(cu_sources)
        $(NVCC) $(NVCC_FLAGS) -I$(CUDA_INC) $< -c

Use cases of recursive_mutex, timed_mutex, recursive_timed_mutex

I understand that the template parameter of std::lock_guard is representing anything BasicLockable type.

That makes the following code block valid.

std::recursive_timed_mutex m;
//.
//.
//.
std::lock_guard<std::recursive_timed_mutex> guard(m);

I have rarely seen a BasicLockable other than std::mutex is used, though. This makes me think std::mutex is just for general mutual exclusion usage. Even tough their definitions are out there, I wanted to look for use cases of other BasicLockable s but couldn't find much.

So my question is, what are the use cases of recursive_mutex/timed_mutex/recursive_timed_mutex?

Why am I getting bad_alloc? Implementing a stack c++

I'm trying to implement my own Stack in C++ but I keep getting this error when I try to use the method pop() in which what I'm trying to do is:

  1. Save element from the top in a variable called "res".
  2. Get the reference to the next element from the node class and set it as the top.
  3. size--
  4. Return the variable "res".

If you could help me I'd appreciate it. Thank you!

Node class:

#include <iostream>

using namespace std;

template<class T>
class Node {
private:
    Node<T>* next;
    T element;

public:
    Node();

    Node(const Node& orig);

    ~Node();

    void setElement(T el);

    T getElement();

    Node<T>* getNext();

    void setNext(Node<T>* ne);
};



template<typename T>
Node<T>::Node() {
    next = nullptr;
}
template<typename T>
Node<T>::Node(const Node& orig) {}

template<typename T>
Node<T>::~Node() {}

template<typename T>
void Node<T>::setElement(T el) {
    element = el;
    cout << element << endl;
}

template<typename T>
T Node<T>::getElement() {
    return element;
}

template<typename T>
Node<T>* Node<T>::getNext() {
    return next;
}

template<typename T>
void Node<T>::setNext(Node<T>* ne) {
    next = ne;
}

Stack class:

#include "EmptyStackException.cpp"
#include "Node.cpp"
#include <iostream>

using namespace std;

template<class T>
class LinkedStack {
private:
    int siz;
    Node<T>* first;

public:
    LinkedStack();

    ~LinkedStack();

    int size();

    bool isEmpty();

    void push(T e);

    T top();

    T pop();
};

template<class T>
LinkedStack<T>::LinkedStack() {
    first = nullptr;
    siz = 0;
}

template<class T>
LinkedStack<T>::~LinkedStack() {
}

template<class T>
int LinkedStack<T>::size() { return siz; }
template<class T>
bool LinkedStack<T>::isEmpty() { siz == 0; }

template<class T>
void LinkedStack<T>::push(T e) {
    Node<T> node = Node<T>();
    node.setNext(first);
    node.setElement(e);
    first = &node;
    siz++;
}

template<class T>
T LinkedStack<T>::top() {
    //to do after...
}

template<class T>
T LinkedStack<T>::pop() {
    T res = first->getElement();
    first = first->getNext();
    siz--;
}

CRTP base constructor crashes because child is not constructed

I have classes which are autogenerated but I want to enable end users to add custom member functions and constructors.

My approach is to use a CRTP base class which has no member variables just functions.

The problem lies with the constructor. If I define a constructor in my CRTP I cannot correctly access the child as it is not constructed yet as the child classes constructor only gets called after the CRTP base is constructed.

#include <iostream>
#include <string>

template<class Child>
struct Foo {
  Foo(std::string i) {
    // Childs constructor is not run yet.
    std::cout << static_cast<Child&>(*this).d.size(); // Prints trash
    static_cast<Child&>(*this).d = i; // Segfault here
    (void) i;
  }
};

// Cannot change this class.
struct Bar : Foo<Bar> {
  using base_t = Foo<Bar>;
  using base_t::base_t;
  std::string d;
};


int main()
{
  Bar bar("asdgasdgsag");
  std::cout << "bar.d: " << bar.d << std::endl;
}

Is there a way to solve this problem?

UBSan complains when calling a member of a derived class from a lambda within a thread

I stumbled upon this issue, where UBSan complains about calling a member function of a derived class through a supposedly invalid pointer - yet I am unable to see why it should be invalid.

I have broken down my code to the following snippet, which you can also examine here in a live version.

struct Base {
    virtual ~Base() {
        for(auto& t : ts) {
            t.join();
        }
    }

    template<typename F>
    void Spawn(F&& f) {
        ts.emplace_back(std::forward<F>(f));
    }

    std::vector<std::thread> ts;
};

struct Foo : public Base {
    Foo() { }

    void Start() {
        Spawn([this] { Member(); /* HERE */ });
    }

    void Member() { }
};

int main() {
    Foo f;
    f.Start();
}

Basically, what I am doing is the following:

  • Create a lambda, which captures the this pointer of the current derived class Foo
  • Spawn a thread which is stored in the respective base class Base
  • Call the lambda from the thread
  • Call a member function from the lambda

UBSan complains as soon as a member of Foo is accessed by the captured pointer within the lambda (output from the live example):

prog.cc:31:52: runtime error: member call on address 0x7ffc50687018 which does not point to an object of type 'Foo'
0x7ffc50687018: note: object is of type 'Base'
 00 00 00 00  48 b5 44 00 00 00 00 00  e0 c6 ce 01 00 00 00 00  e8 c6 ce 01 00 00 00 00  e8 c6 ce 01
              ^~~~~~~~~~~~~~~~~~~~~~~
              vptr for 'Base'

What am I missing here?

C++ : Meaning of int n != unsigned int(n)

I was reading a code segment that was checking if some values from a ppm file are correct. The values were read like this:

image >> img_format >> width >> height >> maxval;

And then to check if width and height are correct this was used:

if (width != unsigned int(width) && height != unsigned int(height))
{
    cerr << "Width and/or height of the image are missing." << endl;
    exit(EXIT_FAILURE);
}

**width and height are declared as unsigned int

How does this condition work?

Understanding implicitly defined copy and move constructor c++11 [duplicate]

Consider following code:

class Shape
{
public:
    virtual void introduceMe() = 0;
};

class Triangle : public Shape
{
public:
    void introduceMe() override { std::cout << " I am a triangle \n"; }
};

Moreover consider my following smart pointer:

template<typename T>
class MyUnique_ptr
{
    T* ptr;

public:

    explicit MyUnique_ptr(T* p = nullptr)
    {
        ptr = p;
    }

    ~MyUnique_ptr()
    {
        delete ptr;
    }
}

Furthermore, consider this supplementary piece of code:

MyUnique_ptr<Shape> make_triangle()
{
    MyUnique_ptr<Shape> x(new Triangle);
    return x;  //a- getting an error: implicit defined copy constructor is a deleted function. (But works if I implement a copy constructor)
}

struct Color {
    float g;
};

Color test() {
    Color c;
    return c; //b- why this work whereas a) does not ?
}

And finally, here is how my main look like:

int main(int argc, char** argv)
{
   MyUnique_ptr<Shape> a(new Triangle);
   MyUnique_ptr<Shape> b(make_triangle());  // c- same error here. But works if I implement a move constructor and no copy constructor, why?  
   MyUnique_ptr<Shape> c(a); // d- same error here. But works if copy constructor is explicitly defined.
}

To resume: 1- in a) c) and d) I'm getting errors, saying the implicitly defined copy constructor is a deleted function. Why it is deleted? If I implement a copy constructor then everything works fine. Why the compiler is forcing me to provide a copy constructor?

2- If I implement a move constructor (and no copy constructor) then lines a) and c) will work. Why the compiler is forcing me defined move semantics (constructor)? Are there some cases in c++ (like my example above maybe) where move constructor or move assignment MUST explicitly be defined? Are they actually implicitly defined by the constructor? Thanks

placement delete function is never called upon exception

The placement delete is used to deallocate the memory when an exception occurs in the placement new. So I ran a test:

class A {
public:
    A(){
        cout << "constructor" << endl;
        throw 1;
    }
};

void* operator new(size_t size, int i){
    cout << "in placement new" << endl;
    return ::operator new(size);
}

void operator delete(void *ptr, int i){
    cout << "in placement delete" << endl;
    ::operator delete(ptr);
}

int main(){
    int o = 9;
    A* a = new(o) A;
}

And the placement delete function was never called, it just simply exited. Why?

Is it possible to change behavior of function based on scope?

I would like to create something similar to rust unsafe scope in C++. The idea is that I have some functions performing number of checks. For example:

void check() {
     if (...)
        throw exception(...);

}

void foo() {
     check();

     // do some work
}

Now, I want to be able to call function foo() with or (in different context) without performing those checks. Ideally it would look like this:

foo(); // call foo and perform checks
unsafe {
    foo(); // call foo without checks
}

My question is, is it possible to achieve something like this in compile time? Is it possible to somehow check (or act differently) from check function in what scope it is called?

I came up only with a runtime solution: to wrap it in some lambda:

unsafe([&] {
    foo();
});

where unsafe is implemented as follows:

void unsafe(std::function<void()> f)
{
     thread_local_flag = unsafe;
     f();
     thread_local_flag = safe;
}

check() function would just check for the thread_local flag and perform checks only when it is set to safe.

jeudi 29 novembre 2018

Return Local Object in C++ [duplicate]

This question already has an answer here:

Never calls move constructor. Why ? An error occurs when I delete the move constructor. Output:

A constructor

0x7fff8ed60ebf

Hello World!

0x7fff8ed60ebf

~A

#include <iostream>
#include <string>
class A{
public:
  A(){std::cerr<<"A constructor"<<std::endl;}
  A(A&& o){std::cerr<<"A move constructor"<<std::endl;}
  //A(A&& o) = delete;
  A(const A &p2){std::cerr<<"A copy constructor"<<std::endl;};
  ~A(){std::cerr<<"~A"<<std::endl;}
  A& operator=(const A& other)=delete;
  A& operator=(A&& other)=delete;

};

A foo(){

  A temp;
  std::cerr<<&temp<<std::endl;
  return temp;
}
int main() {
  A temp = foo();
  std::cerr << "Hello World!\n" << &temp << std::endl;
}

Create rows of struture mapped to names externally defined

We have a class like below:

NamesOfData GetNamesOfData()
{
    NamesOfData names =
    {
        "AAA",
        "BBB"
    };
  return names;
}

Now I have a structure that has to have names as mentioned above along with other fields:

struct A
{
    std::string name;
    ...other fields...;
};

I can have the name easily duplicated to create rows of strut values:

struct A Data [] =
{
     "AAA",.......;
     "BBB", ......;
};

But the issue is that I need to ensure the integrity of names within struct and externally defined - which can be broken any time if the names are modified at any place.

Is there a way design that the issue mentioned above can be overcome or rather having names centrally but easily mapped by both the places?

How to project 3D points to 2D points using pre-computed values

I have few 3D points and corresponding 2D points in my image, Now I want to create some formula using this points through which I can convert other 3D points to 2D points. Please suggest ways to do this.

What is the difference between shallow copy and deep copy in c++?

Basic example to understand the shallow copy and deep copy in c++?

Cpp Core Guidelines recommend against #pragma once?

Based on other answers on SO such as #pragma once vs include guards? as well as what I've seen in some open source and other projects, #pragma once seems to be standard practice. Yet, the CPP Core Guidelines here recommend against it(the note seems pretty strong against #pragma once).

As long as I'm using C++11 or above with an up-to date compiler do I need to worry about this? In which situations, should I be wary of using them?

What is the best way to move a range from a container to another?

Here is my setup:

class C {
public:
    template<typename T>
    void addFrom(T begin, T end){
        std::move(begin, end,
            std::back_inserter(vec));
    }
    std::vector<B> vec;
};
class A {
    C object;
    std::vector<B> vec;
    void passRangeToObject(){
     C.addFrom(std::make_move_iterator(
         vec.rbegin()),  
       std::make_move_iterator(vec.rbegin() 
       +5));
    }
};

After running the code the B objects are added in the C objects vector but they are not removed from A's vector. Is there a good solution out there?

How to cancel a Read() call for grpc::ClientReader in C++?

I have code that requests a stream of data from a grpc::Server with a grpc::ClientReader. The main loop looks like below, and runs in a seperate task. I need to shutdown task when destructor, but the Read() method is blocking. There doesn't seem to be anything I can do to mcReader to get it to stop blocking. I would rather not use deadline, because data isn't completely periodic, and making it big enough to do antyhign would still block a long time. What should I do?

while (mcReader->Read(&dataProductWrapper) && meTasksRunning) 
{
      // Do some work.
}

How do I signal to abort/wake all threads waiting on a condition variable before calling pthread_cond_destroy?

I'm aware of undefined behavior on calling pthread_cond_destroy() when there is 1+ thread waiting on a condition variable and I'm looking for a workaround to send wake signal to all threads waiting on a condition variable before calling pthread_cond_destroy().

My CV class destructor calls pthread_cond_destroy() if condition variable is valid. Therefore, I thought of:

  1. Broadcasting before calling pthread_cond_destroy() but that would wake just 1 thread. I want destructor to succeed and that no thread should be able to wait on the cv object (No dereferencing on destructed object).

  2. Is signal counting (along with workaround #1) a way to fix this issue? If so, how do I ensure that all waiting threads have been scheduled (woken up) before ~CV() succeeds?

  3. Do I overcome this issue if I use C++ 11 thread/condition variable?

e with checking if number is between 2 values

Just started with c++. Been trying to create a simple program. How do i check if number is between 2 values? I've tried using different methods but still couldn't manage to create this program.

Is a good practice import namespaces in C++? [duplicate]

This question already has an answer here:

I was reading a friend project in C++ and he doesn't import namespaces in the project. I asked why and he said that it isn't a good pratice, but dont know why. I know about import STD isn't a good pratice, but it's for all namespaces?

Is it a good practice? Why?

Comparison between signed and unsigned. Is static_cast the only solution?

I use third party containers that use int to store the size. I also use stl containers which use size_t to store size.

I very often in my code have to use both in the same loop, like for example:

// vec is std::vector
// list is the third party container
assert(vec.size() == list.size()); // warning
for(size_t i = 0; i < vec.size(); i++)
{
    vec[i] = list[i]; // warning
}

So to fix I have to either I do function style casting, which I was told is C style casting in disguise.

// vec is std::vector
// list is the third party container
assert(int(vec.size()) == list.size());
for(size_t i = 0; i < vec.size(); i++)
{
    vec[i] = list[int(i)]; // warning
}

Or I can do the even uglier solution that everyone recommends. The static casting.

// vec is std::vector
// list is the third party container
assert(static_cast<int>(vec.size()) == list.size());
for(size_t i = 0; i < vec.size(); i++)
{
    vec[i] = list[static_cast<int>(i)]; // warning
}

I really don't want to static_cast.

  • Can the implicit conversion in this particular scenario be dangerous?
  • Would the function style be okay in my case?
  • If static_cast is really the only safe solution. Should I cast the int to size_t or size_t to int?

Thank you.

How to find the most repeated word?

How can make the program to print the most repeated word? For now it prints as follow:

Input: apple banana apple apple

Output:

apple appeared 3 times

banana appeared 1 times

int main() {
        string words;
        vector<string> stringHolder;

        while (cin >> words)
        {
            stringHolder.push_back(words);
        }
        sort(stringHolder.begin(), stringHolder.end());

        int vSize = stringHolder.size();
        if (vSize == 0) {
            cout << " no words ";
        }
        int wordCount = 1;
        words = stringHolder[0];
        for (int i = 1; i<vSize; i++) {
            if (words != stringHolder[i]) {
                cout << words << " appeared " << wordCount << " times" << endl;
                wordCount = 0;
                words = stringHolder[i];
            }
            wordCount++;
        }
        cout << words << " appeared " << wordCount << " times" << endl;
        system("pause");
    }

Can two functions of the same class share the the values of two member variables? [on hold]

I have a class, named for example shell. In this class I defined two void (f and q) as public and then a list of member variables. The member variables are calculated in the function f, and then when I call the same varaibles them from function q, they have again value 0 (initialization)...how do I fix it please?

class shell {
public:
       void f() const;
       void q() const;
       int a;
       std::vector<int> b;
}

Python's enumerate for C++

In Python there is enumerate which takes a sequence/iterator and yields pairs of an integer index and the value itself. In C++ I occasionally find myself writing

for (size_t i = 0; i != vector.size(); ++i) {
    auto const &elem = vector[i];
    // ...

Similar to Python I would like to write

for (auto const &it : enumerate(vector)) {
    // it.first is the index (size_t)
    // it.second is the element (T const&)

Does such an enumerate exist in either the STL or a common library like Boost?

Allocate vector size with list initialization (curly braces)

How can I do the equivelant of:

#include <vector>

size_t bufferSize = 1024 * 1024;
std::vector<unsigned char> buffer(bufferSize, ' ');

With list (curly braced) initialization?

When I try to do the following:

#include <vector>

size_t bufferSize = 1024 * 1024;
std::vector<unsigned char> buffer {bufferSize, ' '};

It wrongly interprets bufferSize as the value to be stored in the first index of the container (i.e. calls the wrong std::vector constructor), and fails to compile due to invalid narrowing conversion from unsigned int (size_t) to unsigned char.

Deduced type of auto variable in for statement

Considering following code snippet:

  for (auto loopcontrol = 0; loopcontrol < 10; loopcontrol++)
  {
     ...
  }

How is the type of loopcontrol deduced?

On the C++ compiler I use (Microsoft Visual Studio 2017) it is int, but why not e.g. long?

Is it the type of 0?

Is there some sort of copy destructor tech?

For example I got a class like this:

#include <iostream>
#include <functional>

class TestClass {
 public:
  explicit TestClass(std::function<void(void)> f) : f_(std::move(f)) {}
  TestClass(const TestClass &) = delete;
  TestClass(TestClass &&testobj) {
    f_ = testobj.f_;
    testobj.f_ = default_f_;
  }
  ~TestClass() { f_(); }
 private:
  static std::function<void(void)> default_f_;
  std::function<void(void)> f_;
};

std::function<void(void)> TestClass::default_f_ = [] { std::cout << "do nothing\n"; };

int main() {
  std::function<void(void)> f = [] { std::cout << "do something\n"; };
  TestClass t1(f);
  TestClass t2(std::move(t1));
}

Even if the old class is useless, The destructor has to be called and in this case, a useless function which duty is only to make sure the f_ is point to something, this is not very efficiency.

So is there some sort of copy destructor tech to avoid this?

What's the difference between `auto pp` and `auto *ppp`? [duplicate]

int foo = 11;
int *p = &foo;

auto pp = p;
auto *ppp = p;

cout << pp << endl;
cout << ppp << endl;

This program will produces the same output of pp and ppp,so why? auto deduce the variable should be int, so I think declaration of ppp is right. But pp and ppp have the same value... Output: 0x61fefc 0x61fefc

std::uint32_t is not a type in c++11

I am using std::uint32_t as a type in c++11 on a cmake project. I added set_property(cxx_compiler_flag "-std=c++11" in CMakeLists but the error is still here.

CMake & C++ - What is the best approach to share library between several git submodules

I am working with large C++ project (using cLion) which containing 4 submodules. I wrote small C++ library which provides the ability to read from .properties file (most common in Java..).

The "Application.properties" file should includes common variables and per-project variables. For example; I am using Elasticsearch database and all the 4 sub-modules should know his address. In addition, Since i have 4 foreign projects i need to maintenance constantly 5 different CMakeLists files ( 4 sub-modules 1 for the main project).

My solution is to set the shared code in the main project root and using it by include the library in per project.

  • The project & submodules version control is git. I thought about it and decided that maybe I should check for more reviews before I started writing.

With Gratitude, Kobi.

mercredi 28 novembre 2018

how to make a thread wait on another thread called by itself

I am quite new to multithreading and c++11 thread libraries. I have one scenario and would appreciate your way forward with it.

I have 2 threads (say "thread1" and "thread2") such that, "thread1" calls "thread2" and it should wait on some condition until either it is fulfilled by "thread2" or a specific time has elapsed.

Couple of things are worth noting here in this context. Firstly, it's always "thread1" that calls and waits on "thread2" upon some condition or time-limit. Secondly, "thread2" never ever calls "thread1" at any point.

I tried a solution something like below:

bool condition = false;
std::mutex mtx;
std::condition_variable cv;

void thread1()
{
    std::string str = "string";
    std::unique_lock<std::mutex> lck(mtx);
    thread2(str);

    while(!condition)
    {
        cv.wait(lck);   // or let's say 60 seconds elapsed
    }

    std::cout << "condition reached" << std::endl;
}

void thread2(const std::string& str)
{
    calls_some_other_function();
    std::unique_lock<std::mutex> lck(mtx);
    condition = true;
    cv.notify_one();
}

Now, is this a correct implementation? The doubt I have with this implementation is that how to ensure that "thread2" always returns after "thread1" starts to wait on it, or else it will either keep waiting forever or come out of the timer (60 seconds, let's say) even though the condition is satisfying?.

Please help here.

Array elements change automatically when I enter a function

I am implementing a graph. I have print, BFS and DFS methods. My print, BFS, and DFS would work normally if I run them separately, however, if I run them one after another one, for example, I ran BFS after print, the BFS won't work. It seems I changed my array in my methods but I did not, can anyone help me with this?

below is my graph.h

#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <queue>
using namespace std;

struct node{
    char ID;
    int WEIGHT;
    int DISTANCE;
    bool VISITED;
    node(char,int);
    node *next;
};
struct  myGraph{
public:
    void addEdge(node* [], char,char,int);
    void printGraph(node* [], int V);
    void BFS(node* [],char);
    void visitedNode(node* [], char head, int);
    void DFS(node* [],char);
};

below is my graph.cpp

#include "myGraph.h"

node::node(char id, int weight) {
    this->ID = id;
    this->WEIGHT = weight;
    this->VISITED = false;
    this->DISTANCE = 0;
    this->next = nullptr;

}

void myGraph::addEdge(node* adj[], char head, char end, int weight)
{   int parent = head - 'a';
    node* newNode = new node(head,0);
    node* anotherNode = new node(end,weight);
    if (adj[parent] == nullptr){
        adj[parent] = newNode;
        adj[parent]->next = anotherNode;
    }
    else{
        node *temp = adj[parent];
        while(temp->next != nullptr){

            temp = temp->next;
        }
        temp->next= anotherNode;
    }
}

void myGraph::printGraph(node* adj[], int V)
{
    for (int v = 0; v < V; v++)
    {
        if (adj[v] != nullptr){
            cout << "Adjacency list: "<<endl;
            cout<<"Head: "<<adj[v]->ID<<" -> ";
            while (adj[v]->next != nullptr){
                adj[v]= adj[v]->next;
                cout <<"Id: "<<adj[v]->ID <<" Weight: "<<adj[v]->WEIGHT<<" -> ";

            }
            cout<<"nullptr"<<endl;
        }
    }
}
void myGraph::visitedNode(node* adj[], char target, int size){
    for (int i = 0; i < size; i++){
        node* temp =  adj[i];
        while (temp != nullptr){
            if (temp->ID == target){
                temp->VISITED = true;
            }
            temp = temp->next;
        }
    }
}


void myGraph::BFS(node* adj[],char head) {
    queue<node*> temp;
    vector<node*> result;
    node * tempNode = adj[head-'a']; //assign head pointer to tempNode
    temp.push(tempNode);
    visitedNode(adj,tempNode->ID,9);
    while (!temp.empty()){
        tempNode = adj[temp.front()->ID - 'a'];
        temp.pop();
        result.push_back(tempNode);
        while(tempNode->next != nullptr){
            if (!tempNode->VISITED){
                temp.push(tempNode);
                visitedNode(adj,tempNode->ID,9);
            }
            tempNode = tempNode->next;
        }
        if (!tempNode->VISITED){
            temp.push(tempNode);
            visitedNode(adj,tempNode->ID,9);
        }
    }
    cout<<"Traverse by BFS: "<<endl;
    for (auto i : result){
        cout<<i->ID <<" ";
    }
}


void myGraph::DFS(node* adj[],char head){
    stack<node*> temp;
    vector<node*> result;
    node * tempNode = adj[head-'a'];
    temp.push(tempNode);
    visitedNode(adj,tempNode->ID,9);
    while(!temp.empty()){
        while (tempNode->next != nullptr){
            if (!tempNode->next->VISITED){
                tempNode = adj[tempNode->next->ID - 'a'];
                visitedNode(adj,tempNode->ID,9);
                temp.push(tempNode);
            }
            else{
                tempNode = tempNode->next;
            }

        }
        result.push_back(temp.top());
        temp.pop();
        if (!temp.empty()){
            tempNode = temp.top();
        }
    }


    cout<<"Traverse by DFS: "<<endl;
    for (auto i : result){
        cout<<i->ID <<" ";
    }
}

below is my main

#include "main.h"
int main() {
    myGraph *tryme = new myGraph();
    const int V = 9;
    node* adj[V] = {};
    tryme->addEdge(adj, 'a','b',2);
    tryme->addEdge(adj, 'a','c',4);
    tryme->addEdge(adj, 'a','d',6);
    tryme->addEdge(adj, 'b','c',5);
    tryme->addEdge(adj, 'b','a',2);
    tryme->addEdge(adj, 'c','b',5);
    tryme->addEdge(adj, 'c','d',1);
    tryme->addEdge(adj, 'c','e',2);
    tryme->addEdge(adj, 'c','a',4);
    tryme->addEdge(adj, 'd','h',4);
    tryme->addEdge(adj, 'd','f',3);
    tryme->addEdge(adj, 'd','c',1);
    tryme->addEdge(adj, 'd','a',6);
    tryme->addEdge(adj, 'e','c',2);
    tryme->addEdge(adj, 'e','i',3);
    tryme->addEdge(adj, 'e','g',5);
    tryme->addEdge(adj, 'e','f',1);
    tryme->addEdge(adj, 'f','g',4);
    tryme->addEdge(adj, 'f','e',1);
    tryme->addEdge(adj, 'f','d',3);
    tryme->addEdge(adj, 'g','e',5);
    tryme->addEdge(adj, 'g','f',4);
    tryme->addEdge(adj, 'h','d',4);
    tryme->addEdge(adj, 'i','e',3);

    tryme->printGraph(adj, V);
    tryme->DFS(adj,'a');
    tryme->BFS(adj,'a');

If I only call print, or only call DFS, or only call BFS, the code works fun, if I call them one by one, below is the output

Adjacency list: 
Head: a -> Id: b Weight: 2 -> Id: c Weight: 4 -> Id: d Weight: 6 -> nullptr
Adjacency list: 
Head: b -> Id: c Weight: 5 -> Id: a Weight: 2 -> nullptr
Adjacency list: 
Head: c -> Id: b Weight: 5 -> Id: d Weight: 1 -> Id: e Weight: 2 -> Id: a 
Weight: 4 -> nullptr
Adjacency list: 
Head: d -> Id: h Weight: 4 -> Id: f Weight: 3 -> Id: c Weight: 1 -> Id: a 
Weight: 6 -> nullptr
Adjacency list: 
Head: e -> Id: c Weight: 2 -> Id: i Weight: 3 -> Id: g Weight: 5 -> Id: f 
Weight: 1 -> nullptr
Adjacency list: 
Head: f -> Id: g Weight: 4 -> Id: e Weight: 1 -> Id: d Weight: 3 -> nullptr
Adjacency list: 
Head: g -> Id: e Weight: 5 -> Id: f Weight: 4 -> nullptr
Adjacency list: 
Head: h -> Id: d Weight: 4 -> nullptr
Adjacency list: 
Head: i -> Id: e Weight: 3 -> nullptr
Traverse by DFS: 
d Traverse by BFS: 
a d 

Calling std::move on a return value - what should the signature be

Consider

class X
{
public:
    std::unique_ptr<int> m_sp;
    A m_a;

    A test1()
    {
        return std::move(m_a);
    }

    A&& test2()
    {
        return std::move(m_a);
    } 

    std::unique_ptr<int> test3()
    {
        return std::move(m_sp);
    }

    std::unique_ptr<int>&& test4()
    {
        return std::move(m_sp);
    }

    std::unique_ptr<int> test5()
    {
        return std::make_unique<int>(50);
    }
};

class A
{
public:
    A()
    {
        m_i = 1;
    }

    A(A&& other)
    {
        this->m_i = other.m_i;
        other.m_i = -1;
    }

    A& operator=(A&& other)
    {
        this->m_i = other.m_i;
        other.m_i = -1;
        return *this;
    }

    int m_i;
};

To exercise these classes

X x;
A y;
y.m_i = 10;
y = x.test1();

X x2;
A y2;
y2.m_i = 10;
y2 = x2.test2();

both call A's move assignment but only in the test1 case do we call A's move constructor. Why is that? Is it because as we cannot return a A&& (std::move will cast A to A&&, but test1 says it must return an A).

In general, when one wants to move/transfer ownership of expensive member variables, do you want to specify the return to be an rvalue-reference (A&&) or an lvalue (A) type?

It feels a little unnatural as if you aren't using member variables, you let RVO/NRVO do it's thing and just return an lvalue. Take in the case of unique_ptr, when you've got an automatic variable you have a signature like test5(), but if you have a variable, not suitable for RVO/NRVO, like a member varaible should test3 or test4's signature be preferred.

Interested to know.

Thanks

Why does [=]{} have a lambda capture?

At an intuitive level, it makes sense that a lambda that needs to carry no state (through a reference or otherwise) should be cleanly convertible to a naked function pointer. However, I was recently surprised to see the following failing in GCC, Clang, and MSVC:

int main(int, char *[]) {
    void (*fp)() = []{}; // OK
  //fp = [=]{};          // XXX - no user defined conversion operator available
  //fp = [&]{};          // XXX - same ...
}

The C++17 spec (or at least visible public draft version N4713), refers in item 7 of § 8.4.5.1 [expr.prim.lambda.closure] to lambdas with and without captures:

The closure type for a non-generic lambda-expression with no lambda-capture whose constraints (if any) are satisfied has a conversion function to pointer to function with C++ language linkage (10.5) having the same parameter and return types as the closure type’s function call operator. ...

However, looking into the formal grammar you can see the following in § 8.4.5 [expr.prim.lambda]:

  • lambda-expression :
    • lambda-introducer compound-statement
    • ...
  • lambda-introducer :
    • [ lambda-captureopt ]
  • ...

and in § 8.4.5.2 [expr.prim.lambda.capture]:

  • lambda-capture :
    • capture-default
    • capture-list
    • capture-default, capture-list
  • capture-default :
    • &
    • =

So all the compilers were actually obeying the letter of the law to my dismay...

Why does the language define the existence of a capture as a narrow grammatical distinction in the declaration instead of basing it on whether the body contains references to any non-static/captured state?

programing the Oregon Trail in c++

I'm trying to write a c++ program for the "Oregon trail" game from the 80s and need help making and implementing a class for tracking the players distance travelled and whether they are at a fort or a river etc.

Type aliasing rules with vectors/arrays

I know this is safe regarding type aliasing:

Foo foo;
char* buf = reinterpret_cast<char*>(foo);

What about:

std::vector<Foo> vvv;
auto buf = reinterpret_cast<std::vector<char> *>(vvv);
auto ptr = new Foo[50];
auto ptr_buf = reinterpret_cast<char *>(vvv);

I guess this is not allowed, am I correct? The standard says nothing about this in chapter 3.10 (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3690.pdf).

split S to array[rows][columns] [on hold]

Function solution will return number of possible reservations. S contains reserved seat details in the format {1A 1B 2C 3D 5J} where A,B,C,D,J are columns and 1,1,2,3,5 are rows. Considering columns are from A to J at this moment and N < 100.

int solution(int N, string S){}

Operator overloading in variadic template inheritance

Imagine a code like this:

struct Foo
{
    int foo{0};
};

Foo operator+(const Foo& lhs, const Foo& rhs)
{
    Foo ret;
    ret.foo = lhs.foo + rhs.foo;
    return ret;
}

struct Bar
{
    int bar{0};
};

Bar operator+(const Bar& lhs, const Bar& rhs)
{
    Bar ret;
    ret.bar = lhs.bar + rhs.bar;
    return ret;
}

template<typename... Ts>
struct Fooz : public Ts...
{

};

template<typename... Ts>
Fooz<Ts...> operator+(const Fooz<Ts...>& lhs, const Fooz<Ts...>& rhs)
{
    // how can you call base class's operator+ here?
}

int main(int argc, char **argv)
{
    Fooz<Foo,Bar> fooz1{1,1}; // fooz1.foo == 1; fooz1.bar == 1;
    Fooz<Foo,Bar> fooz2{2,2}; // fooz2.foo == 2; fooz2.bar == 2;

    // auto fooz3 = fooz1 + fooz2 // fooz3.foo == 3; fooz3.bar == 3;
    return 0;
}

The variadic inheritance here is needed, since I want to have all the member variables from the base structs inherited to the variadic class (see main).

The question is: is it possible to call the base struct's operator+ inside FooBar's operator+ function?

Any help is appreciated!

c++ add data to a std::vector containing a std::tuple

Below is code that adds elements to a vector containing a std::pair

std::vector<std::pair<std::string, std::type_index>> args_;

template <class T>
            inline OperationEntry& setArg(const std::string& name)
            {
                args_.push_back({name, typeid(T)});
                return *this;

            }

How do I add elements to a vector containing a std::tuple?

std::vector<std::tuple<std::string, std::type_index, Attribute>> args_;

template <class T>
            inline OperationEntry& setArg(const std::string& name, Attribute value = Attribute())
            {
                args_.push_back({name, typeid(T), value});
                return *this;

            }

I tried args_.push_back(std::make_tuple(name, typeid(T), value));

I am getting this error:

[GCC] converting to
‘std::vector<std::tuple<std::__cxx11::basic_string<char,
std::char_traits<char>, std::allocator<char> >, std::type_index,
mv::Attribute> >::value_type {aka
std::tuple<std::__cxx11::basic_string<char, std::char_traits<char>,
std::allocator<char> >, std::type_index, mv::Attribute>}’ from
initializer list would use explicit constructor ‘constexpr std::tuple<
<template-parameter-1-1> >::tuple(_UElements&& ...) [with _UElements =
{const std::__cxx11::basic_string<char, std::char_traits<char>,
std::allocator<char> >&, const std::type_info&, mv::Attribute&};
<template-parameter-2-2> = void; _Elements =
{std::__cxx11::basic_string<char, std::char_traits<char>,
std::allocator<char> >, std::type_index, mv::Attribute}]’

understanding std::findif() using a lamda on std::pair

It is my understanding that std::find_if() below returns an iterator to the first element in the range of arg for which the third argument (lamda function) returns true. Is that correct?

Could somebody explain why there isn't an iterator defined like this std::pair<std::string, std::type_index>::iterator = std::find_if(...)?

Where is the iterator returned by std::findif() stored and how can you call ->second on its own and not on an iterator?

and why is there a != args_.end() after the closing brace of std::find_if?

std::type_index argType(const std::string& name) const
{
    return std::find_if(args_.begin(), args_.end(),
        [&name](std::pair<std::string, std::type_index> arg)->bool
        {
            return arg.first == name;
        }
    )->second;
}

std::bind and variadic template function

Is this even possible?

#include <iostream>
#include <functional>

enum class Enum {a, b, c };

class Dispatch {
    public:
    void check(uint16_t) { std::cout << "check 16\n"; }
    void check(uint32_t) { std::cout << "check 32\n"; }
    void check(uint64_t) { std::cout << "check 64\n"; }

    template<Enum E, typename... A>
    void event(A&&... args) {
        tag_event(Tag<E>(), std::forward<A>(args)...);
    }

    private:
    template<Enum E> struct Tag {};    
    void tag_event(Tag<Enum::a>, uint16_t) { std::cout << "a\n"; }
    void tag_event(Tag<Enum::b>, uint16_t) { std::cout << "b\n"; }
    void tag_event(Tag<Enum::c>, uint16_t) { std::cout << "c\n"; }
};

void exec(std::function<void()>&& func) { func(); }

int main() {
    Dispatch d;

    // all good    
    exec(std::bind(static_cast<void(Dispatch::*)(uint16_t)>(&Dispatch::check), &d, uint16_t()));
    exec(std::bind(static_cast<void(Dispatch::*)(uint32_t)>(&Dispatch::check), &d, uint32_t()));
    exec(std::bind(static_cast<void(Dispatch::*)(uint64_t)>(&Dispatch::check), &d, uint64_t()));

    // all good
    d.event<Enum::a>(uint16_t());
    d.event<Enum::b>(uint16_t());
    d.event<Enum::c>(uint16_t());

    // but how do we bind an event<> call?
    exec(std::bind(static_cast<void(Dispatch::*)(uint16_t)>(&Dispatch::event<Enum::a>), &d, uint16_t()));
}

So I'm trying to bind a call to the variadic template method but get the following compiler error...

In function 'int main()':
42:86: error: no matches converting function 'event' to type 'void (class Dispatch::*)(uint16_t) {aka void (class Dispatch::*)(short unsigned int)}'
13:10: note: candidate is: template<Enum E, class ... A> void Dispatch::event(A&& ...)

Any suggestions short of exposing all the tag overloads instead?

One template specialization for several enum values

Normally if I want to have a templated (data) class by enum I would write something like this

enum class Modes : int
{
    m1 = 1,
    m2 = 2,
    m3 = 3
};

template <Modes M>
class DataHolder
{
};

template<>
class DataHolder<Modes::m1>
{
    public: int a = 4;
};

Then if I want the same specialization for the Modes::m1 as for the Modes::m2 I would write the same specialization again. Is there a way to write one specialization for several enum values? I have tried it with SFINAE, but I am not succesfull.

template <Modes M, typename = void>
class DataHolder
{
};

template<Modes M, typename = typename std::enable_if<M == Modes::m1 || M == Modes::m2>::type>
class DataHolder
{
    public: int a = 4;
};

This doesn't not compile. Especially, after I would like to carry on with different specialization for Modes::m3. I've tried many similiar solution found here on SO, but nothing seems to be solving the issue.

Select function based on if template is pointer/reference or none

I would like to provide different implementations of a function dependant on if it is a pointer, a reference or a regular type. This is my code so far:

template<class T,
         class = typename std::enable_if_t<std::is_reference<T>::value>>
void f(T && in)
{}

// This causes redefinition error 
template<class T,
    class = typename std::enable_if_t<std::is_pointer<T>::value>>
void f(T && in)
{}

template<class T,
    class = typename std::enable_if_t<!std::is_reference<T>::value>,
    class = typename std::enable_if_t<!std::is_pointer<T>::value>>
void f(T && in)
{}

The middle function causes:

12:13: error: redefinition of 'template<class T, class> void f(T&&)' 7:13: note: 'template<class T, class> void f(T&&)' previously declared here

Funnily only the first and last function together compile.

Any ideas how to fix it or simplify this code.

Is this compiler bug?

I have following C++ code

#include <functional>
#include <stdio.h>
#include <string>

int main()
{
    std::function<void(int)> func;
    int capture = 1234;

    printf("outside capture=%d\n", capture);

    if (capture) {
        func =
            [capture](int x) {
                printf("inside capture=%d\n", capture);
            };

        func(0);
    }
}

Compile (with -Os, -O2 or -O3) and execute it, result is

outside capture=1234
inside capture=67213

Compile with -O1 or without -O?, the result is

outside capture=1234
inside capture=1234

Is there any thing wrong? I doubt this is compiler or C++ standard library bug. Could you give me some comments?

gcc-linaro-6.1.1-2016.08-x86_64_arm-linux-gnueabihf/bin/arm-linux-gnueabihf-g++ -v

Using built-in specs.
COLLECT_GCC=/opt/arm/gcc-linaro-6.1.1-2016.08-x86_64_arm-linux-gnueabihf/bin/arm-linux-gnueabihf-g++
COLLECT_LTO_WRAPPER=/opt/arm/gcc-linaro-6.1.1-2016.08-x86_64_arm-linux-gnueabihf/bin/../libexec/gcc/arm-linux-gnueabihf/6.1.1/lto-wrapper
Target: arm-linux-gnueabihf
Configured with: /home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg/target/arm-linux-gnueabihf/snapshots/gcc-linaro-6.1-2016.08/configure SHELL=/bin/bash --with-mpc=/home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg/target/arm-linux-gnueabihf/_build/builds/destdir/x86_64-unknown-linux-gnu --with-mpfr=/home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg/target/arm-linux-gnueabihf/_build/builds/destdir/x86_64-unknown-linux-gnu --with-gmp=/home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg/target/arm-linux-gnueabihf/_build/builds/destdir/x86_64-unknown-linux-gnu --with-gnu-as --with-gnu-ld --disable-libstdcxx-pch --disable-libmudflap --with-cloog=no --with-ppl=no --with-isl=no --disable-nls --enable-c99 --enable-gnu-indirect-function --with-tune=cortex-a9 --with-arch=armv7-a --with-fpu=vfpv3-d16 --with-float=hard --with-mode=thumb --disable-multilib --enable-multiarch --with-build-sysroot=/home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg/target/arm-linux-gnueabihf/_build/sysroots/arm-linux-gnueabihf --enable-lto --enable-linker-build-id --enable-long-long --enable-shared --with-sysroot=/home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg/target/arm-linux-gnueabihf/_build/builds/destdir/x86_64-unknown-linux-gnu/arm-linux-gnueabihf/libc --enable-languages=c,c++,fortran,lto --enable-checking=release --disable-bootstrap --build=x86_64-unknown-linux-gnu --host=x86_64-unknown-linux-gnu --target=arm-linux-gnueabihf --prefix=/home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg/target/arm-linux-gnueabihf/_build/builds/destdir/x86_64-unknown-linux-gnu
Thread model: posix
gcc version 6.1.1 20160711 (Linaro GCC 6.1-2016.08) 

Different member function definition according to compile-time condition

As per this answer, I've been using

 template <typename T,  typename = typename enable_if<bool_verfier<T>()>::type> > classMember(const T& arg);

As the function signature for several class members, where bool_verifier<T>() is a templated function that asserts that a particular class T fulfills certain requirements, with return type constexpr bool. This ensures a particular overload of classMember(const T& arg) is only used for particular argument types, but it is not possible to do this when there are multiple overloads with the same prototype/argument signature, because the compiler won't allow it:

// ...
template <typename T,  typename = typename enable_if<bool_verfier<T>()>::type> > classMember(const T& arg);
template <typename T,  typename = typename enable_if<!(bool_verfier<T>())>::type> > classMember(const T& arg);
// ...

which causes the following compilation error:

 ‘template<class T, class> void myClass::classMember<T>(const T&)’ cannot be overloaded with ‘template<class T, class> void std::myClass<T>::classMember(const T&)’

If I need classMember to have different definitions according to whether or not bool_verifier<T>() returns true, what would be the correct syntax/member declaration? Alternatively, is there a way to call bool_verifier<T> from an #if precompiler conditional statement?

std::tuple equivalent of std::pair's second member?

I'm converting this function to use std::tuple which does not have first and second memebers like std:pair.

std::type_index argumentType(const std::string& name) const
{
    return std::find_if(args_.begin(), args_.end(),
        [&name](std::pair<std::string, std::type_index> arg)->bool
        {
            return arg.first == name;
        }
    )->second;
}

I'm confused by the syntax ->second, what is this doing? and is thre equivalent std::get<1>(arg)

std::type_index argType(const std::string& name) const
{
    return std::find_if(args_.begin(), args_.end(),
        [&name](std::tuple<std::string, std::type_index, Attribute> arg)->bool
        {
            return std::get<0>(arg) == name;
        }
    )std::get<1>(arg);

Is there an alternative for 2d and 3d vector in C++?

I have been writing a performance critical application and i need to use 3d vectors frequently,however a lot of my friends are saying that 3d and 2d vectors are not good performance and i should check for alternatives. So is there a performance critical (a lot as the calculations should take only ms to complete) implementation that does what 3d and 2d vectors do?

Separated input by blank lines

enter image description here

How can I do to pass the blank line in input // Please tell me

static_cast dangling reference when downcasting

Is the following code correct or does it yield undefined behavior due to a dangling reference and why exactly is it correct:

class A {};
class B : public A {};

B& f(A& a) {
  // Dangling reference here?
  return static_cast<B&>(a);    
}

int main()
{
  A a;
  B& b = f(a);
}

Evaluation order of side effects for assignment operator in C++11

I would very much appreciate it if someone could give a clarification on the sequencing of side effects for assignment statements in C++11. E.g., point me to the relevant standard text that deals with it.

The page on evaluation order on cpprefence.com states the following regarding assignments:

8) The side effect (modification of the left argument) of the built-in assignment operator and of all built-in compound assignment operators is sequenced after the value computation (but not the side effects) of both left and right arguments, and is sequenced before the value computation of the assignment expression (that is, before returning the reference to the modified object)

What is meant by "(but not the side effects)? Are the side effects unsequenced, inderminately sequenced or sequenced after the modification of the left argument (or perhaps even sequenced after the returning of the reference?

As an example when do the post-increment operations take place in: while (*tgt++= *src++);

It seems clear from evaluation order that the value calculations are performed first, so *tgt and *src are calculated first. But is it known when post-increment side effects occur?

Best regards

How to create alias for template type?

I have some template classes whose declaration looks like this:

template <typename T, typename A, typename B, typename C>
class foo1;

template <typename T, typename A, typename B, typename C>
class foo2;

...

I use them in the following context (every foo* is instantiated with A and B and C which bar was instantiated with) :

template <typename A, typename B, typename C>
class bar {
    foo1<int, A, B, C> f1;
    foo2<int, A, B, C> f2;
    foo2<char, A, B, C> f3;
};

For simplicity and clarity reasons I would like to be able to omit A, B and C parameters inside bar and just write:

...
foo1<int> f1;
...

I know that I could just use alias template for all foo types like this:

template <typename T>
using foo1_a = foo1<T, A, B, C>;

but there could be a lot for foo types and it woul require creating alias for all of them.

I tried to put all this aliases in a class:

template <typename A, typename B, typename C>
class types {
    template <typename T>
    using foo1_a = foo1<T, A, B, C>;

    ...
};

and then usage looks like this:

...
using t = types<A,B,C>;
typename t::template foo1_a<int> f1;
...

but in my opinion this looks even worse...

Is it possible to achieve this in some other way?

Statements out of function, but where?

Trying to get my last assignment in for the quarter, balance my job, and my other class. I would love an extra set of eyes to tell me where in the world my statements go out outside of my function:

This is an implementation file. The associated header is throwing no errors.

I get the following errors:

1.) In file included from tests.cpp:7:0: GBoard.cpp:31:2: error: expected unqualified-id before ‘for’ for(int r=0;r<15;r++) ^~~

2.) GBoard.cpp:31:14: error: ‘r’ does not name a type for(int r=0;r<15;r++) ^

But I am pretty sure 2 is part of my code being outside of the function somehow.

Here is my code, parts redacted so I don't get hit w/ plagiarism:

bool Gfunction::makeMove(int redacted,int redacted,char secret) {

if(redacted >= 0 && redacted < 15 && redacted >= 0 && redacted<15)
{
    if(redacted() == UNFINISHED && function[redacted][redacted] == '.')
    function[redacted][redacted] = secret;
    return true;
}   
    else
{
    return false;

}

int track = 0;


for(int r=0;r<15;r++)
{
    track = 0;
        for(int c=0;c<15;c++)
        {
                if(function[r][c] == secret)
                {
            track++;
                if(track==5)
                    {
                            if(secret == 'x')
                            secret squirrel stuff = X_WON;
                            else
                        secret squirrel stuff = O_WON;
                            return true;
                }
            }
            else
            {
                track = 0;
            }
    }

}   



for(int r=0;r<15;r++)
{
        track = 0;
        for(int c=0;c<15;c++)
        {
                if(function[r][c] == secret)
                {  
                    track++;
                    if(track==5)
                    {
                        if(secret == 'x')
                            secret squirrel stuff = X_WON;
                            else
                            secret squirrel stuff = O_WON;
                            return true;
                    }

                }
                    else
                {
                        track = 0;
                }
        }

}



    int r = 0, c = 0;
    for(int redacted = 0; redacted<15; redacted++)
    {
        r = redacted;
            c = 0;
            track = 0;
            while(r < 15 && c < 15)
            {
                if(function[r][c] == secret)
                {
                    track++;
                    if(track == 5)
                    {
                            if(secret == 'x')
                            secret squirrel stuff = X_WON;
                            else
                            secret squirrel stuff = O_WON;
                            return true;
                    }
            }
                    else
                    {
                            track = 0;
                    }
                            r++;
                            c++;
    }
}

for(int redacted = 0; redacted<15; redacted++)
{
        r=0;
        c=redacted;
        track=0;
        while(r<15 && c<15)
            {
                if(function[r][c] == secret)
                {
                        track++;
                        if(track == 5)
                        {
                            if(secret == 'x')
                            secret squirrel stuff = X_WON;
                            else
                            secret squirrel stuff = O_WON;
                            return true;
                    }
        }
                    else
                    {
                            track = 0; 
                    }
                            r++;
                            c++;
            }
    }


for(int redacted=0; redacted<15; redacted++)
{
    r=redacted;
    c=15-1;
    track=0;
    while(r<15 && c>=0)
    {
                if(function[r][c] == secret)
                {
                    track++;
                    if(track == 5)
            {
                if(secret == 'x')
                        secret squirrel stuff = X_WON;
                        else
                        secret squirrel stuff = O_WON;
                        return true;
                    }
        }
                        else
                {
                        track = 0;
                }
                        r++;
                        c--;
    }
}


for(int redacted=15-1;redacted>=0;redacted--)
{
        r=0;
        c=redacted;
        track=0;
        while(r<15 && c>= 0)
        {
                if(function[r][c] == secret)
                {
                    track++;
                    if(track == 5)                    
                    {
                            if(secret == 'x')
                            secret squirrel stuff = X_WON;
                            else
                            secret squirrel stuff = O_WON;
                            return true;
                    }
        }
                    else
                    {
                        track = 0;
                    }
                        r++;
                        c--;
        }
    } 


for(int r=0;r<15;r++)
{
        for(int c=0;c<15;c++)
        {
        if(function[r][c] == '.')
            {
                secret squirrel stuff = UNFINISHED;
                return true;
        }
    }
}  
    secret squirrel stuff = DRAW;
    return true;

}

What the benefits by using the template

I'm reading the pbrt and it has defined a type:

template <int nSpectrumSamples>
class CoefficientSpectrum;
class RGBSpectrum : public CoefficientSpectrum<3> {
    using CoefficientSpectrum<3>::c;
typedef RGBSpectrum Spectrum;
// typedef SampledSpectrum Spectrum;

And the author said:

"We have not written the system such that the selection of which Spectrum implementation to use could be resolved at run time; to switch to a different representation, the entire system must be recompiled. One advantage to this design is that many of the various Spectrum methods can be implemented as short functions that can be inlined by the compiler, rather than being left as stand-alone functions that have to be invoked through the relatively slow virtual method call mechanism. Inlining frequently used short functions like these can give a substantial improvement in performance."

1.Why template can inline function but normal way can not?

2.Why do normal way has to use the virtual method?

Linkage to the entire header file: https://github.com/mmp/pbrt-v3/blob/master/src/core/spectrum.h

mardi 27 novembre 2018

Why would I ever need a move assignment operator?

Suppose I have a class A that has explicitly defined copy and move constructors and a destructor. Now it's time for me to define the assignment operators: copy and move.

For the copy constructor, I will use implement a non-throwing swap function and use that:

A& operator = (A const & a)
{
     A(a).swap(*this);
     return *this;
}

Now, why don't I replace the manual copying with passing the parameter by value?

A& operator = (A a)
{
     swap(a);
     return *this;
}

So far, so good. Now all I need to do is define the move assignment operator to complete the rule of 5. But do I really need to do that? In a scenario where I need to move-assign something, that something will be moved to the parameter a of my copy-assignment operator via the move constructor and then simply swapped with *this, which is a non-throwing fast operation.

Are there any drawbacks/caveats to my approach? If we have defined a good copy-assignment operator that uses the copy-and-swap idiom, why would we ever need a separate move assignment?

Using ffmpeg library with Qt framework results in error

When I include:

extern "C" {
#include <libavcodec/avcodec.h>
}

I am getting the error:

undefined reference to QVideoSurfaceFormat::QVideoSurfaceFormat(QSize const&, QVideoFrame::AVPixelFormat, QAbstractVideoBuffer::HandleType)

without the include - build success.

My guess that include brings some defines that breaks QVideoSurfaceFormat defenition.
Have someone faced with the similar issue?

Return lambda from ternary operator

I can return a lambda from ternary operator if both the lambda doesn't capture anything.

 auto lambda1 = 1==1
             ? [] (int a) {std::cout << "First\n";}
             : [] (int a) {std::cout << "Second\n";};

 auto lambda2 = 1==2
             ? [] (int a) {std::cout << "First\n";}
             : [] (int a) {std::cout << "Second\n";};
lambda1(10);
lambda2(10);

This works fine.

But this doesn't

int n = 10;

auto lambda3 = 1==1
             ? [&n] (int a) {std::cout << "First\n";}
             : [&n] (int a) {std::cout << "Second\n";};

 auto lambda4 = 1==2
             ? [&n] (int a) {std::cout << "First\n";}
             : [&n] (int a) {std::cout << "Second\n";};
lambda3(10);
lambda4(10);

The error is main.cpp:20:18: error: operands to ?: have different types 'main()::<lambda(int)>' and 'main()::<lambda(int)>' ? [&n] (int a) {std::cout << "First\n";}

I wonder why capturing the same variable changes the type of lambda?

Type inference of 'auto' when using range-for loop in multidimensional arrays

After int ia[3][4]{}. Then I run:

for(auto row : ia) // row should be type int*
    for(int *j = std::begin(*row); j!= end(*row); ++j) // error!!
        std::cout << *j << std::endl;

According to C++ primer 5th:

Because row is not a reference, when the compiler
initializes row it will convert each array element (like any other 
object of array type)
to a pointer to that array’s first element

So if row is a pointer to ia's first element, then why error happens?

Many thanks!

returning a rvalue parameter as a rvalue reference

On this thread (Should I return an rvalue reference parameter by rvalue reference?), it is written that The parameter cannot be a temporary (which is just what rvalue references represent). If I understand this sentence well, this code should not be correct

#include <string>
#include <iostream>
std::string &&f(std::string &&a) {
    return std::move(a);   
}

int main() {
    std::string a = f("lol");
    std::cout << a << std::endl;
    return 0;
}

However, when we look to std::get, it seems that it returns rvalue reference for temporary tuple, and I actually think that there is no issue with using std::get with temporary tuple.

So, I think I misunderstand the sentence above, and the prior code is correct. However, this one is not correct :

#include <string>
#include <iostream>
std::string &&f(std::string &&a) {
    return std::move(a);   
}

int main() {
    std::string &&a = f("lol");
    std::cout << a << std::endl;
    return 0;
}

It would be correct if the function returns a value and not rvalue reference. Am I correct?

Is it safe to use a C++ mutex in openmp code

Is it safe to use a C++11 mutex inside openMP 4.5 code? The idea is that I am using a logging library which protects each std::cout using a C++ mutex so that the outputs to cout are not scrambled when running with multiple threads. Inside my openMP code I may want to use this logging library to print some messages. Is it safe to do so?

Avoid raw new operotor [on hold]

I want to draw a keyboard.

For this purpose, I need to create multiple instanses of object Key and save some data about each key in somewhere. I don't want to user raw operator new and do some thing like this:

std::vector<Key*> keys;
keys.push_back(new Key());

Is it a good idea to save shared_ptr(s) in vector?

std::vector<std::shared_ptr<Key>>

Thanks.

How can I implement an assignment operator in a class template?`

I thought my problem was answered by this, but I can't get the following to compile:

#include <string>

template<class C>
class tKeySet {
  protected:
    bool set;
    static const std::string key;
};

template<class C, typename T>
class tKeySetType : private tKeySet<C> {
  protected:
    T m_val;
};

template<class C>
class tKeySetString: private tKeySetType<C, std::string> {
  public:
    tKeySetString<C>& operator=(const std::string &str) {
        this->set = true;
        this->m_val = str;
        return *this;
    }
};

class foo : private tKeySetString<foo> { };
template<> const std::string tKeySet<foo>::key = "foo key";

int main(void) {
    foo f;

    f = std::string("foo");

    return 0;
}

How can I make the assignment operator in tKeySetString<C> work with std::string?

Variables are being overwritten when I put values into an array

This function is supposed to take user inputs and put them into a map object. The width and length are being stored as variables in Map and id, x, and y are being stored in an array.

void Game::createMap()
{
    Map map1;
    int width;
    int length;
    int id;
    int x;
    int y;
    string answer = "1";


    cout << "Enter a map width: " << endl;
    cin >> width;
    cout << "Enter a map length: " << endl;
    cin >> length;
    map1.setWidth(width);
    map1.setLength(length);


    while(answer != "2")
    {
        cout << "Would you like to add a player? 1) Yes 2) No" << endl;
        cin >> answer;
        switch (stoi(answer))
        {
            case 1:
                cout << "Choose player id: " << endl;
                cin >> id;
                cout << "Enter an x coordinate: " << endl;
                cin >> x;
                cout << "Enter a y coordinate: " << endl;
                cin >> y;
                map1.setPlayers(id, x, y, map1.getNumPlayers());

                break;


            case 2:
                break;
            default:
                cout << "Enter a valid input" << endl;
                break;
        }
    }
    mapVector.push_back(map1);
}

This is the function that puts the user inputs into the array:

void Map::setPlayers(int x, int y, int player, int n)
{
    position[n][0] = player;
    position[n][1] = x;
    position[n][2] = y;
    cout << width << endl;
    cout << length;
}

For some reason, after the setPlayers function gets called, my width and length variables get set to the values gotten from the user for id and x. I do not know why these variables are being changed. It seems like when I am writing to the array it is overwriting the variables.

Unable to allocate a 2D vector in c++

I use dfs in a question but I have not called dfs in the main till now and my program is crashing, Recently I was programming in c and now I switched to cpp, so I am new to cpp,I know where I did mistake in vectors please tell what can I improve I know vector can increase there size automatically.

    #include<iostream>
    #include<vector>
    using namespace std;
    const int MAX = 100000;

    bool visited[MAX] = {0};
    int intime[MAX];
    int outtime[MAX];

    int timer = 0;
    void dfs(vector<vector<int>> graph, int v) 
    {
        visited[v] = true;
        timer++;
        intime[v] = timer;
        vector<int>::iterator it = graph[v].begin();
        while (it!=graph[v].end()) {
            if (visited[*it] == false)
            {
                dfs(graph, *it);
            }
            it++;
        }
        ++timer;
        outtime[v] = timer;
    }

    int main() 
    {
        vector<vector<int>> graph;
        graph[1].push_back(2);
        graph[1].push_back(3);
        graph[3].push_back(6);
        graph[2].push_back(4);
        graph[2].push_back(5);
        graph[5].push_back(7);
        graph[5].push_back(8);
        graph[5].push_back(9);  
        system("pause");
    }

Two-dimensional array vs projection onto a one-dimensional with a calculated index: which is faster?

I've seen regular 2-D arrays, e.g. arr[10][12], and I've seen projections onto a 1-D arr[120] which is then indexed into with arr[y * 10 + x] (mostly in lower-level systems; I think some don't support multidimensionals?) I've seen similar questions concerning c# and ruby, but those are both interpreted languages and run differently. In a language like c or c++, which would generally be faster? Why?
Thank you.

Wrapping non type template constants to avoid mixing parameters of same type

I have a template method taking non type template arguments. It has the following form:

template <long long connectionTimeout, long long sendTimeout, bool autoAck>
void create() { ... }

It is a utility function in another header, and what annoys me in the caller's code is that the constants are not typed.

Meaning, instead of this way of calling:

create<1, 2, true>();

I prefer to have the following:

create<
    connection_timeout {1},
    send_timeout {2},
    auto_ack {true}
>();

With the create function guaranteeing that a send_timeout cannot be passed instead of a connection_timeout.

I started writing a proof of concept, however, with some gaps. I'd like to make it work with C++11/14. However, I had to use C++17 constructs to make things work until now. That being said, I don't mind C++17 solutions to get an idea if this can be done.

What is lacking in the following is the compile time check that the types match. However, the syntax in the main is what I desire to have.

#include <iostream>
#include <string>

template <typename T, T userSpecifiedValue>
struct compile_time_constant_wrapper
{
   using type = T;
   static const T defaultValue = userSpecifiedValue;

   constexpr operator T() const
   {
       return value;
   }

   T value = defaultValue;
};

using connection_timeout = compile_time_constant_wrapper<long long, 5000>;
using send_timeout = compile_time_constant_wrapper<long long, 10>;
using auto_ack = compile_time_constant_wrapper<bool, false>;

struct ComplicatedToBuild
{
    long long connectionTimeout;
    long long sendTimeout;
    bool autoAck;
};

template <typename T, long long connectionTimeout = connection_timeout {}, long long sendTimeout = send_timeout {}, bool autoAck = auto_ack {}>
struct create
{
    operator T() const
    {
        return T{connectionTimeout, sendTimeout, autoAck};
    }
};

std::ostream& operator<<(std::ostream& out, const ComplicatedToBuild& complicated)
{
    out << "connection timeout = " << complicated.connectionTimeout << ", "
        << "send timeout = " << complicated.sendTimeout << ", "
        << "auto ack = " << complicated.autoAck;
    return out;
}

int main()
{
    ComplicatedToBuild defaultValuesCase = create<ComplicatedToBuild>();
    std::cout << "defaultValuesCase: " << defaultValuesCase << std::endl;

    ComplicatedToBuild customizedCase = create<
           ComplicatedToBuild,
           connection_timeout {2500},
           send_timeout {5},
           auto_ack {true}
    >();
    std::cout << "customizedCase: " << customizedCase << std::endl;

    ComplicatedToBuild compilationErrorCase = create<
           ComplicatedToBuild,
           send_timeout {5},
           connection_timeout {2500},
           auto_ack {true}
    >();
}

In my case, the class ComplicatedToBuild is not a plain struct. And the values required to build it are known at compile time. This is why I thought of using non type templates.

Como hacer un agregar y listar, en una lista de listas de manera recursiva? [on hold]

https://pastebin.com/nTuCi9UA

#include <bits/stdc++.h>
using namespace std;
class Nodo{
        public:
                int dato;
                Nodo *nodo;
                vector<Nodo *> lista;
                int i =0;
                Nodo (int dato){
                        this->dato = dato;
                        i =0;  
                }
                Nodo(){  
                }
}

Using tuple as a parameter of a function

Hi I'm trying to pass a tuple as a parameter to a function. I would like to not to specify the amount of elements in the tuple (I followed this example: tuple as function argument)

What is missing now is how I can count the number of element into the tuple in order to access it with std::get

#include<tuple>
#include<iostream>

template <typename... T> void fill(std::tuple<T...> values) {
    std::cout << std::tuple_size<T...>::value << '\n';
    //std::cout << std::get<0>(values) << '\n';
    //std::cout << std::get<1>(values) << '\n';
}
int main() {
    fill(std::make_tuple(2.));
    fill(std::make_tuple(2., 5));
}

tuple_size seems not suitable to be used (https://en.cppreference.com/w/cpp/utility/tuple/tuple_size)

Could I make a project with specific STL and linked to it a shared library which was compiled with another STL ?

I have a whole project, which runs with c++_static. Within this project, a one of the library is "Opencv", popular library.

This is c++ content compiled for android, she works with static linking without any Optimizations like VPVF3 Or NEON (best).

Then, after viewing a lot of articles/forums, I've seen that Opencv need optimizations on ARM If we want to make a several calculus by opencv.

To do that, I've compiled successfully Opencv (3.4.4) with NEON optimizations.

But when I want to link it in my project, I have a few undefined references, such as :

error: undefined reference to 'cv::read(cv::FileNode const&, std::__ndk1::vector

&)' error: undefined reference to 'cv::write(cv::FileStorage&, cv::String const&, std::__ndk1::vector > const&)' error: undefined reference to 'cv::KeyPointsFilter::retainBest(std::__ndk1::vector >&, int)' error: undefined reference to 'cv::read(cv::FileNode const&, std::__ndk1::basic_string, std::__ndk1::allocator >&, std::__ndk1::basic_string, std::__ndk1::allocator > const&)' error: undefined reference to 'cv::KeyPointsFilter::retainBest(std::__ndk1::vector >&, int)' error: undefined reference to 'cv::KeyPointsFilter::retainBest(std::__ndk1::vector >&, int)' error: undefined reference to 'cv::DescriptorMatcher::knnMatch(cv::_InputArray const&, cv::_InputArray const&, std::__ndk1::vector >, std::__ndk1::allocator > > >&, int, cv::_InputArray const&, bool) const' error: undefined reference to 'cv::DescriptorMatcher::knnMatch(cv::_InputArray const&, cv::_InputArray const&, std::__ndk1::vector >, std::__ndk1::allocator > > >&, int, cv::_InputArray const&, bool) const' error: undefined reference to 'cv::KeyPointsFilter::retainBest(std::__ndk1::vector >&, int)' error: undefined reference to 'cv::DescriptorMatcher::knnMatch(cv::_InputArray const&, cv::_InputArray const&, std::__ndk1::vector >, std::__ndk1::allocator > > >&, int, cv::_InputArray const&, bool) const' error: undefined reference to 'cv::DescriptorMatcher::knnMatch(cv::_InputArray const&, cv::_InputArray const&, std::__ndk1::vector >, std::__ndk1::allocator > > >&, int, cv::_InputArray const&, bool) const' error: undefined reference to 'cv::drawKeypoints(cv::_InputArray const&, std::__ndk1::vector const&, cv::InputOutputArray const&, cv::Scalar const&, int)' clang++: error: linker command failed with exit code 1 (use -v to see invocation) ninja: build stopped: subcommand failed.

Information -->

  • With Opencv without optimizations she was linked with static libraries with same ANDROID STL than the project (c++_static).

  • But until now I have never ever good happened when i would want to compile Opencv with NEON and c++_static, however with "gnustl_static" she's compiled perfectly.

RESUME INFORMATION :

without NEON --> STATIC LIB (c++_static). with NEON --> SHARED LIB (gnustl_static), why ?

Because, If I want to link these Opencv libs with NEON without the same STL, she must need to link with shared lib, I have seen that you can link a shared lib with other STL it will not create any problem, by the way that's my question.

Could I make a project with stl(c++_static) and linked to it a shared lib with stl(gnustl_static) ?

If you have any idea, I will be very grateful and you'll be very helpful !

How to add elements to n array tree structure recursively if we know connection between parent and children?

It is given that A is root and its children are B, C, D and also we know that B has a child E. My question is how to insert elements recursively instead of adding element by element if we know connection between them?

class Node { 
public: 
string key; 
vector<Node*> child; 

// constructor 
Node(string data) 
{ 
    key = data; 
} 
}; 

Node* root = new Node("A"); 
(root->child).push_back(new Node("B")); 
(root->child).push_back(new Node("C")); 
(root->child).push_back(new Node("D"));  
(root->child[0]->child).push_back(new Node("E"));

boost managed shared memory construction ends up with "bus error"

I have a code that is going to create a big segment on managed shared memory using c++ boost (about 2 Gigs). And if we don't have enough memory on the machine, it will receive bus error.

Actually, the error happens when I try to write on shared memory with use of construct function. When I create the segment, it doesn't receive any error. I've already check my segment's size and free size and they all would be showing values that if there was enough memory to allocate! (get_size returns 2000000000!). even if the machine has less than that!

I know that the OS makes the program think that there exists enough memory, but I have to run the code on different machines and it must work on all of them. I mean, it MUST NOT crash even if there doesn't exist enough memory and we should have a good exception to be thrown out in this case. No mater that there exists enough memory or not. And there must be a way to find this out programmatically.

So, I was wondering is there any way to understand whatever requesting memory exists or not "USING BOOST"?

Here is what I want (Or at least have in mind!)

// consider that we are going to create a shared memory segment with 2G size in a machine that only has 1G of RAM
boost::interprocess::managed_shared_memory segment(open_or_create, "name", 2000000000);
if (real_allocated_memory < actual_need)
    throw std::overflow_error("Not enough memory");
segment.find_or_construct(a huge object); // here is where I receive the error

Choose correct return type of template member function

I have a template class that looks like this:

template <typename T, std::size_t M, std::size_t N> // MxN matrix with elements of type T
struct Mtx{...}

// component wise division
template <typename U> Mtx operator/(const Mtx<U, M, N> &rhs) const 
{ return componentDivide(*this, rhs); }

What is the best way to ensure that the return type of functions like operator / is "correct"?

eg:

Mtx<float> * Mtx<unsigned> = Mtx<float>
Mtx<float> * Mtx<int>      = Mtx<float>
Mtx<float> * Mtx<double>   = Mtx<double>
Mtx<double> * Mtx<float>   = Mtx<double>
Mtx<short> * Mtx<int>      = Mtx<int>

Using iterators in nested loop through two vectors two match elements and erase from the vectors

I wanted to use the following loops to match elements from two vectors and then delete them from the vectors:

for(auto it1=left_unprocessed_event_arrays.begin(); it1!=left_unprocessed_event_arrays.end(); ++it1){
  for(auto it2=right_unprocessed_event_arrays.begin(); it2!=right_unprocessed_event_arrays.end(); ++it2){
    if(it1->header.stamp.nsec==it2->header.stamp.nsec){
      matching_event_arrays.push_back({*it1,*it2});
      left_unprocessed_event_arrays.erase(it1);
      right_unprocessed_event_arrays.erase(it2);
    }
  }
}

I then realised I couldn't do it like this, because using the erase() is making the iterators invalid.
Searching a solution brought me to this. Here someone suggests using the pointer that is returned by erase(), and then incrementing the iterator in the else-bracket. But When I increment only in the innerloop, it won't correctly go through the outer-loop. I'm struggling to see how I can make this work for my nested loop.
So my question is: How can I implement the solution of the linked answer for a nested loop? Or if there is another/better solution: what's that?

Use initialization list with boost-parameter

The following code will not compile because in the last call to 'demo' the compiler cannot deduce a type from the initialization-list.

#include <boost/parameter/name.hpp>
#include <boost/parameter/preprocessor.hpp>
#include <iostream>
#include <array>

BOOST_PARAMETER_NAME(arg)

BOOST_PARAMETER_FUNCTION(
    (void),
    demo,
    tag,
    (optional
    (arg, (std::array<int, 3>), (std::array<int,3>{}))
    )
    )
{
    std::cout << arg[1] << std::endl;
}


int main()
{   
    demo();
    demo(_arg=std::array<int,3>({1,2,3}));
    // 28:14: error: no match for 'operator=' 
    // (operand types are 'const boost::parameter::keyword<tag::arg>' 
    // and '<brace-enclosed initializer list>')
    demo(_arg={1,2,3});
}

Is there a way to combine initialization-lists with boost-parameter without adding an explicit call to the constructor of array?

lundi 26 novembre 2018

CLion is telling me that I have a undeclared identifier but I already have

#include <iostream>
#include <chrono>
#include <thread>
#include <ctime>
#include "turkey.h"

using namespace std;

// pause the program, sleep, for given number of milliseconds
void timeTick(int amount = 1000){
     this_thread::sleep_for(std::chrono::milliseconds(amount));
}

I'm working on debugging this assignment, but Clion is telling me that my 'this_thread' "use of undeclared identifier 'this_thread'" any suggestions would be great. I have the #include already but I can't seem to figure out the reason through google.

Implicit conversion looses integer precision

ALL,

I'm trying to write a cross-platform code to compile on Windows, *nix and OSX. The first 2 compiles fine, but Xcode give following warning:

Implicit conversion looses integer precision "std::map<int, std::vector<Foo *>>::size_type (aka 'unsigned long') to std::__t::map<int, std::__t::vector<Foo *, std::__t::allocator<Foo *> >, std::__t::less<int>, std::__t::allocator<std::__t::pair<const int, std::__t::vector<Foo *, std::__t::allocator<Foo *> > > >::key_type (aka int)

Is it just a matter of writing an operator<() function in Foo?

TIA!!

Adding words from a text file to a vector c++

I am trying to add each word from a file to a vector but if I make the size of the vector (500) and I only have 20 words in the file. The size of the vector is still considered 500. How do I fix this?

Am I doing this a bad way? Could this be made simpler?

void loadFile(string fileName)
{
    vector<string> fileContents(500);
    int p = 0;
    ifstream file;
    file.open(fileName);
    if (!file.is_open()) return;

    string word;
    while (file >> word)
    {
        fileContents[p] = word;
        p++;
    }

    for (int i = 0; i < fileContents.size(); i++)
    {
        cout << fileContents[i] << endl;
    }  
}

rvalue qualified method and const expression

Let's say I have one object with ref qualified methods :

struct A {
  void f() &{}                  // 1
  void f() &&{}                 // 2
  constexpr void f() const &{}  // 3
  constexpr void f() const &&{} // 4 really usefull?
};

now I want to perform something like :

static_assert(A{}.f();); // call 2 instead of 4, so does not work
constexpr A a;
static_assert(a.f();); // call 3, so works

What am I missing here?

c++: Error: No instance of overloaded function using std::map

#include <iostream>
#include <mutex>
#include <map>
#include <thread>

using namespace std;

//Global variable
std::mutex mu; //declare a mutex
std::map<std::string, int> threadIDs;

void run(int id) {
    std::unique_lock<std::mutex> map_locker(mu); 
    threadIDs.insert(std::make_pair(std::this_thread::get_id(), id));
    map_locker.unlock();
}

int main()
{
    std::thread t[5];
    for (int i = 0; i < 5; i++) {
        t[i] = std::thread(run, i);
    }
    for (int i = 0; i < 5; i++) {
        t[i].join();
    }
    return 0;    
}//end of the code

Hello, I am trying to execute 5 thread running the void run() function and save thread id and int value using std::map. However I get red underline underneath the '.' in threadIDs.insert(std::make_pair(std::this_thread::get_id(), id)); line saying no instance of overloaded function... I guess the error occurs because std::map wants a string and an int inside but I am trying to put std::this_thread::get_id() in the string place. How can I put the thread identity inside the std::map?

event based c++ library

I have to design/implement an event-based software for a non GUI based production system where different. I have never done any event-based programming before and also I cannot use any libraries other than standard c++14 or boost. I came across 2 libraries called boost.signal2 and boost.fibre. I was wondering under which scenario I should choose one over the other. It's not an opinion based question as I would like to know a quick reference when to choose what? or it's better to implement something of my own using callback.

C++ cannot declare variable var to be of abstract type Type1

I created a base class with two pure virtual functions. Each subclass overrides and implements one of the virtual functions that belong to base class.

Compilation fails in main,

saying cannot declare variable ‘rr’ to be of abstract type ‘Type1Renderer’

What causes this error and how can I fix this?

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


using namespace std;

#include <string>
#include <iostream>

struct TypeRenderer {
    virtual float render_type_1 (float v) = 0;
    virtual std::string render_type_2 (std::string& s) = 0;
};


struct Type1Renderer : TypeRenderer {

    float render_type_1 (float v) override {
        std::cout << "render type 1 with : " << v;
        return v;
    }
};

struct Type2Renderer : TypeRenderer {

    std::string render_type_2 (std::string& v) override {
        std::cout << "render type 1 with : " << v;
        return v;
    }
};


int main()
{
    Type1Renderer rr;

}

C++ Threadpool Bug

I tried to implement a threadpool in C++, but its running into issues. It compiles, but it keeps spitting out “terminate called without an active exception.” Its my understanding that this happens when a thread terminates without being joined, but all my threads are running a function that is an infinite loop; I am not sure how they could be terminating. I’m mostly new to threads in C++, so if somebody could explain what’s going wrong, I’d be very appreciative. Link to my the repo for my code is below.

Source code

Writing methods in the implementation file with templates

I'm trying to write a class which can have about 50+ methods. The class is templated like this:

template <typename T>
class xyz<T>
{
private:
    void method1(int x, int at);
public:
    xyz();
    ~xyz();
    void method2(T a);
    void method3(T a);
    void metho(T a);
    .. //Other methods
};

Now I would like to implement these methods in a separate implementation .cpp file, so i would have to do something like this:

#include "xyz.h"
template <typename T>
xyz<T>::xyz()
{
}

template <typename T>
xyz<T>::~xyz()
{
}
template <typename T>
void method1(T a){
..
}
template <typename T>
void method2(T a){
..
}

So as you can see, I have to make a template each time I implement a new method. Do I have any better way of doing this than making the template 50+ times? So that I'd only make it once and can reuse it every time? Sorry if this is too obvious (I believe it is).