lundi 30 avril 2018

Get return type of a variable to avoid signed integer overflow

I currently have something like this

std::atomic<std::chrono::time_point<std::chrono::steady_clock>> _blah
auto test = std::chrono::steady_clock::now() - _blah.load() > std::chrono::seconds(5); 

Because of second statement I get signed integer overflow warning. How can I get the return type of

std::chrono::steady_clock::now()

and then cast

_blah.load()

to that type to get rid of the warning ?

Casting with AVX intrinsics

There are two ways of casting with AVX2, either:

__m256i b = ...set register...
auto c = (__m256d)b; // version 1
auto d = _mm256_castsi256_pd(b); // version 2

I assume that both of these should give same results. The official manual from Intel says that there is zero runtime latency for version 2. Can I use version 1 as well with a zero latency assumption? In addition can I assume casting from any to any register type with version 2 is zero latency.

Defining constexpr static data members

So, I'm aware that in C++ static members can be initialized inside the class if they are a const literal type like the following

class test{
        static constexpr int stc = 1;
private:
        int a = 0;
        int b = 0;
        int c = 0;
};

and the static constexpr variable stc can be used where the compiler can directly substitute the value of the member i.e

int array[stc]; 

However, if used in a context where the value cannot be directly substituted by the compiler then the compiler generates an error unless the static member is defined outside the class like so:

constexpr int test::stc;

Why is this the case?

C++ Windows: Catching exception when executing external application into the program

I have the following function to execute a external program:

std::string exec(const char* cmd) {
    char buffer[128];
    std::string result = "";
    FILE* pipe = _popen(cmd, "r");
    if (!pipe) throw std::runtime_error("_popen() failed!");
    try {
        while (!feof(pipe)) {
            if (fgets(buffer, 128, pipe) != NULL)
                result += buffer;
        }
    } catch (...) {
        _pclose(pipe);
        throw;
    }
    _pclose(pipe);
    return result;
}

Is it possible to catch the exception in this way?

try
{
   exec(cmd.c_str());
}
catch(...)
{

}

Dynamic Zero-Length Arrays in C++

#include <stdlib.h>

void *operator new[](size_t size, int n){
    if( size != 0 && n != 0 )
        return calloc(n, size);
    return calloc(1, 1);
}

int main(){

    int * p1;
    const int i = 0;

//  p1 = new (20)  int[i] ; // Case 1 (OK)
    p1 = new (20) (int[i]); // Case 2 (Warning)

    if( p1 == 0 )
        return 1;
    return 0;
}

This code (https://godbolt.org/g/hjo7Xn) compiles successfully with Clang 6.0.0, however, GCC 7.3 issues a warning saying that zero-length arrays are forbidden in C++. If the parentheses are removed (Case 1), the warning goes away.

Unlike statically allocated zero-length arrays (C++03:8.3.4/1), dynamically allocated zero-length arrays are allowed (C++03:5.3.4/6). Nevertheless, in the C++ Standard the latter are explicitly allowed only when following one of the two possible syntax paths of the new-expression, that is, the one with new-type-id and without parentheses (Case 1).

Is it allowed by the C++ Standard to use the new-expression with a zero-length array following the second syntax path, that is, with type-id and parentheses (Case 2)?

The only related quote is C++03:5.3.4/5:

When the allocated object is an array (that is, the direct-new-declarator syntax is used or the new-type-id or type-id denotes an array type), the new-expression yields a pointer to the initial element (if any) of the array.

The wording (if any) would allow an array with no elements, however, it does not seem clear if it refers to both cases or only to the one with new-type-id and without parentheses (Case 1).

Thanks in advance.

Notes:

  1. ISO/IEC 14882:2003, Section 8.3.4, Paragraph 1:

    If the constant-expression (5.19) is present, it shall be an integral constant expression and its value shall be greater than zero.

  2. ISO/IEC 14882:2003, Section 5.3.4, Paragraph 6:

    The expression in a direct-new-declarator shall have integral or enumeration type (3.9.1) with a non-negative value.

  3. ISO/IEC 14882:2003, Section 5.3.4, Paragraph 7:

    When the value of the expression in a direct-new-declarator is zero, the allocation function is called to allocate an array with no elements.

  4. ISO/IEC 14882:2003, Section 5.3.4, Paragraph 1:

    new-expression:

    ::opt new new-placementopt new-type-id new-initializeropt

    ::opt new new-placementopt ( type-id ) new-initializeropt

  5. Although the above quotes are from the C++03 Standard, to the best of my knowledge this issue is still unclear in newer versions of the C++ Standard (C++11, C++14 and C++17).
  6. Interesting Herb Sutter's post about zero-length arrays.
  7. The code in the example is a slightly modified test from SolidSands' SuperTest suite.

WM_CREATE GRAPHICS DEPENDECIES Gaps in shape drawing algoritms

Ricently i have added to Planet Chili framework, menu with popup tabs And also i have wrote simple function for drawing thin line circle and line and combining both is causing visble gaps in shapes.

[1]http://forum.planetchili.net/download/file.php?id=2733 "frame"

when I will remove WM_CREATE and WM_COMMAND section averything goes back to normal.

case WM_CREATE:
{
    HMENU hMenu, hSubMenu;

    hMenu = CreateMenu();

    hSubMenu = CreatePopupMenu();
    AppendMenu(hSubMenu, MF_STRING, ID_FILE_EXIT, L"E&xit");
    AppendMenu(hMenu, MF_STRING | MF_POPUP, (UINT)hSubMenu, L"&File");

    hSubMenu = CreatePopupMenu();
    AppendMenu(hSubMenu, MF_STRING, ID_STUFF_GO, L"&Go");
    AppendMenu(hMenu, MF_STRING | MF_POPUP, (UINT)hSubMenu, L"&Stuff");

    SetMenu(hWnd, hMenu);

    break;
}
case WM_COMMAND:
{
    switch (LOWORD(wParam))
    {
    case ID_FILE_EXIT:
        PostMessage(hWnd, WM_CLOSE, 0, 0);
        break;
    case ID_STUFF_GO:
        ShowMessageBox(L"You clicked Go!", L"Woo!");

        break;
    }

    break;

}

this is my repo https://github.com/oBornToCreateo/chili_framework

how to make copy of unique_ptr wih custom deleter

I am getting compilation errors if I make a copy of unique_ptr with custom deleter . Please some one help me out .

#include <iostream>
#include<memory>
#include <algorithm>
using namespace std;

auto del = [](int *p) { cout <<"obj deleted "<<endl;delete p;};
int main()
{
   unique_ptr<int, decltype(del)> p1(new int(10), del);
   unique_ptr<int,decltype(del)> p2;
   p2 = std::move(p1);
}

Errors:

C:\Program Files (x86)\CodeBlocks\MinGW\lib\gcc\mingw32\5.1.0\include\c++\tuple||In instantiation of 'constexpr std::_Head_base<_Idx, _Head, true>::_Head_base() [with unsigned int _Idx = 1u; _Head = <lambda(int*)>]':|
C:\Program Files (x86)\CodeBlocks\MinGW\lib\gcc\mingw32\5.1.0\include\c++\tuple|353|required from 'constexpr std::_Tuple_impl<_Idx, _Head>::_Tuple_impl() [with unsigned int _Idx = 1u; _Head = <lambda(int*)>]'|
C:\Program Files (x86)\CodeBlocks\MinGW\lib\gcc\mingw32\5.1.0\include\c++\tuple|202|required from 'constexpr std::_Tuple_impl<_Idx, _Head, _Tail ...>::_Tuple_impl() [with unsigned int _Idx = 0u; _Head = int*; _Tail = {<lambda(int*)>}]'|
C:\Program Files (x86)\CodeBlocks\MinGW\lib\gcc\mingw32\5.1.0\include\c++\tuple|602|required from 'constexpr std::tuple<_T1, _T2>::tuple() [with _T1 = int*; _T2 = <lambda(int*)>]'|
C:\Program Files (x86)\CodeBlocks\MinGW\lib\gcc\mingw32\5.1.0\include\c++\bits\unique_ptr.h|158|required from 'constexpr std::unique_ptr<_Tp, _Dp>::unique_ptr() [with _Tp = int; _Dp = <lambda(int*)>]'|
F:\3d\C++CodeProject\Hello\main.cpp|10|required from here|
C:\Program Files (x86)\CodeBlocks\MinGW\lib\gcc\mingw32\5.1.0\include\c++\tuple|59|error: use of deleted function '<lambda(int*)>::<lambda>()'|
F:\3d\C++CodeProject\Hello\main.cpp|6|note: a lambda closure type has a deleted default constructor|
C:\Program Files (x86)\CodeBlocks\MinGW\lib\gcc\mingw32\5.1.0\include\c++\bits\unique_ptr.h||In instantiation of 'std::unique_ptr<_Tp, _Dp>& std::unique_ptr<_Tp, _Dp>::operator=(std::unique_ptr<_Tp, _Dp>&&) [with _Tp = int; _Dp = <lambda(int*)>]':|
F:\3d\C++CodeProject\Hello\main.cpp|11|required from here|
C:\Program Files (x86)\CodeBlocks\MinGW\lib\gcc\mingw32\5.1.0\include\c++\bits\unique_ptr.h|252|error: use of deleted function '<lambda(int*)>&<lambda(int*)>::operator=(const<lambda(int*)>&)'|
F:\3d\C++CodeProject\Hello\main.cpp|6|note: a lambda closure type has a deleted copy assignment operator|
||=== Build failed: 2 error(s), 8 warning(s) (0 minute(s), 1 second(s)) ===|

Boost Asio share same io_service along disposible objects

I'm developing a program, which consists of bunch of Active Objects, that sending messages to each other. I'm using one same io_service to initialize all these objects. So they're working to end of the software life.

I'm using the Active Objects to ,let's say, one for file operation, another for serial IO, another for local database connection and one to communicate all of these.

However I couldn't be sure about the objects with short lives. I'm using the short lived objects to open tcp socket to send a quick message to a remote endpoint then dispose the socket immediately. I'm thinking to make these also asynchronous.

The question is, should I use the same io_service for these short lived objects or should I create a new io_service for each socket ?

cannot resolve overloaded function based on conversion to type

I'm pretty new to C++ template programming. I'd like to design a function element such as e.g.

  1. element<3, 3, 3, 3, 3> will return 3
  2. element<3, 3, 2> will fail an assertion

    #include <iostream>
    #include <cstdlib>
    
    namespace meta
    {       
      template<typename T>
      constexpr T element(T x)
      {
        return x;
      }
    
      template<typename T, typename... Ts>
      constexpr T element(T x, Ts... xs)
      {
        constexpr T oth = element(xs...);
        static_assert(oth == x, "element Mismatch");
        return x;
      }
    
      template<int... DIMS>
      void get_elements()
      {
        std::cout << "elements " << element(DIMS...);
      }
    }
    
    int main(int argc, char ** argv)
    {
      static constexpr int D1 = 3, D2 = 3;
    
      meta::foo<D1, D2>();
    }
    
    

But GCC with std=c++14 is failing with

cannot resolve overloaded function ‘element’ based on conversion to type ‘int’ E = meta::element<D1, D2>; ^

I'd like to exploit recursion to perform an equality check on each template argument in the list, and return one of them if they're all equal.

Using enable_if to match numbers

I want to use std::enable_if to make constructor that matches numbers. I tried the following code, but the constructor is not found. Main function has examples how I want to use this. What should I change to make this work?

#include <type_traits>
#include <string>

class A {
public:
    A(const std::wstring&, const std::wstring&)
    {}

    template<typename T>
    A(const std::wstring& n, typename std::enable_if<std::is_arithmetic<T>::value, T>::type v)
    {}
};

int main() {
    A(L"n", 1234); // does not compile
    A(L"n", 2.7); // does not compile
    A(L"n", L"n"); // compiles
    return 0;
}

Error on Ideone: template argument deduction/substitution failed

How to include the max value of uniform_real_distribution

I am a beginner in C++ and I am trying to explore C++11 features. Here I am trying to get familiar with the new randomness generating engines.

I summarized the following code from a tutorial on this subject and I noticed two things:

1- The uniform_real_distribution doe not include the max value.
2- The commented line produce an error although it seems to work fine on the tutorial.

#include <iostream>
#include <chrono>

using namespace std;

int main(){
    unsigned seed = 201;
    //seed = chrono::steady_clock()::now().time_since_epoch().count();
    default_random_engine e(seed);
    uniform_real_distribution<double> u(0,9);
    vector<double> v(10);
    int num;
    for(int i = 0; i < 400; ++i){
        num = u(e);
        ++v[num];
    }
    for (int i = 0; i < 10; ++i)
        cout << i << ":  " << string(v[i],'*') << "\n";
}

I tried to find the reasons of these two things with no luck.

So, my questions:

1- How to include the max value?
2- Why I am getting the error when uncomment the chrono line ?

cannot convert 'std::chrono::_V2::steady_clock' to 'unsigned int' in initialization

Note: I am using MinGW64 g++ with c++14.

keypad functionality implementation using egl calls

Hi i am trying to handle key press events using egl calls and xrandr libraries. i need only few key board events to work like s, h, q and escape. Presently my code works for s,h,q and escape. But it also works for print screen key and alt key. when i press print screen key, a screen shot is being captured which i don't need. i tried searching the key codes for print screen and alt key and disabling it in my code. But when i run the code, nothing has changed and screen shot is getting captured.

dimanche 29 avril 2018

systemd reboot threshold limit

I'm working for a commercial product that runs a camera service. This service is critical for the normal functionality of the system. So far, it is going good and I'm able to restart the service if it fails due to low-level protocol/driver issues. Here is a snippet from .service unit file that deals with the service restart and reboot logic.

...
[service]
Restart=on-failure
StartLimitInterval=2min
StartLimitBurst=5
StartLimitAction=reboot-force
...

Under certain conditions (for example: bus rail faults), it is quite possible that any number of reboots wouldn't help recover the system. In this situation, we want to stop rebooting the device (as it could be annoying to the user) and stop all attempts to recover the camera pipelines. This can be achieved using a monitoring service that just keeps track of the number of reboots the device went through, before stopping further reboots.

The other option, I thought is to depend on systemd, instead of adding another monitoring service for this purpose alone (which in turn would be monitored by systemd). I have spent some time to look for systemd options, reading through the documentations/examples to see if such reboot-thresholds exist. I'm looking for a way to restrict the number of reboots to some configurable StartLimitReboot

tl;dr

I want to achieve something like this

...
[service]
... 
...
... 
StartLimitReboot=3 # stop rebooting after this limit
...

Looks like systemd doesn't support such a semantics as of now, but if it supports, that would simplify my task substantially.

Seeking clarification on inline namespace

In cppreference, the following text is found:

Each member of an inline namespace can be partially specialized , explicitly instantiated or explicitly specialized as if it were a member of the enclosing namespace.

Note: the rule about specializations allows library versioning: different implementations of a library template may be defined in different inline namespaces, while still allowing the user to extend the parent namespace with an explicit specialization of the primary template.

What do these statements imply? Can someone explain by means of a simple example?

return value type does not match the function type C++

I am having a problem with the error "return value type does not match the function type" for both functions test and test2 below.

I am aware I am trying to pass in my "current" pointer to something's value and this function takes a float argument.

However, for the function getTest I tried creating a float variable chkTest to compensate for that...

I am still receiving the same error.

if (type == '1') 
    { 
        float chkTest = current->test;
        return getTest(chkTest);
    }
    if (type == '2') { return getTest2(current->test2); }

My declarations for these functions in the header is:

auto getTest(float t);
auto getTest2(float t);

and my function definitions are below:

  auto TransactionType::getTest(float t)
{
    //Do Something...
};
auto TransactionType::getTest2(float t2)
{
    //Do Something...
};

If I comment out my function definitions, then this error goes away, so obviously my problems are in the function definitions (correct me if I am wrong)

Please suggest on a solution and an explanation!

Thanks.

std::async doesn't work with MinGW32_w64

I've been trying to use std::async(std::launch:async, &MyClass::function, this, args) to launch a new thread that does some tasks. My old implementation is using std::thread and it works, and after I switch everything to std::async, the code compiles(so no syntax error), but the program freezes every time when it executes the code that invokes std::async. After hours of readings, I don't think this piece of code is wrong. I suspect that std::async just doesn't work with MinGW32_64 on Windows. p.s. I'm using MinGW32_w64 7.2.0, thread model is posix, and gcc version is 7.2.0

How to solve this error in unordered_set hasher function of custom class objects?

I am using unordered map for the first time and that with custom objects. I tried to write the below functions. There are errors that I need help with.

This is the class.

class Node
{
  public:
    int g= 0, h=0;
    char val;                                                              //Char value in the grid
    pair<int,int> pos,parent;  
    bool par_prsnt = false;                                                //Bool to check if the parent is set


    Node(pair<int,int>nodePos,char value)
    {
    pos=nodePos;
    val=value;
    }  

    int move_cost(Node other)
    {
    if (val=='.')
        return 0;
    else
        return 1;
    }

    pair<int,int> get_pos() const
    {
    return pos;
    }

    void set_parent(pair<int,int> par)
    {
    parent = par;
    par_prsnt = true;
    }

};

Below is the custom functions:

// Custom Hasher for Class Node, to be used for Unordered_set
struct NodeHasher
{
  template <typename T, typename U>
  size_t
  const operator()(const Node &obj)
  {
    pair<T,U> position;
    position = obj.get_pos();
    return 3* std::hash<T>()(position.first) + std::hash<U>()(position.second) ;
  }
};

// Custom Comparator for Class Node, to be used for Unordered_set
struct NodeComparator
{
  bool
  const operator()(const Node  &obj1, const  Node  &obj2) const
  {
    if (obj1.get_pos() == obj2.get_pos())
      return true;
    return false;
  }
};

I get the following errors:

Player 1: compilation error
In file included from /usr/include/c++/7/bits/hashtable.h:35:0,
from /usr/include/c++/7/unordered_map:47,
from /usr/include/x86_64-linux-gnu/c++/7/bits/stdc++.h:117,
solution.cc:7:
/usr/include/c++/7/bits/hashtable_policy.h: In instantiation of ‘struct std::__detail::__is_noexcept_hash’:
/usr/include/c++/7/type_traits:143:12: required from ‘struct std::__and_,  std::__detail::__is_noexcept_hash >’
/usr/include/c++/7/type_traits:154:31: required from ‘struct std::__not_, std::__detail::__is_noexcept_hash > >’
/usr/include/c++/7/bits/unordered_set.h:98:63: required from ‘class std::unordered_set’
solution.cc:119:51: required from here
/usr/include/c++/7/bits/hashtable_policy.h:87:34: error: no match for call to ‘(const NodeHasher) (const Node&)’
noexcept(declval()(declval()))>
~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~
solution.cc:83:9: note: candidate: template const size_t NodeHasher::operator()(const Node&)
const operator()(const Node &obj)
^~~~~~~~
solution.cc:83:9: note: template argument deduction/substitution failed:
In file included from /usr/include/c++/7/bits/hashtable.h:35:0,
from /usr/include/c++/7/unordered_map:47,
from /usr/include/x86_64-linux-gnu/c++/7/bits/stdc++.h:117,
solution.cc:7:
/usr/include/c++/7/bits/hashtable_policy.h:87:34: note: couldn't deduce template parameter ‘T’
noexcept(declval()(declval()))>
~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/7/bits/move.h:54:0,
from /usr/include/c++/7/bits/stl_pair.h:59,
from /usr/include/c++/7/bits/stl_algobase.h:64,
from /usr/include/c++/7/vector:60,
solution.cc:3:
/usr/include/c++/7/type_traits: In instantiation of ‘struct std::__not_, std::__detail::__is_noexcept_hash > >’:
/usr/include/c++/7/bits/unordered_set.h:98:63: required from ‘class std::unordered_set’
solution.cc:119:51: required from here
/usr/include/c++/7/type_traits:154:31: error: ‘value’ is not a member of ‘std::__and_, std::__detail::__is_noexcept_hash >’
: public __bool_constant
^~~~~~~~~~~~~~~~
In file included from /usr/include/c++/7/unordered_set:48:0,
from /usr/include/x86_64-linux-gnu/c++/7/bits/stdc++.h:118,
solution.cc:7:
/usr/include/c++/7/bits/unordered_set.h: In instantiation of ‘class std::unordered_set’:
solution.cc:119:51: required from here
/usr/include/c++/7/bits/unordered_set.h:98:63: error: ‘value’ is not a member of ‘std::__not_, std::__detail::__is_noexcept_hash > >’
typedef __uset_hashtable _Hashtable;
^~~~~~~~~~
/usr/include/c++/7/bits/unordered_set.h:105:45: error: ‘value’ is not a member of ‘std::__not_, std::__detail::__is_noexcept_hash > >’
typedef typename _Hashtable::key_type key_type;
^~~~~~~~ 

The error list is much longer, I think this much maybe enough for someone to understand the error. I referred this page for the custom functions : http://thispointer.com/how-to-use-unordered_set-with-user-defined-classes-tutorial-example/. Any suggestions? Thanks for reading.

why functional C++ have its form?

I'm reading the STL llmv and gcc, to learn how STL is implemented and then learn to code better. But also I'm trying to create my version that is more readable and if possible faster.

for example partition with Foward Iterator:

template<class FIter, class Predicate>
  FIter
  partition(FIter first, FIter last, Predicate pred)
  {
    // find the first element that don't pass the test
    first = newton::find_if(first, last, newton::not1(pred));
    // same that
    // first = std::find_if_not(first, last, pred);
    if (first == last)
      return first;

    // and then find the first next element that pass the test
    // if the element exist swap the first and next
    FIter next = newton::find(first + 1, last, pred);
    while (next != last) {
      std::iter_swap(first, next);
      ++first;
      ++next;
      next = newton::find(next, last, pred);
    }

    return first;
  }

That is more readable than GCC

  /// This is a helper function...
  template<typename _ForwardIterator, typename _Predicate>
  _ForwardIterator
  __partition(_ForwardIterator __first, _ForwardIterator __last,
              _Predicate __pred, forward_iterator_tag)
  {
    if (__first == __last)
      return __first;

    while (__pred(*__first))
      if (++__first == __last)
        return __first;

    _ForwardIterator __next = __first;

    while (++__next != __last)
      if (__pred(*__next))
        {
          std::iter_swap(__first, __next);
          ++__first;
        }

    return __first;
  }

I think my version it's better because it's easier to understand and review.

CppCon 2016: Marshall Clow “STL Algorithms - why you should use them, and how to write your own"

So..........

When I write the code I start to see how functions in works

And there is something CRAZY!, but not just crazy, CRAZY! CRAZY!.

GCC

template<typename _Tp>
struct less : public binary_function<_Tp, _Tp, bool>
{
   bool operator()(const _Tp& __x, const _Tp& __y) const
   { return __x < __y; }
};

LLVM

template <class T> // <class T=void> in C++14
struct less : binary_function<T, T, bool>
{
    bool operator()(const T& x, const T& y) const;
};

I Just... don't understand. Who is crazy here, is it me?

Who writes template <class T> // <class T=void>?

My version is this:

struct less
  {
    // return true if left is less than right, false otherwise.
    template <class T, class U = T>
    constexpr bool operator()(const T& left, const U& right) const;
  } less;

I think it's better.

  1. because <class T, class U = T> can compare uint16_t and int16_t
  2. don't need a template when declare the struct, just when using operator std::less<uint16_t> comp vs newton::less comp
  3. end with } less;

And you can use it without declare it.

for example, I have another function that is not in STL. divisible

struct divisible
  {
    // return true if left is divisible by right, false otherwise.
    template <class T, class U = T>
    constexpr bool operator()(const T& left, const U& right) const;
  } divisible;

So you could:

if ( newton::divisible(element, 2) )
   party.on();

mean while using the form of STL you should:

std::divisible foo(); //(屮゚Д゚)屮
if ( foo(element, 2) )
   party.on();

So why STL have that form?

Should be because the binary_function<T, T, bool> but, right now I think it's unnecessary.

Is there ever a difference between compare_exchange_strong and compare_exchange_weak on x86_64?

I am aware of the semantic difference between compare_exchange_strong and compare_exchange_weak; this question concerns the specific implementation on x86_64.

I compiled both of the following two programs on my x86_64 machine with gcc 5.4.

include <atomic>

std::atomic<int> foo;
int main(){
    int expected = 0;
    int desired = 1;
    foo.compare_exchange_strong(expected, desired);
}


#include <atomic>

std::atomic<int> foo;
int main(){
    int expected = 0;
    int desired = 1;
    foo.compare_exchange_weak(expected, desired);
}

When I disassembled the two programs using objdump -d, the output is identical.

Is this generally / reliably true on x86_64, or will I see differences across compiler versions or memory orders?

unordered_multiset pointer in C++

Iam beginner in C++, and I want to use insert function of unordered multiset pointer below to add new element:

struct Customer {
 size_t operator()(const char& c) const;
};

unordered_multiset<char, Customer>* ms

can any one help?

Error in compiling specific Dlib program c++

I am trying to make a program for face recognition using dlib & opencv

Program for face detection is working correctly but when I copied the code in another program which is supposed to work on frame of camera instead of images I'm getting a error - see image for errordlibfacedetectError

code for program working correctly- [facedetectcorrectprogram][2] code for program with errors- https://pastebin.com/7EktwVfM

another problem -I have to compile program inside dlib's libray example folder for correct compilation else I get error see screenshot facedetectErrorOtherLocation
when I compile inside example folder program works correctlyenter image description here is this related to the cause of error?

set running process on bottom

I'm new to C++ just started to learn and I'm trying to change the appearance of a running process for example "Calculator" to be always on bottom/on desktop but with no successes.

Here is the code I have so far:

#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <string>
#include <iostream>
using namespace std;

void set_to_bg() {
    LPCSTR app_name = "Calculator";
    HWND hWnd = FindWindowA(0, (app_name));
    HWND ProgmanHwnd = FindWindow(_T("Progman"), _T("Program Manager"));
    SetParent(hWnd, ProgmanHwnd);
    SetWindowPos(hWnd, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
}

int main()
{
    set_to_bg();
}

What Happens is that the "Calculator" window disappears. I'm using Spy++ to monitor windows and I'v noticed that the "Calculator" is parented to "Program Manager" but it doesn't shows it. if I omit the "SetParent(hWnd, ProgmanHwnd);" the "Calculator" is shown and sets to bottom. When I open a folder or some other app they overlap the "Calculator" which is a good result but if I click the "Calculator" then it losses its "OnBottom" property and overlaps all the other folders or apps that opened.

Any ideas, code snippets, guidance would be very appreciated!

Converting ascii to char

I have the following snippet

std::string encodedstr;
if(std::isdigit(encodedstr.at(i))) {
             num_of_times = encodedstr.at(i);
             std::cout << num_of_times << "\n";
         }

The output is :

52
51 

I tried to cast it to a char but the output didn't change

num_of_times = static_cast<char>(encodedstr.at(i));

I am on windows with mingw64 compiler

How to stop C++ from automatically converting double to int?

How do I stop C++ from automatically converting double to int values? I get that this is by design, but I don't want it to.

My code in question is as follows:

double validateInput()
{
    int n = {};
    cin >> n;

    while (cin.fail() || (n < 1) || (n > 999))
    {
        cin.clear();
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        n = {};

        cout << "Please enter a valid number:" << endl;
        cin >> n;

    }

    cout << "n = " << n << endl; 
    return (double)n;
}

The function is supposed to to take an integer value and return an error if anything but an integer value is entered. However, since C++ converts double to int by design, converted double values still get through.

How to declare an std::array of structs initialised inline with different values

I am trying to a initialise an array of structs in a std::array. I know that the following is a way of initialising an std::array with integers.

std::array<int, 5> arr { {1, 2, 3, 4, 5} };

Scenario:
But, say I have an array of structs like this

struct MyStruct {
    const char     *char_val_1;
    const char     *char_val_2;
    int             int_val_1;
    double          d_val_1;
} my_struct_obj[] = {
    { "a1b1"    , "a2b1"    , 1  ,   1.1 },
    { "a1b2"    , "a3b1"    , 2  ,   1.2 },
    { "a1b3"    , "a4b1"    , 3  ,   1.3 },
    { "a1b4"    , "a5b1"    , 4  ,   1.4 },
    { "a1b5"    , "a6b1"    , 5  ,   1.5 },
    { "a1b6"    , "a7b1"    , 6  ,   1.6 },
    { "a1b7"    , "a8b1"    , 7  ,   1.7 },
    { "a1b8"    , "a9b1"    , 8  ,   1.8 },
    { "a1b9"    , "a10b1"   , 9  ,   1.9 },
};

Question:
How can I create an std::array of MyStructs each initialised with different set of values?

C++: The iterator of struct in the class pointed by the iterator of class pointer

In this code, 'vector iterator of class pointer' and 'vector iterator of struct' loops for total twice.

but with for (vector<VkQueueFamilyProperties>::iterator iter2..., the following exceptions caused:

vector iterator not dereferencable

Am I did the wrong way to access the iterator?

I want to know why the second iterator cannot be initialized.

class RVulkanDevice;
struct VkQueueFamilyProperties;

bool foundGraphic = false;
bool foundCompute = false;

// First Iterator (with vector of class pointer)
for (vector<RVulkanDevice*>::iterator iter
    = RVulkanDeviceClass.begin(); iter != RVulkanDeviceClass.end(); ++iter)
{
    (*iter)->GetPhysicalDeviceQueueFamilyProperties();

    // Second Iterator (with vector of first iterator's struct)
    // Before Breakpoint
    for (vector<VkQueueFamilyProperties>::iterator iter2
        = (*iter)->queueFamilyProps.begin(); iter2 != (*iter)->queueFamilyProps.end(); ++iter2)
    {
        // After Breakpoint
        if (iter2->queueFlags & VK_QUEUE_GRAPHICS_BIT) {
            foundGraphic = true;
        }
        if (iter2->queueFlags & VK_QUEUE_COMPUTE_BIT) {
            foundCompute = true;
        }
    }
}

Debugged with VS2017

Inheritance of a Pure Virtual Function

Could somebody please clear these concepts and answer these questions. Thank you in advance.

Class A is a base class and has a pure virtual function named display.

Class A 
{ 
  public:
       virtual void display()const=0;

};

Class B is a derived class that inherits the A class. Furthermore, B overrides the display function,

Class B:public A 
{ 
  public:
       void display()const{cout<<"Always"<<endl;}

};

Q1: Now B contains 1 overridden display and 1 inherited pure virtual display, right? Or does the pure virtual one become non-existent due to the override.

I'm asking this because the ultimate question I'm facing is this: Q2: Suppose B did override the display function, Now, if there a new class

Class C:public B 
{ 
  public:
};

Now, I'm clear on the concept that the all the first level derived classes (like B) have a must on them that they override the pure virtual function(coming from the class A), suppose that they do override it, now what if the there is a new class C that is derived from one of the first-level-derived classes ( class B ), will it also need to override the pure virtual function (display) or will it be not required as it was overridden in the class B and C inherits B(consequently receiving an override of the the display function?

samedi 28 avril 2018

Relabel-To-Front Algorithm Implementation Flow is correct Cut is not

I am trying to do an implementation of Relabel-To-Front Algorithm for my project, and whats happening right now is that the algorithm goes OK, but even though it gets the maximum flow correct, it doesn't get the right cut. So what i'm thinking is it is not getting to the right Heights on the vertices, but if that does happen how does that make sense, because I know that the vertices have no excess flow, so the flow is getting to the source, but for the flow to get to the source the height of the vertices would have to be higher then the source and that would give me the right cut. In what part of the algorithm could the problem be.

How to call a template function in a non-template class [duplicate]

This question already has an answer here:

  • I am trying to a make a generic function that displays vector elements of any data type by using templates.
  • I was successful in making a function template that displays the vector elements for any data type vector
  • But when I put the same function template inside a non-template class and try to call it then I get an error
  • What is the right way to call a template function inside a non-template class

main.cpp

#include <iostream>
#include <Eigen>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include "tools.h"
using namespace std;

template <typename T>
void disp_vect(const vector<T> & vect)
{
  typename vector<T>::const_iterator it;
  for (it = vect.begin() ; it != vect.end(); ++it)
  {
    std::cout << ' ' << *it;
  }
  std::cout << '\n';
}


int main()
{
  Tools tools;
  vector<int> vect{ 10, 20, 30 };
  disp_vect(vect);    // No Error Here

  // ===================Below is what i tried to call ======================
  // tools.disp_vect(vect);  // <==== If used this then Error
  // tools.disp_vect<int>(vect);  // <==== If used this then Error
  // tools.disp_vect(vect);  // <==== If used this then Error
  // tools.template disp_vect(vect);  // <==== If used this then Error
  // tools.template disp_vect<int>(vect);  // <==== If used this then Error
  // ===================Above is what i tried to call ======================

}

tools.h

#ifndef TOOLS_H_
#define TOOLS_H_
#include <vector>
#include "Eigen"

using Eigen::MatrixXd;
using Eigen::VectorXd;
using namespace std;

class Tools {
public:
  /**
  * Constructor.
  */
  Tools();

  /**
  * Destructor.
  */
  virtual ~Tools();

  template <typename T>
  void disp_vect(const vector<T> & vect);

};

#endif /* TOOLS_H_ */

tools.cpp

#include <iostream>
#include "tools.h"
#include <Eigen>

using Eigen::VectorXd;
using Eigen::MatrixXd;
using std::vector;

Tools::Tools() {}

Tools::~Tools() {}


template <typename T>
void Tools::disp_vect(const vector<T> & vect)
{
  typename vector<T>::const_iterator it;
  for (it = vect.begin() ; it != vect.end(); ++it)
  {
    std::cout << ' ' << *it;
  }
  std::cout << '\n';
}

- I also tried replacing the typename key-word with class and still i get error - This is the error message that i get:

    undefined reference to `void Tools::disp_vect<int>(std::vector<int, std::allocator<int> > const&)'
    collect2.exe: error: ld returned 1 exit status`

  • I referred these links but these links did not solve my error and hence posting this question over here:

1] Function template in non-template class

2] How to call a template member function?

3] Why calling template member functions gives error?

  • I also referred many other links which I have not mentioned

  • Based on the above links I tried the following solution:

     // tools.disp_vect(vect);  // <==== If used this then Error
     // tools.disp_vect<int>(vect);  // <==== If used this then Error
     // tools.disp_vect(vect);  // <==== If used this then Error
     // tools.template disp_vect(vect);  // <==== If used this then Error
     // tools.template disp_vect<int>(vect);  // <==== If used this then Error
    
    
  • I am new to C++ so before you down-vote my question please comment what should I add more to make the question more clear

  • If this is a duplicate then please mark it duplicate with right answer but do not down-vote it .. I searched for solution and also tried so please do not down-vote... Thank-you

Does a thread start immediately

I just started reading C++ Concurrency In Action 2012.pdf. In Chap 2 it shows a thread being invoked and joined. with the join not being an atomic operation with thread creation. By this I mean that the thread is started with std:thread t(...) and in a succeeding line a join is performed. My assumption is that when a thread is created it can begin executing at any time, including at once. And if it begins executing at once and terminates before the creating program begins executing, then the join fails.

The same issue occurs when if t.joinable()) is used.

If my guess is correct then there is no guarantee that a join can ever be successful and the joinable() predicate does not help. What am I missing?

=delete for user defined member functions apart from constructor, assignment operator c++11

In C++11, we use "= delete" as not to allow the constructors and operator overloaded member functions to be invoked implicitly while doing some operations(change of dataype/assignment of objects).

class color{
 public:    
 color(){cout<<"color constructed called"<<endl;}
 color(int a){};
 color(float)=delete;
 color& operator = (color &a) = delete;
 virtual void paint() = delete;  //What is the use of delete in this function
 virtual void paints () final {};
};

I have used delete on user defined member function in the above example. It says that we can define the paint() function, hence no other function can call it.

Want to know if there is there is any scenarios in which this type of function declaration(paint) would be useful/recommended.

How do I create three Nodes from the user's input

I'm having with linked list assignment. This my computer class assignment. And This is my very first time learning list. It's quite difficult for me understand this. Can some please help me with this assignment?

here is what my professor said what I need to do:

In main, prompt the user for three contacts.

Create three ContactNodes from the user's input Use the nodes to build a linked list use the insertAfter function to link each node together

Here is main:

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

using namespace std;

int main()
{
    ContactNode* headNode = nullptr;
    ContactNode* node1 = nullptr;
    ContactNode* node2 = nullptr;
    ContactNode* node3 = nullptr;
    ContactNode* currObj = nullptr;

    string name1;
    string name2;
    string name3;
    string phoneNum1;
    string phoneNum2;
    string phoneNum3;

    cout << "Enter name: " << endl;
    getline(cin, name1);

    cout << "Enter phone number: " << endl;
    getline(cin, phoneNum1);



    currObj = headNode;
    while (currObj != NULL)
    {
        currObj->printContactNode();
        currObj = currObj->getNext();
    }

}

How to use GetMessage to read another Thread's message queue

I'm trying to run a trhead in the background which reads the message queue from the main thread, so I can focus on installing and uninstalling hooks and responding to user actions, but I can't make the second thread poll from the main thread's message queue. I searched for a solution but didn't find any answer which solves my problem. Does anyone here know what to do? thanks in advance!

this is the code I wrote: (the Macro_Record hook increase counter everytime it is called)

int counter = 0;
MSG stam;

void Init(DWORD main_id)

{
     DWORD cur_id = GetCurrentThreadId();
     int result = AttachThreadInput(main_id, cur_id, true);
     if (!result)
     {
         cout << "Threads not attached " << result << endl;
     }
     else
     {
         cout << "Threads attached " << result << endl;
     }
     while (GetMessage(&stam, NULL, 0, 0));
}


int main()
{
    DWORD id = GetCurrentThreadId();
    HANDLE hthread;
    hthread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) Init,(LPVOID)id, 0, NULL);
    if (hthread == NULL)
    {
        cout << "Thread failed" << endl;
    }
    else
    {
        cout << "Thread Success" << endl;
    }
    /*string ans;
    cout << "Enter path to file you want to open" << endl;
    getline(cin, ans);*/
    File_Run* calc= new File_Run("C:\python27\python.exe", "open");
    Macro calc_macro(calc, false, false);
    recording = &calc_macro;
    HHOOK record_handle =SetWindowsHookEx(WH_KEYBOARD_LL, Macro_Record, NULL, NULL);
    if (record_handle == NULL)
    {
        cout << "Install record failed" << endl;
        cout << GetLastError() << endl;
    }
    else
    {
        cout << "Record success, start typing" << endl;
        while (counter < 8);

undefined behaviour in std::string.substr

I want to get a substring from a string . I do this in new for_each loop with lambda and string.substr() .for the first time ,it runs correctly but after that it don't work correctly

here is my code:-

suppose eqn = "1231-78*78-433-67+89/32" and

std::for_each(eqn.begin(),eqn.end(),[&](char ch)
{
    if(isdigit(ch) || ch=='.')
        i++;
    else if(isOperator(ch))
    {
        std::string temp = eqn.substr(li,i);
        double tempN = std::stod(temp);
        NumOp.insert(std::pair <double ,char> (tempN,ch));
        li=i+1;i++;
    }
});

now here is what I see in my QtCreator's debug:-

enter image description here

it should give me "78*" substring from string "1231-78*78-433-67+89/32" but i am getting "78*78-4" which is causing so much destruction and I can't figure out.please help me cause I was like waking since all night

Erase some of a vector's elements in a for-each loop without iterating the whole vector

I have a vector and I am searching for an element in it while iterating over the vector with a for-each loop. If I find any invalid elements during the search, I would like to remove them from the vector.

Basically, I want to do something like this:

for (auto el : vec) {
    if (el == whatImLookingFor) {
        return el;
    } else if (isInvalid(el)) {
        vec.erase(el);
    }
}

I looked at some other questions like this and this, but both recommend using std::remove_if. That will iterate over the whole vector and remove all invalid elements, instead of iterating only until I find the element I'm looking for, and ignoring any elements after that.

What would be a good way to do this?

Getting current time in milliseconds in c++ [duplicate]

This question already has an answer here:

I am new to c++, using Microsoft visual studio 2017, and I want to know how to get the current time in hours, minutes, seconds and milliseconds, without colons. For instance, if the time is

18:25:45.3456776543

I want to set a variable to

182545.3456776543

with a function like

double currentTime = getCurrentTimeNoColons()

Is this possible?

Thanks 😃

Feasibility of a user-defined swap method

Thinking about this topic I got a thought (given that I'm talking about C++11) that a user-defined swap should be provided only for types which don't provide a move semantic, more precisely a move assignment operator ('cause I think it's more common to have a move ctr while lack a move assignment operator); or the move ctor and/or the move assignment operator have some side-effects which ain't desired to happen.

Let's see the examples: [ the same as in a linked topic ]

class remote_connection
{
public:
  int socket_fd;

  friend void swap( remote_connection& lhs, remote_connection& rhs ) = delete;
}

As we have NO provided a user-defined swap the code trying to swap objects of a remote_connection type calls a swap instantiated from std::swap which causes a move construction and two move assignments to happen (as @1201ProgramAlarm indicated).

So, to swap objects a compiler issues: one function call to a std::swap, one call to a move ctr and two calls to a move assign operator. Which leads to 3 int copies to make an actual swap.

As a result: 4 function calls and 3 copies.

Let's implement a swap method:

class remote_connection
{
public:
  int socket_fd;

  friend void swap( remote_connection& lhs, remote_connection& rhs )
  {
    using std::swap;

    swap( lhs.socket_fd, rhs.socket_fd );  
  } 
}

As we have provided a user-defined swap the code trying to swap objects of a remote_connection type calls this user-defined swap which causes 3 copies for int to happen (create a tmp from a rhs, copy a lhs to the rhs, copy the tmp to the lhs).

So, to swap objects a compiler issues: one function call to a swap (found by ADL), one call to a std::swap(int&, int&). Which also leads to 3 int copies to make an actual swap.

As a result: 2 function calls and 3 copies.

The user-defined swap won, but what if we add some members to our class:

class remote_connection
{
public:
  int socket_fd;
  int a, b, c, d, e;

  friend void swap( remote_connection& lhs, remote_connection& rhs )
  {
    using std::swap;

    swap( lhs.socket_fd, rhs.socket_fd );  
    swap( lhs.a, rhs.a );  
    swap( lhs.b, rhs.b );  
    swap( lhs.c, rhs.c );  
    swap( lhs.d, rhs.d );  
    swap( lhs.e, rhs.e );  
  } 
}

Here we have: 8 function calls and 6 copies. But if we didn't provide the user-defined swap, we'd have: 4 function calls and 6 copies.

So, it seems that whatever class we have (derived from a class with plenty members, consisting of plenty sub-objects of built-in and user-defined types) it's more sane, IMHO, to not provide a user-defined swap. Not only this, but also such the swap is hard to support (if we changed something in a class and forgot to reflect that changes in the swap we get a surprise.)

So the questions is: "If we have no side-effects in move ctr/move assign operator and provide them both, do we have to implement a user-defined swap, or is it a good practice to rely on stl provided one in such circumstances?"

Sorry for such ammount of so, I'm not a native speaker :)

P.S. I forgot to add that we need, IMHO, a user-defined swap if we're going to implement a copy-and-swap idiom and we've implemented a move assignment operator.

Disabling direct creation allowing creation only via NEW and smart pointer

This is an experiment to see if it can be done.

By making destructor private, I'm able to disable direct object creation (ex: Test t; ). I want to force instantiation via new (this works) or smart pointer like unique_ptr.

I believe that I'm doing something wrong with how I'm approaching unique_ptr but I'm not sure what.

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

class Test
{
private:
    ~Test() {cout << "x" << endl;}
public:
    Test() {cout << "c" << endl;}
    static void destruct(Test* ptr) {delete ptr;}
};

int main()
{
    //Perfect
    //We want to disable direct creation. This fails and we want it to fail.
    //Test t;  ERROR: Can't because dest is private!

    //OK   
    Test *ptr = new Test;       //Creation via new works fine
    ptr->destruct(ptr);         //Destruct works fine

    //NOT OK. :-(
    //auto up = make_unique<Test>();  //error
    //unique_ptr<Test> up( new Test(), [](Test* p){destruct(p);} );     //error

    return 0;
}

c++ function is publicly callable despite explicitly declared private

I am currently investigating why I am able to call a private function from a context where it should not be accessible from. I have already narrowed it down to a very simple example, but I am still unable to identify the issue.

LIVE example

This is my narrowed down version:

template<typename From, typename To>
concept bool ConvertibleNoNarrow = requires(From f, To t) {
    t = { f };
};

template<typename T>
class Wrapper {
    T t;
public:
    Wrapper(ConvertibleNoNarrow<T> u) : t(u) { }

private:
    // should be PRIVATE
    void operator()() { }
};

int main() {
    Wrapper<long> w(1);

    // should not be able to call this!
    w();
}

Turning numbers into text and sorting for Card Deck

So I've done the majority of this project (unwrapping cards in ascending order, shuffling them, and dealing them). However, I now have to take what I have, which has been approved, and turn the numbers into text descriptions of the cards( Ace, Hearts, ect) and sort them. I basically have to finish out my showHand function. I'm having trouble figuring out where to start with this. I was thinking of using a struct, but don't know if that would be the correct approach. We have not learned classes and public, so I would want to keep with the approach I've already taken. Here is what I have so far:

#include <iostream>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <string>

using namespace std;

using cards = unsigned short;

//Global constants
const int NUM_COLS=13;
const int NUM_ROWS=4;


//Create Function prototypes for card loading and shuffling deck of 
cards
void unwrap(vector<int> &);
void shuffle(vector<int> &);
void printCards(vector<int>);

//Function for dealing cards to players
void deal(vector<vector<int>>&, const vector<int>&);
void showHands(const vector<vector<int>>&);


int main() {

//Declare vector for the number of cards
vector <int> deck;



//Call function for showing cards in ascending order, and shuffling 
cards
cout << "The deck before shuffling: " << endl;
unwrap(deck);
printCards(deck);

cout << "The deck after shuffling: " << endl;
shuffle(deck);
printCards(deck);

//Declare 2d vector for dealing the cards to each player
vector<vector<int>> players(NUM_ROWS, vector<int>(NUM_COLS, 0));

cout << " Before cards have been dealt " << endl;
showHands(players);

cout << " After the cards have been dealt "<<endl;
deal(players, deck);
showHands(players);

return 0;
}

//Function definitions that load cards and randomly shuffles them
void unwrap(vector<int> &deck)
{
//Load vector with ints from 0 to 51
for (int i = 0; i <= 51; i++)
{
    deck.push_back(i);
}

}

// Randomize the cards in the deck
void shuffle(vector<int> &deck)
{
random_shuffle(deck.begin(), deck.end());

}
void printCards(vector<int> deck)
{
for(int j=0; j<deck.size(); j++)
{
    cout<< deck[j] << endl;
}
}
// deal one card to each player in order, repeat until the entire deck 
is dealt
void deal(vector<vector<int>>& players, const vector<int>& deck)
{
int card_count = 0;

for (int cols = 0; cols < NUM_COLS; cols++)
{
    for (int rows = 0; rows < NUM_ROWS; rows++)
    {
        players[rows][cols] = deck[card_count];
        card_count++;
    }
}
}
//Show hand after cards have been randomly dealt to each player
void showHands(const vector<vector<int>>& players)
{
for (int rows = 0; rows < NUM_ROWS; rows++)
{
    cout << "Player " << rows + 1 << ": ";
    for (int cols = 0; cols < NUM_COLS; cols++)
    {
        cout << players[rows][cols] << ' ';
    }
    cout << '\n';
}
}

Set GCC path in makefile

Whenever I am building my package it uses /usr/bin/g++ (System compiler). I want to build my package with c++11 constructs. I have tried -std=c++11 option but with system compiler it says unrecognized option. I want to build my package from a different gcc compiler which will get downloaded as part of my package dependency.

So, How can i specify the location of gcc compiler in Makefile.

vendredi 27 avril 2018

C++ decltype(auto) of const reference return type [duplicate]

This question already has an answer here:

This is the test program I have:

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

template <typename T>
decltype(auto) foo(T& arg)
{
    return arg;
}

int main()
{
    const int x = 10;
    int & y = const_cast<int&>(foo(x));
    y = 20;
    cout << "x: " << &x << " " << x << endl;
    cout << "y: " << &y << " " << y << endl;
}

Output:

g++ -std=c++17 main.cpp  && ./a.out
x: 0x7ffee31f4a6c 10
y: 0x7ffee31f4a6c 20

Why was the value of x not changed even though foo returned a const int& to which it was const_cast'ed to int&?

Because from the output it seems like the two addresses of x and y are the same.

Assembly Language Interpreter for a Simple Assembly Language [on hold]

I have to build Assembly Language Interpreter for a Simple Assembly Language in C++11. I have all SAL instructions and commands .

I couldn't find any sources with examples and explanations regarding this topic. Could you please recommend some sources?

Multiple, but unique, class inheritance

The problem is: ExampleIt which inherits (and overrides methods) from class It, so that when I overload operator in class Wrapped (which calls some methods from It, which should be overridden by ExampleIt.

The wanted effect is that when I overload operator* I should be able to call *name_of_Wrapped_class and this should execute virtual method Dereference (from It) which should be overridden by ExampleIt.

class It {
public:
    virtual std::pair<int, std::string> Dereference() const;
};

class ExampleIt : It {
public:
    std::pair<int, std::string> Dereference() const override;
};

class Wrapped : It{ //??? not sure about that
public:
     std::pair<int, std::string> operator*() const; // it should call for Dereference()
};

Generalization of class in generic function creates object code for base class?

class A {
protected:
    int fooA;
    A() : fooA(0) {}
};

class B {};

template<typename T>
class C : public A {
public:
    using A::A;

    void fooF(const T element) {
        element.fooA = 1;
    }
};

class D : public C<B>, public B {
    using C::C;
};

int main() {

    D d1;
    D d2;

    d1.fooF(d2);

    return 0;
}

error: ‘const class B’ has no member named ‘fooA’ element.fooA = 1;

It seems like when T is particulariced into B, it transforms d2 into its parent class (B), what can I do to avoid that? (I need to do it that way so i can't change the number of classes either its inheritances). Thanks.

expected type-specifier C++ template class

So I am trying to implement a Vector class.

I am getting the error "expected type-specifier before '[' token" in my 'at' function, as shown below:

T Vector<T>::at(unsigned i){
    return operator[i]; 
}

I have tried:

return this->operator[i];

and

(*this).operator[i];

but to no avail. Any ideas?

Running functions from a vector of futures

I'm instantiating a class that can hold futures so I can run these functions according to a scheduler later on. When I try to run my begin() method, my functions are not called.

    class ThreadManager {
public:
    std::vector<std::future<int>>* threadList;
    std::vector<std::promise<int>>* promiseList;

    ThreadManager() {
        threadList = new std::vector<std::future<int>>();
        promiseList = new std::vector<std::promise<int>>();
    }

    ~ThreadManager() {
        delete threadList;
        delete promiseList;
    }

    std::vector<std::future<int>>* getThreadList() {
        return ThreadManager::threadList;
    }

    void addFuture(std::future<int>* x) {
        getThreadList()->push_back(std::move(*x));
    }

    void begin() {
        std::vector<std::future<int>>* futureList = getThreadList();
        int i = 0;
        for (auto iterator = futureList->begin(); iterator != futureList->end(); iterator++) {
            std::cout << "There are " << i + 1 << " items in this list\n";
            std::cout << "Future at " << i << " is " << typeid(futureList->at(i)).name() << std::endl;
            futureList->at(i).get();
            i++;
        }
    }

};

My main instantiates a ThreadManager class and adds futures. Why aren't my functions running?

Big O of Switch statement having function calls in its Cases?

How can we calculate Big O of switch statement whom are having function calls in there cases. that Function can be the Function in whom the switch statement is present and can also direst to another function whom can send it back to the same Switch statement.

void ifpascorrectSwitch(int *currentbalance) {

cout << "\n\n";
cout << "Current balance = £" << *currentbalance << endl;
string casee;
cout << "Enter any of the below option\n"
        "1 for Deposit cash \n"
        "2 for Withdraw cash\n"
        "e for Quiting the application\n"
        "= ";


cin >> casee;
if (casee.length() == 1) {
    const char *k = casee.c_str(); // character inter to a c string

    switch (*k) {

        case '1':
            cout << "1 Deopist cash \n";
            Depositcash(currentbalance);          

//Deposit is another function call whom can can come back to this function // and have this switch menu again because of bellow given //ifpascorrectSwitch(currentbalance) which is function call of the current //function

            ifpascorrectSwitch(currentbalance);

            break;
        case '2':
            cout << "2 Withdraw menu\n";
            WithdrawCash(currentbalance);
            ifpascorrectSwitch(currentbalance);

            break;
        case 'e':
            cout << "r is working";
            break;
        default:
            cout << "Default switch wrong entery";
            ifpascorrectSwitch(currentbalance);
            break;
    }

} else {
    cout << "Wrong entery please try again";
    ifpascorrectSwitch(currentbalance);
}   }

All other function call other then ifpascorrectSwitch(currentbalance)which is current function call are having same scenario of switch stament. almost.

If only someone could help me atleast undesrtanding this Switch statement Big O calcultaion.

LEDA: Segfault on initialization of node_array

I am running into a segmentation fault whenever I initialize a leda::node_array. It even appears with the node_array example from here:

http://www.algorithmic-solutions.info/leda_guide/graphs/node_array_example.html

I tried different ways of compilation, but for a quick reproduction try:

g++ -I/path/to/LEDA/incl -l/path/to/LEDA/libleda.so -lX11 -lm main.cpp

I tried

  • with and without the std=c++11 flag
  • using a cmake file
  • compilation and linking in separate steps
  • leaving out the -lm and -lX11 libraries (the latter one throws an error)

Here is a smaller example that reproduces the error for me:

#include <LEDA/graph/graph.h>
#include <LEDA/graph/node_array.h>

int main()
{
  leda::graph G;
  G.new_node();
  leda::node_array<int> array_local(G);

  return 0;
}

I use LEDA version 6.5 installed to /opt/LEDA and g++ version 5.4.1 on Ubuntu 16.04. The error is caused by LEDA's memory allocator LEDA_MEMORY().

What might cause this behavior?

Mapping objects as key with unordered_map

I have a simple Observable class, implementing the observer pattern. This class maps a template type Event to registered observers. This is all fine, though instead of std::map I'd like to use std::unordered_map for performance reasons.

If I change the member variable below to use an unordered_map I get a rather generic error:

std::map<Event, std::vector<std::function<void()>>> _observers;

Static_assert failed "the specified hash does not meet the Hash requirements"

My expectation was that std::map and std::unordered_map should be interchangeable. What are the hashing requirements to use unordered_map in this case, and why is it different?

This is my code:

#include <functional>
#include <unordered_map>
#include <map>
#include <vector>
#include <utility>

template <typename Event>
class Observable
{
public:
    Observable()=default;

    template <typename Observer>
    void registerObserver(const Event &event, Observer &&observer)
    {
        _observers[event].push_back(std::forward<Observer>(observer));
    }

    template <typename Observer>
    void registerObserver(Event &&event, Observer &&observer)
    {
        _observers[std::move(event)].push_back(std::forward<Observer>(observer));
    }

    void notify(const Event &event) const
    {
        for (const auto& obs : _observers.at(event)) obs();
    }

    /* disallow copying */
    Observable(const Observable&)=delete;
    Observable& operator=(const Observable&)=delete;

private:
    std::map<Event, std::vector<std::function<void()>>> _observers;
};

VS2017: No suitable conversion from "vector

I am writing a program that will receive a text file, read in a list of names from that file, sort those names in alphabetical order, and then print the sorted list back out.

This originally was a project for my Intro to Programming class that was to use arrays, but I'm trying to retool it to work with vectors instead, allowing me to use a file of any length instead of a rigid array length.

But Intellisense is giving me the error "No suitable conversion function from "std::vector>" to "std::vector>*" exists" above any time that I try to pass the filename to a function (lines 27, 30, and 33). I'm having a hard time Googling how to pass a vector to a function, so I think that's where my problem is. The full code is pasted below:

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

int readFromFile(string[], string);
void displayArray(vector<string>[], int);
void alphaSort(vector<string>[], int);
void swap(string&, string&);


int main() {
//Declare variables
string fileName;
vector<string>names(1);
int nameQty;

//Prompt for file name
cout << "Please enter the name of the file to read names from: " << endl;
cin >> fileName;

//Call function to open file and read names into a vector array. Function will return the number of names in file
nameQty = readFromFile(names, fileName);

//Display unsorted names
cout << "Unsorted names:" << endl;
displayArray(names, nameQty);

//Sort names into alphabetical order
alphaSort(names, nameQty);

//Display sorted names
cout << "Sorted names:" << endl;
displayArray(names, nameQty);

//More to come after this; program isn't done yet!
}

/*
* Function to read a list from a text file into an array.
* The array starts at size 1, then increments by 1 for each subsequent iteration
* The array then deletes the final element when there is nothing more to read
* (since the last element will be uninitialized)
*/
int readFromFile(vector<string> array, string fileName) {

ifstream inputFile;
inputFile.open(fileName);

if (!inputFile) {
    cout << "Invalid file name. Please restart program and try again."
        << endl;
    system("pause");
    exit(EXIT_FAILURE);
}

else {
    int index = 0;
    while (inputFile) {
        cin >> array[index];
        array.push_back;
        index++;
    }
    array.pop_back;
    inputFile.close();
    return (index + 1);
}
}

//Function to display list of items in array
void displayArray(vector<string> array[], int quantity) {
    for (int i = 0; i < quantity; i++)
        cout << array[i] << endl;
}

//Selection sort function puts array elements in alphabetical order
void alphaSort(vector<string> names[], int qty) {
    for (int j = 0; j < qty - 1; j++) {

        for (int i = j + 1; i < qty; i++) {
            if (names[j] > names[i]) {
                swap(names[j], names[i]);
            }
    }
}

}

//Function to swap elements a and b in array
void swap(string &a, string &b) {
    string temp = a;
    a = b;
    b = temp;
}

Please don't worry about my using system("pause") and using namespace std. I'm aware that's poor practice, but it's what we've been asked to do in class. Thanks!

How to resolve "multiple definitions of _start" compiler error in c++ . I have gone through many answers but nothing helps

How to resolve "multiple definitions of _start" compiler error in c++ . I have gone through many answers but nothing helps .

error I got :

(.text+0x0): multiple definition of _start' makefile:45: recipe for target 'SDK' failed /usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o:(.text+0x0): first defined here ./src/SDK.o: In function_fini': (.fini+0x0): multiple definition of _fini' /usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crti.o:(.fini+0x0): first defined here ./src/SDK.o:(.rodata+0x0): multiple definition of_IO_stdin_used' /usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o:(.rodata.cst4+0x0): first defined here

My c++ code :

int main() {
    cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
    return 0;
}

at first this code works , but when I linked a library and changed to c++ 11 standard ,the above mentioned error came .kindly help me

Adding overload operator == with enable_if

I have a working template class point with an overload for operator==.

Because of floating point comparison, I was trying to add a second overload with enable_if for floating point to use an almost equal function.

This is my attempt:

template<typename T>
class Point2D
{
public:
   Point2D(T x, T y);

   Point2D& operator= (const Point2D& point);
   bool     operator==(const Point2D& point) const;
   bool     operator!=(const Point2D& point) const;
}

template<typename T>
Point2D<T>::Point2D(T x, T y) : x_(x), y_(y)
{
}

template<typename T>
Point2D<T>& Point2D<T>::operator=(const Point2D& point)
{
   if(this != &point)
   {
      x_ = point.x_;
      y_ = point.y_;
   }

   return *this;
}

template<typename T>
bool Point2D<T>::operator==(const Point2D& point) const
{
   return (x_ == point.x_) && (y_ == point.y_);
}

template<typename T>
typename std::enable_if<std::is_floating_point<T>::value, bool>::type
Point2D<T>::operator==(const Point2D& point) const
{
   return Traits::almost_equal(x_, point.x_) &&
          Traits::almost_equal(y_, point.y_);
}

Note:

  • This is a semplified example.

  • The code actually work without the enable_if overload

  • I have to separate declaration and implementation (both in .h), so please refer to the code as is.

The error the compiler gives me is

error: prototype for 'typename std::enable_if::value, bool>::type Point2D::operator==(const Point2D&) const' does not match any in class Point2D' Point2D::operator==(const Point2D& point) const ^

error: candidate is: bool Point2D::operator==(const Point2D&) const bool Point2D::operator==(const Point2D& point) const ^

I don't understand what the error is referred to.

Workaround GCC 5.5 unordered_map bug

This code works in GCC 6.1, but causes a compile error in GCC 5.5:

#include <memory>
#include <unordered_map>
#include <vector>

std::unordered_map<int, std::shared_ptr<std::vector<uint8_t>>> foo;

int main() {
    foo.emplace(0, new std::vector<uint8_t>(1));
}

The error is below. Is there any way around this (I assume) bug?

In file included from /opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/x86_64-linux-gnu/bits/c++allocator.h:33:0,

                 from /opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/allocator.h:46,

                 from /opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/memory:63,

                 from <source>:1:

/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/ext/new_allocator.h: In instantiation of 'void
__gnu_cxx::new_allocator<_Tp>::construct(_Up*, _Args&& ...) [with _Up = std::pair<const int, std::shared_ptr<std::vector<unsigned char> > >; _Args = {int, std::vector<unsigned char, std::allocator<unsigned char> >*}; _Tp = std::pair<const int, std::shared_ptr<std::vector<unsigned char> > >]':

/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/alloc_traits.h:530:4: required from 'static void std::allocator_traits<std::allocator<_Tp1>
>::construct(std::allocator_traits<std::allocator<_Tp1> >::allocator_type&, _Up*, _Args&& ...) [with _Up = std::pair<const int, std::shared_ptr<std::vector<unsigned char> > >; _Args = {int, std::vector<unsigned char, std::allocator<unsigned char> >*}; _Tp = std::pair<const int, std::shared_ptr<std::vector<unsigned char> > >; std::allocator_traits<std::allocator<_Tp1> >::allocator_type = std::allocator<std::pair<const int, std::shared_ptr<std::vector<unsigned char> > > >]'

/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/hashtable_policy.h:1955:37:   required from 'std::__detail::_Hashtable_alloc<_NodeAlloc>::__node_type* std::__detail::_Hashtable_alloc<_NodeAlloc>::_M_allocate_node(_Args&& ...) [with _Args = {int, std::vector<unsigned char, std::allocator<unsigned char> >*}; _NodeAlloc = std::allocator<std::__detail::_Hash_node<std::pair<const int, std::shared_ptr<std::vector<unsigned char> > >, false> >; std::__detail::_Hashtable_alloc<_NodeAlloc>::__node_type = std::__detail::_Hash_node<std::pair<const int, std::shared_ptr<std::vector<unsigned char> > >, false>]'

/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/hashtable.h:1517:77: required from 'std::pair<typename std::__detail::_Hashtable_base<_Key,
_Value, _ExtractKey, _Equal, _H1, _H2, _Hash, _Traits>::iterator, bool> std::_Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1,
_H2, _Hash, _RehashPolicy, _Traits>::_M_emplace(std::true_type, _Args&& ...) [with _Args = {int, std::vector<unsigned char, std::allocator<unsigned char> >*}; _Key = int; _Value = std::pair<const int, std::shared_ptr<std::vector<unsigned char> > >;
_Alloc = std::allocator<std::pair<const int, std::shared_ptr<std::vector<unsigned char> > > >; _ExtractKey = std::__detail::_Select1st; _Equal = std::equal_to<int>; _H1 = std::hash<int>; _H2 = std::__detail::_Mod_range_hashing; _Hash = std::__detail::_Default_ranged_hash; _RehashPolicy = std::__detail::_Prime_rehash_policy; _Traits = std::__detail::_Hashtable_traits<false, false, true>; typename std::__detail::_Hashtable_base<_Key, _Value, _ExtractKey, _Equal, _H1,
_H2, _Hash, _Traits>::iterator = std::__detail::_Node_iterator<std::pair<const int, std::shared_ptr<std::vector<unsigned char> > >, false, false>; std::true_type = std::integral_constant<bool, true>]'

/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/hashtable.h:726:21: required from 'std::_Hashtable<_Key, _Value, _Alloc, _ExtractKey,
_Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>::__ireturn_type std::_Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2,
_Hash, _RehashPolicy, _Traits>::emplace(_Args&& ...) [with _Args = {int, std::vector<unsigned char, std::allocator<unsigned char> >*};
_Key = int; _Value = std::pair<const int, std::shared_ptr<std::vector<unsigned char> > >; _Alloc = std::allocator<std::pair<const int, std::shared_ptr<std::vector<unsigned char> > > >; _ExtractKey = std::__detail::_Select1st; _Equal = std::equal_to<int>; _H1 = std::hash<int>; _H2 = std::__detail::_Mod_range_hashing; _Hash = std::__detail::_Default_ranged_hash; _RehashPolicy = std::__detail::_Prime_rehash_policy; _Traits = std::__detail::_Hashtable_traits<false, false, true>; std::_Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2,
_Hash, _RehashPolicy, _Traits>::__ireturn_type = std::pair<std::__detail::_Node_iterator<std::pair<const int, std::shared_ptr<std::vector<unsigned char> > >, false, false>, bool>]'

/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/unordered_map.h:380:54: required from 'std::pair<typename std::_Hashtable<_Key, std::pair<const _Key, _Tp>, _Alloc, std::__detail::_Select1st, _Pred,
_Hash, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_hash, std::__detail::_Prime_rehash_policy, std::__detail::_Hashtable_traits<std::__not_<std::__and_<std::__is_fast_hash<_Hash>, std::__detail::__is_noexcept_hash<_Key, _Hash> > >::value, false, true> >::iterator, bool> std::unordered_map<_Key, _Tp, _Hash, _Pred,
_Alloc>::emplace(_Args&& ...) [with _Args = {int, std::vector<unsigned char, std::allocator<unsigned char> >*}; _Key = int; _Tp = std::shared_ptr<std::vector<unsigned char> >; _Hash = std::hash<int>;
_Pred = std::equal_to<int>; _Alloc = std::allocator<std::pair<const int, std::shared_ptr<std::vector<unsigned char> > > >; typename std::_Hashtable<_Key, std::pair<const _Key, _Tp>, _Alloc, std::__detail::_Select1st, _Pred, _Hash, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_hash, std::__detail::_Prime_rehash_policy, std::__detail::_Hashtable_traits<std::__not_<std::__and_<std::__is_fast_hash<_Hash>, std::__detail::__is_noexcept_hash<_Key, _Hash> > >::value, false, true> >::iterator = std::__detail::_Node_iterator<std::pair<const int, std::shared_ptr<std::vector<unsigned char> > >, false, false>]'

<source>:8:47:   required from here

/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/ext/new_allocator.h:120:4: error: no matching function for call to 'std::pair<const int, std::shared_ptr<std::vector<unsigned char> > >::pair(int, std::vector<unsigned char>*)'

  { ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }

    ^

In file included from /opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/stl_algobase.h:64:0,

                 from /opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/memory:62,

                 from <source>:1:

/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/stl_pair.h:206:9: note: candidate: template<class ... _Args1, long unsigned int ..._Indexes1, class ... _Args2, long unsigned int ..._Indexes2> std::pair<_T1, _T2>::pair(std::tuple<_Args1 ...>&, std::tuple<_Args2 ...>&, std::_Index_tuple<_Indexes1 ...>, std::_Index_tuple<_Indexes2 ...>)

         pair(tuple<_Args1...>&, tuple<_Args2...>&,

         ^

/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/stl_pair.h:206:9: note:   template argument deduction/substitution failed:

In file included from /opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/x86_64-linux-gnu/bits/c++allocator.h:33:0,

                 from /opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/allocator.h:46,

                 from /opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/memory:63,

                 from <source>:1:

/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/ext/new_allocator.h:120:4: note:   mismatched types 'std::tuple<_Elements ...>' and 'int'

  { ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }

    ^

In file included from /opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/stl_algobase.h:64:0,

                 from /opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/memory:62,

                 from <source>:1:

/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/stl_pair.h:155:9: note: candidate: template<class ... _Args1, class ... _Args2> std::pair<_T1, _T2>::pair(std::piecewise_construct_t, std::tuple<_Args1 ...>, std::tuple<_Args2 ...>)

         pair(piecewise_construct_t, tuple<_Args1...>, tuple<_Args2...>);

         ^

/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/stl_pair.h:155:9: note:   template argument deduction/substitution failed:

In file included from /opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/x86_64-linux-gnu/bits/c++allocator.h:33:0,

                 from /opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/allocator.h:46,

                 from /opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/memory:63,

                 from <source>:1:

/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/ext/new_allocator.h:120:4: note:   cannot convert 'std::forward<int>((* & __args#0))' (type 'int') to type 'std::piecewise_construct_t'

  { ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }

    ^

In file included from /opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/stl_algobase.h:64:0,

                 from /opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/memory:62,

                 from <source>:1:

/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/stl_pair.h:150:12: note: candidate: template<class _U1, class _U2, class> constexpr std::pair<_T1, _T2>::pair(std::pair<_U1, _U2>&&)

  constexpr pair(pair<_U1, _U2>&& __p)

            ^

/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/stl_pair.h:150:12: note:   template argument deduction/substitution failed:

In file included from /opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/x86_64-linux-gnu/bits/c++allocator.h:33:0,

                 from /opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/allocator.h:46,

                 from /opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/memory:63,

                 from <source>:1:

/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/ext/new_allocator.h:120:4: note:   mismatched types 'std::pair<_T1, _T2>' and 'int'

  { ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }

    ^

In file included from /opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/stl_algobase.h:64:0,

                 from /opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/memory:62,

                 from <source>:1:

/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/stl_pair.h:144:12: note: candidate: template<class _U1, class _U2, class> constexpr std::pair<_T1, _T2>::pair(_U1&&, _U2&&)

  constexpr pair(_U1&& __x, _U2&& __y)

            ^

/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/stl_pair.h:144:12: note:   template argument deduction/substitution failed:

/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/stl_pair.h:141:38: error: no type named 'type' in 'struct std::enable_if<false, void>'

       template<class _U1, class _U2, class = typename

                                      ^

/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/stl_pair.h:138:12: note: candidate: template<class _U2, class> constexpr std::pair<_T1,
_T2>::pair(const _T1&, _U2&&)

  constexpr pair(const _T1& __x, _U2&& __y)

            ^

/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/stl_pair.h:138:12: note:   template argument deduction/substitution failed:

/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/stl_pair.h:136:27: error: no type named 'type' in 'struct std::enable_if<false, void>'

       template<class _U2, class = typename

                           ^

/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/stl_pair.h:133:12: note: candidate: template<class _U1, class> constexpr std::pair<_T1,
_T2>::pair(_U1&&, const _T2&)

  constexpr pair(_U1&& __x, const _T2& __y)

            ^

/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/stl_pair.h:133:12: note:   template argument deduction/substitution failed:

In file included from /opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/x86_64-linux-gnu/bits/c++allocator.h:33:0,

                 from /opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/allocator.h:46,

                 from /opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/memory:63,

                 from <source>:1:

/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/ext/new_allocator.h:120:4: note:   cannot convert 'std::forward<std::vector<unsigned char>*>((* &
__args#1))' (type 'std::vector<unsigned char>*') to type 'const std::shared_ptr<std::vector<unsigned char> >&'

  { ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }

    ^

In file included from /opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/stl_algobase.h:64:0,

                 from /opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/memory:62,

                 from <source>:1:

/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/stl_pair.h:128:17: note: candidate: constexpr std::pair<_T1, _T2>::pair(std::pair<_T1,
_T2>&&) [with _T1 = const int; _T2 = std::shared_ptr<std::vector<unsigned char> >]

       constexpr pair(pair&&) = default;

                 ^

/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/stl_pair.h:128:17: note:   candidate expects 1 argument, 2 provided

/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/stl_pair.h:127:17: note: candidate: constexpr std::pair<_T1, _T2>::pair(const std::pair<_T1, _T2>&) [with _T1 = const int; _T2 = std::shared_ptr<std::vector<unsigned char> >]

       constexpr pair(const pair&) = default;

                 ^

/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/stl_pair.h:127:17: note:   candidate expects 1 argument, 2 provided

/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/stl_pair.h:124:12: note: candidate: template<class _U1, class _U2, class> constexpr std::pair<_T1, _T2>::pair(const std::pair<_U1, _U2>&)

  constexpr pair(const pair<_U1, _U2>& __p)

            ^

/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/stl_pair.h:124:12: note:   template argument deduction/substitution failed:

In file included from /opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/x86_64-linux-gnu/bits/c++allocator.h:33:0,

                 from /opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/allocator.h:46,

                 from /opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/memory:63,

                 from <source>:1:

/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/ext/new_allocator.h:120:4: note:   mismatched types 'const std::pair<_T1, _T2>' and 'int'

  { ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }

    ^

In file included from /opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/stl_algobase.h:64:0,

                 from /opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/memory:62,

                 from <source>:1:

/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/stl_pair.h:112:26: note: candidate: constexpr std::pair<_T1, _T2>::pair(const _T1&, const
_T2&) [with _T1 = const int; _T2 = std::shared_ptr<std::vector<unsigned char> >]

       _GLIBCXX_CONSTEXPR pair(const _T1& __a, const _T2& __b)

                          ^

/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/stl_pair.h:112:26: note:   no known conversion for argument 2 from 'std::vector<unsigned char>*' to 'const std::shared_ptr<std::vector<unsigned char> >&'

/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/stl_pair.h:108:26: note: candidate: constexpr std::pair<_T1, _T2>::pair() [with _T1 = const int; _T2 = std::shared_ptr<std::vector<unsigned char> >]

       _GLIBCXX_CONSTEXPR pair()

                          ^

/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/bits/stl_pair.h:108:26: note:   candidate expects 0 arguments, 2 provided

Compiler returned: 1

How to open another window when the user enter correct user name and password in c++ gtkmm?

I am writing a program in which the user is supposed to enter the login details . If he enters the correct login details then the second window will open ( this is the actual app ) .

I have created login window . ( It has main .cpp )

I have also created my app . ( It also has main.cpp )

But I do not know how to link them ?

How to Solve ambiguous in clr based c++?

I am a .net developer. i am new to c++ code.

In native c++ project i am changed for the clr based for accessing c#. i am writing wrapper of c++ managed clr code.I was build the code it's throw the error

"ambiguous for IServiceProvider"

Error Image:-

enter image description here

In this IServiceProvider is include in native headers and managed clr namespaces. How can i solve this problem.

I was checking internet for this problem. i am not able to find the solution. they given solution not worked for me.

pls anyone know share the knowledge.

Thanks,

jeudi 26 avril 2018

Shared pointer segmentation faults -- how to properly share a PlanningScene?

ps_ptr is a boost shared pointer to a PlanningScene instance, created w/ boost::make_shared. The PlanningScene class is declared as,

class PlanningScene : private boost::noncopyable, public std::enable_shared_from_this<PlanningScene>

and includes a method clone for "copying" a planning scene.

These definitions imply to me there is a specific way this class is intended to be shared. What is the proper way to pass around ps_ptr? I would like to share it with another class SceneStuff, where SceneStuff only uses it to call a const method (PlanningScene::checkCollision).

Some notes:

  • Using ps_ptr as-is results in seg-faults due to double free or corruption. That's the compiler telling me I'm trying to free memory that has already been freed or was dereferenced, but shouldn't a boost::shared_ptr handle this? I've been through many SO threads on this topic, but to no avail.
  • I'm unable to call auto new_ps_ptr = ps_ptr->clone(ps_ptr); because no matching function for call to ‘planning_scene::PlanningScene::clone(boost::shared_ptr<planning_scene::PlanningScene>&)’
  • boost smart pointers docs

UPDATE: Thanks to Igor's comment I've switched ps_ptr to a std::shared_ptr, but still get seg-faults occasionally due to the following code (additionally invoked by SceneStuff)C:

// Setup collision-models
auto robot_model_ptr = ps_ptr->getRobotModel();
collision_detection::CollisionRobotFCL crobot(robot_model_ptr);
auto world_ptr = ps_ptr->getWorldNonConst();
collision_detection::CollisionWorldFCL cworld(world_ptr);

// Just standard structs
auto dreq = collision_detection::DistanceRequest();
auto dres = collision_detection::DistanceResult();

// Compute obstacle distances for the given `conf`
moveit::core::RobotState query_state = ps_ptr->getCurrentState();
query_state.setVariablePositions(x.data());  // x is simply an Eigen::VectorXd
cworld.distanceRobot(dreq, dres, crobot, query_state);

Here's the relevant source:

Generic Exponential Backoff Retry Mechanism C++11

I have written a generic exponential backoff retry loop in C++11. I'm using std::function to pass the callable to retry loop. callable will be retried if isRetriable function returns true.

#include <algorithm>
#include <cassert>
#include <chrono>
#include <functional>
#include <iostream>
#include <thread>

constexpr int64_t max_backoff_milliseconds = 30000; // 30 seconds
template <class R, class... Args>
R Retry(int max_retry_count, int64_t initial_dealy_milliseconds,
    const std::function<bool(R)> &isRetriable,
    const std::function<R(Args...)> &callable, Args &&... args) {
    int retry_count = 0;
    while (true) {
        auto status = callable(std::forward<Args>(args)...);
        if (!IsRetriable(status)) {
            return status;
        }

       if (retry_count >= max_retry_count) {
           // Return status and abort retry
           return status;
       }
       int64_t delay_milliseconds = 0;
       if (initial_dealy_milliseconds > 0) {
           delay_milliseconds =
               std::min(initial_dealy_milliseconds << retry_count,
                     max_backoff_milliseconds);
       }
       std::cout << "Callable execution failed. Retry Count:"
              << retry_count + 1 << std::endl;
       std::this_thread::sleep_for(
           std::chrono::milliseconds(delay_milliseconds));
      retry_count++;
   }
}

bool isRetriable(int status) {
    if (status == 5)
       return true;
    return false;
}

int foo(int x, int y) {
    static int a = 1;
    a += (x + y);
    return a / 6;
}

int main() {
    auto result = Retry(1000, 100, isRetriable, foo, 1, 3);
    std::cout << result << std::endl;
    return 0;
}

When I compile it, I'm getting below error:

prog.cpp: In function ‘int main()’:
prog.cpp:50:71: error: no matching function for call to ‘Retry(int, 
int, bool (&)(int), int (&)(int, int), int, int)’
auto result = Retry<int, int, int>(1000, 100, isRetriable, foo, 1, 3);
                                                                   ^
prog.cpp:11:3: note: candidate: template<class R, class ... Args> R 
Retry(int, int64_t, const std::function<bool(R)>&, const 
std::function<_Res(_ArgTypes ...)>&, Args&& ...)
R Retry(int max_retry_count,
^~~~~
prog.cpp:11:3: note:   template argument deduction/substitution failed:
prog.cpp:50:71: note:   mismatched types ‘const 
std::function<int(_ArgTypes ...)>’ and ‘int(int, int)’
auto result = Retry<int, int, int>(1000, 100, isRetriable, foo, 1, 3);
                                                                   ^  

Could someone explain to me why I have this error?