jeudi 31 janvier 2019

Why does std::is_copy_constructible not behave as expected?

#include <type_traits>

int main()
{
    std::is_constructible_v<int&, const int&>; // false, as expected.
    std::is_copy_constructible_v<int&>; // true, not as expected!
}

According to cppref:

If T is an object or reference type and the variable definition T obj(std::declval()...); is well-formed, provides the member constant value equal to true. In all other cases, value is false.

std::is_copy_constructible_v<int&> should give the same result as std::is_constructible_v<int&, const int&>, however, clang 7.0 gives different results as shown above.

Is this conforming to the C++ standards?

compile error in reactive extensions for cpp

I encounter a strange question about rxcpp. When capturing a rxcpp::connectable_observable variable and call it's connect method, I got a compile error as follow.

1>------ Build started: Project: LearnRx, Configuration: Debug x64 ------
1>Main.cpp
1>c:\users\liuzichao\source\repos\learnrx\learnrx\main.cpp(19): warning C4477: 'printf' : format string '%d' requires an argument of type 'int', but variadic argument 1 has type 'std::thread::id'
1>c:\users\liuzichao\source\repos\learnrx\learnrx\main.cpp(259): error C2662: 'rxcpp::composite_subscription rxcpp::connectable_observable<SourceValue,Multicast>::connect(rxcpp::composite_subscription)': cannot convert 'this' pointer from 'const Result' to 'rxcpp::connectable_observable<SourceValue,Multicast> &'
1>        with
1>        [
1>            SourceValue=int,
1>            Multicast=rxcpp::operators::detail::multicast<int,rxcpp::observable<int,rxcpp::sources::detail::create<int,publish_example::<lambda_3a462b77ca22ce68ef79403bfe94c65d>>>,rxcpp::subjects::subject<int>>
1>        ]
1>        and
1>        [
1>            Result=rxcpp::connectable_observable<int,rxcpp::operators::detail::multicast<int,rxcpp::observable<int,rxcpp::sources::detail::create<int,publish_example::<lambda_3a462b77ca22ce68ef79403bfe94c65d>>>,rxcpp::subjects::subject<int>>>
1>        ]
1>        and
1>        [
1>            SourceValue=int,
1>            Multicast=rxcpp::operators::detail::multicast<int,rxcpp::observable<int,rxcpp::sources::detail::create<int,publish_example::<lambda_3a462b77ca22ce68ef79403bfe94c65d>>>,rxcpp::subjects::subject<int>>
1>        ]
1>c:\users\liuzichao\source\repos\learnrx\learnrx\main.cpp(259): note: Conversion loses qualifiers
1>c:\users\liuzichao\source\repos\learnrx\learnrx\main.cpp(334): warning C4477: 'printf' : format string '%d' requires an argument of type 'int', but variadic argument 1 has type 'std::thread::id'
1>c:\users\liuzichao\source\repos\learnrx\learnrx\main.cpp(338): warning C4477: 'printf' : format string '%d' requires an argument of type 'int', but variadic argument 1 has type 'std::thread::id'
1>c:\users\liuzichao\source\repos\learnrx\learnrx\main.cpp(345): warning C4477: 'printf' : format string '%d' requires an argument of type 'int', but variadic argument 1 has type 'std::thread::id'
1>c:\users\liuzichao\source\repos\learnrx\learnrx\main.cpp(346): warning C4477: 'printf' : format string '%d' requires an argument of type 'int', but variadic argument 1 has type 'std::thread::id'
1>c:\users\liuzichao\source\repos\learnrx\learnrx\main.cpp(348): warning C4477: 'printf' : format string '%d' requires an argument of type 'int', but variadic argument 1 has type 'std::thread::id'
1>Done building project "LearnRx.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

The problem code is shown below.

void publish_example() {
    auto o = rxcpp::observable<>::create<int>([](rxcpp::subscriber<int> s) {
        s.on_next(0);
        s.on_next(1);
    }).publish();
    o.subscribe([](int v) {printf("%d", v); });
    rxcpp::observable<>::timer(std::chrono::microseconds(2000)).subscribe(
        [](const int i) {},
        [](const std::exception_ptr& e) {},
        [o]() {
        o.connect();
    }
    );
}

I tried 2 methods to pass compiling
1. Comment "o.connect()"
1. turn variable o to static variable, so o doesn't need to be captured. code is shown follow

void publish_example() {
    static auto o = rxcpp::observable<>::create<int>([](rxcpp::subscriber<int> s) {
        s.on_next(0);
        s.on_next(1);
    }).publish();
    o.subscribe([](int v) {printf("%d", v); });
    rxcpp::observable<>::timer(std::chrono::microseconds(2000)).subscribe(
        [](const int i) {},
        [](const std::exception_ptr& e) {},
        []() {
        o.connect();
    }
    );
}

Could you help telling me why the compile error appeared and hwo to figure it?

Thank you!

Questions on overloading operator+

My code did not work as I expected. For sure, I don't get the operator+ or something else.

the code is as follows:

Vector.h

class Vector
{
public:
    Vector(float x, float y);
    Vector(const Vector& other);
    ~Vector();

    Vector operator+(float a);

private:
    float mX;
    float mY;
};

Vector.cpp

#include "Vector.h"

Vector::Vector(float x, float y) : mX(x), mY(y)
{}

Vector::Vector(const Vector & other) : mX(other.mX), mY(other.mY)
{}

Vector::~Vector()
{}

Vector Vector::operator+(float a)
{
    Vector tmp(0.f, 0.f);
    tmp.mX = a + mX;
    tmp.mY = a + mY;

    return tmp;
}

Main.cpp

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


int main()
{
    Vector a(4.5, 2.5);

    Vector b = a + 1.5;
    Vector c = 1.5 + a;   // Compile error


    return 0;
}

Actually, what I want is that both Vector b = a + 1.5 and Vector c = 1.5 + a are working by operator+(float a).

But in the case of Vector c = 1.5 + a, it doesn't work.

I tried to solve it but I didn't. Do I have to add another function? but how??

Sorry to bother you, guys.

Please, enlighten me.

random_device()() work only for initializing data members

This is typical sequence of declarations/definitions for generating random numbers in C++11:

std::random_device rd
std::default_random_engine gen(rd());
std::uniform_int_distribution<> dist(1, 6);

rd is only used for seeding the generator gen, so I am thinking of not defining it in particular. In stead, I would like to use a temporary for this purpose:

int main() {
    std::default_random_engine gen(std::random_device()());
    std::uniform_int_distribution<> dist(1,6);
}

But compiler gave me an error:

function returns function

But this works if I initialize the engine as a data member:

class A
{
public:
    A();
private:
    std::default_random_engine gen;
    std::uniform_int_distribution<> dist;
}

A::A() : gen(std::random_device()()), dist(1) {}

So why can I not use std::random_device()() in normal statement to initialize a random generator but can use it in initializing data members? How to make it working in normal statement? Thanks.

PS: I am working on Windows 10 using Visual Studio 2015.

How to perform string validation & unit testing using google test in C++?

I am trying to write some string validation functions such as

  • check whether the string is NULL, Empty or have only spaces!

  • check whether the string is alphanumeric or uppercase!

I am only interested in strings with lowercase alphabets from a-z.(VALID strings) rest I want to block, so I have written the following functions:

std::string isEmpty(const std::string &input){
    // empty string
    if (NULL ==input || input=="\0" || !input.size())
        return "";
}
std::string isMalfunctioned(const std::string &input){
    for (int i = 0; i < input.size(); ++i){
        // string is not a-z or alphanumeric or uppercase
        if ( input[i] < 'a' || input[i] > 'z'|| isalpha(input[i]) || isupper(input[i]) )
            return "";
    }
}

and from the main function, I am just calling myFunc() using a reference to the input string & it calls the validation function written above to notify a user of incoming invalid strings:

#include"myFunc.h"

std::string myFunc(const std::string & input){
    if( isEmpty(input)== "")
        std::cout<<"Empty input"<< std::endl;
    if( isMalfunctioned(input)== "")
        std::cout<<"malfunctioned input"<< std::endl;
    return input;
}
int main(){
    std::string input="1234";
    std::cout << myFunc(input)<< std::endl;
    return  0;
}

My question:

  • First, I think my validation functions are not syntaticaly correct, since I am getting compile time errors as below, could anyone help in this regards?

mismatched types ‘const __gnu_cxx::__normal_iterator<_
Iterator, _Container>’ and ‘long int’

candidate: template<class _Iterator,
 class _Container> bool __gnu_cxx::operator==(const __gnu_cxx::__normal_iterator<_Iterat
or, _Container>&, const __gnu_cxx::__normal_iterator<_Iterator, _Container>&)
     operator==(const __normal_iterator<_Iterator, _Container>& __lhs,

  • Second, I think, my validation functions are not fully covering my specifications. Any suggestion for it?

  • Third, I have written some test cases using google test, but unable to interface with the above functionality, Any suggestions on what I am doing wrong & how to correct them? Also, any suggestion on refactoring the code is also welcomed!


#include "myfunc.h"
#include <gtest/gtest.h>

TEST(testbundle, EmptyString){
  ASSERT_EQ("", myfunc(""));
}

TEST(testbundle, Malfunctioned){
  ASSERT_EQ("", myfunc("ad34534654"));
  ASSERT_EQ("", myfunc("!$#sadasfd1"));
}

TEST(testbundle, LowerCase){
  ASSERT_EQ("abbsbdbbdbdb", myfunc("abbsbdbbdbdb"));
}
TEST(PreliminaryTest, UpperCaseString){
  ASSERT_EQ("", myfunc("ASDFFGGGHH"));
}

int main(int argc, char **argv){
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

Projection Points ArUco Marks

I am developed an application for calibrate 3 cameras, i'm using an Aruco board 3D. When i try to project points from 3D to 2D and then draw this, the ids markers is drawn randomly. I don't understand why this happens and is harder draw this markers exactly. I attach the image with the result:

enter image description here

Below you can see the output of my calibration

    "number camera": {
  "dist_coeffs": [  7.747757704467927e-20,  2.7128757910621084e-14, 2.0805976286646755e-22,
                          2.892724687955422e-22, -3.911300702468758e-20                                           ],

  "extrinsic_params": [  0.9955066953788915,    0.07732327027806252,  0.0546583143657419, 126.33880396061808,
                                   0.09469117766170831, -0.8128039484252789,   -0.5747898070576021, 307.0727477049988,
                                  -0.0000181338734452,    0.5773827615176801,   -0.8164736042110489, -74.26709128158872,
                                   0,                                  0,                                 0,                               1                            ],

  "intrinsic_params": [ 1, 0, 2.2509091168656316e-28, 
                                 0, 1, 1.6229852483634223e-28, 
                                 0, 0, 1                                      ] }

Please help!

Best Regards,

Input iterator can be read repeatedly while Output Iterator can only be written once?

I was reading The C++ Programming Language 4th edition by Bjarne Stroustrup. In the iterator chapter (Chapter 31.1.2), it says:

Input iterator: We can iterate forward using ++ and read each element (repeatedly) using *.

Output iterator: We can iterate forward using ++ and write an element once only using *.

I have done many searches on whether input iterator can be read only once or repeatedly, for example: http://www.cplusplus.com/reference/iterator/InputIterator/ https://www.geeksforgeeks.org/input-iterators-in-cpp/

and most suggests that input iterator can be read once only. But why the author says repeatedly for the input iterator? Is this correct? And if so, why input iterator can be read repeatedly but output iterator can only be written once. I always thought input and output iterator are completely opposite of each other.

Thanks everyone!

Is it legal to pass a pointer to a function expecting an array? [duplicate]

This question already has an answer here:

Consider the code:

double func(double a[3])
{
    /* do something with a and return */
}

int main(void)
{
    std::vector<double> test(LARGE_NUM_DIVISIBLE_BY_3);
    for (size_t i = 0; i < LARGE_NUM_DIVISIBLE_BY_3 / 3; ++i)
    {
        test[3 * i] = /* some random double */;
        test[3 * i + 1] = /* some random double */;
        test[3 * i + 2] = /* some random double */;

        double val = func(&test[3 * i]);
    }
}

Is this defined behavior in C++11? I.e., can I pass a pointer (&test[3 * i]) to a function that expects an array (double func(double a[3]))? I know if I were to go the other way (i.e., pass an array to a function that expects a pointer), the array would decay to a pointer - does the reverse also work?

Is write-only to a shared std::unordered_map thread safe?

Say I have an initialized but empty std::unordered_map, and two simultaneous threads that are going to populate it. The two threads will only write to the map, and nothing will read from the map until the two threads are done.

Furthermore, the two threads will never operate on the same keys in the map. For example, say Thread 1 will populate keys "A" through "M", and Thread 2 will simultaneously populate keys "N" through "Z".

Is this thread safe?

In my current implementation, I have 8 threads writing to a single mutexed std::unordered_map in the fashion described above. The mutex obviously slows the process down (there are close to 10,000 keys being populated), so I'm wondering if I even need the mutex.

Thanks all!

How to handel callback for a previous request

I have a hypothetical scenario for which I do not have a dummy code to list here.

Say we have two classes with each class registering a callback to each other - example Class A member function will be called by Class B as a callback and provides its own member method as std::function argument to callback when it is done. Now Class B waits on a timed semaphore for a response / callback after to which it will accept another request of a flow.

What will happen when response is now received for a previous request - how can we drop that call or ensure that nothing needs to be done now or identify that it is a response callback for a previous flow - in order to ensure that we fetch response from a mapped callback within a flow?

How to make it work, problem with 2 classes

i have problem with my small project. I have two classes in it. Problem:

error: 'Display' was not declared in this scope

Display is a class. Here is code:

//main.cpp
#include <iostream>
#include "Display.h"
#include "Polynomial.h"

using namespace std;

int main()
{
    Polynomial prr;
    prr.show();
    cout<<endl;
    cout<<"Enter x= ";
    int x;
    cin>>x;
    cout<<endl;

    cout<<"value for x="<<x<<endl<<"y="<<prr.value(x);

    Display aa; // this doesn't work
    //abc.show();

    return 0;
}


//Display.h
#ifndef DISPLAY_H
#define DISPLAY_H

class Display
{
    std::vector <vector <char> > graph;
    public:
        Display(int a, int b);
        //friend void lay(Polynomial abc,Display cba);
        //void show();
};

#endif // DISPLAY_H

I was thinking that maybe vectors are doing problems. I tested it without vectors, but it didn't change anthing.

//Display.cpp
#include "Display.h"
#include <iostream>

using namespace std;


Display::Display(int a, int b)
{
    //ctor
    if(a%2==0)
        a++;
    if(b%2==0)
        b++;

    vector <char> help;
    vector <char> mid;

    for(int i=0; i<b; i++)
    {
        mid.push_back('-');
        if(i==(b+1)/2)
            help.push_back('|');
        else
            help.push_back(' ');
    }

    for(int i=0; i<a; i++)
    {
        if(i==(a+1)/2)
            graph.push_back(mid);
        else
            graph.push_back(help);
    }
}

Now it's Polynomial class it's working fine, but Display class no, and i don't know why.

//Polynomial.h
#ifndef POLYNOMIAL_H
#define POLYNOMIAL_H
#include <vector>



//class Display;

class Polynomial
{...}


#endif // POLYNOMIAL_H


//Polynomial.cpp
#include "Polynomial.h"
#include <iostream>
#include <windows.h>
#include <cmath>

using namespace std;

// constructors and methods here
// everything here working fine

function to convert unsigned char * to char and char * to unsigned char *

I want a function to convert unsigned char * to char * and vice versa . Looking for two functions 1. That takes unsigned char * as parameter and returns char *. 2. That takes char * as parameter and returns unsigned char *.

The conversion should not lose any information during conversion.

Telnet server always returns garbage when connecting to it using Boost Asio

So I am trying to make a telnet client that connects to some address part for work and part for Boost::Asio learning purpose.

My small project has three handlers:

Resolve handler:

void resolverHandler(const boost::system::error_code& ec, ip::tcp::resolver::iterator iter) {
    if (ec) {
        cout << "Resolved failed with message: " << ec.message() << endl;
    }
    else {
        ip::tcp::endpoint endpoint = *iter;
        cout << "Connection to: " << endpoint.address() << ":" << endpoint.port() << endl;
        tcpSocket.async_connect(endpoint, connectHandler);
    }
}  

Connect handler

   void connectHandler(const boost::system::error_code& ec) {
        if (ec) {
            cout << "Connect failed with message: " << ec.message() << endl;
        }
        else {
            cout << "Connection established" << endl;
            tcpSocket.async_read_some(buffer(_data), readHandler);
        }
    }

Read handler:

void readHandler(const boost::system::error_code& ec, size_t ammountOfBytes) {
    if (ec) {
        cout << "Read failed with message: " << ec.message() << endl;
    }
    else {
        cout << ammountOfBytes << endl;
        cout << _data.data() << endl;
        tcpSocket.async_read_some(buffer(_data), readHandler);
    }
}

And this is my main function:

io_service ioservice;
ip::tcp::resolver resolver(ioservice);
ip::tcp::socket tcpSocket(ioservice);
array<char, 16> _data;
ip::tcp::resolver::query query("192.168.200.200", "23");


int main() {

    resolver.async_resolve(query, resolverHandler);

    ioservice.run();

    return 0;
}

But I always get garbage like this:

Connection to: 192.168.206.226:23
Connection established
15
 ² ²  ²# ²' ²$

I admit that I am new to telnet, but I am not sure why do I get this response ? Not sure if I need to null terminate the data that I receive before printing it, but even like that I have the same response.

Here is the normal response I should receive - tried with Windows Telnet:

Welcome Message (localhost) (ttyp0)

login:

Apreciate if someone has any ideas on what to do.

What is benfit of throw catch over if else

I gone through this question and I know about standard exception objects. My question is, What is the benefit of using exception over simple function calling ?

For Example Code A

#include <stdexcept>

int compare( int a, int b ) {
    if ( a < 0 || b < 0 ) {
        throw std::invalid_argument( "received negative value" );
    }
}

try {
    compare( -1, 3 );
}
catch( const std::invalid_argument& e ) {
    // do stuff with exception... 
}

and Code B

int compare( int a, int b ) {
    if ( a < 0 || b < 0 ) {
        throwFunc( "received negative value" );
    }
}


compare( -1, 3 );

throwFunc(const std::string& e ) {
    // do stuff with exception... 
}

What is the benefit of Code A over Code B ? and benefit of standard exception objects ? Ultimately we just throw a variable or string.

How to abort gRPC streaming on error and indicate the error in C++

I'm sending a synchronous stream of gRPC messages from a client written in C++, in the following sequence:

  • Obtain an unique_ptr to a ClientWriter
  • Call its Write() method with messages as many times as needed.
  • Call its WritesDone() method
  • Call Finish() to obtain the server's status.

How would I abort this sequence in case of a client-side error and indicate that to the server?

How to convert std::array to boost::asio::buffer?

I am trying to convert an std::array to an boost::asio::buffer to use it for async_read_some, but I always get some errors:

Here is my code sample:

array<char, 16> data;
tcpSocket.async_read_some(buffer(data), [data](const boost::system::error_code& ec, size_t ammountOfBytes) {
if (ec) {
    cout << "Read failed with message: " << ec.message() << endl;
}
else {
    cout.write(data.data(), ammountOfBytes);
}
});

This are the errors I get:

Error   C2661   'boost::asio::detail::buffer_sequence_adapter_base::init_native_buffer': no overloaded function takes 1 arguments
Error   C2440   '<function-style-cast>': cannot convert from 'const boost::asio::const_buffers_1' to 'boost::asio::mutable_buffer'

I find it weird that all examples I see online use the same syntax.

Why would temporary lifetime extension cause destructor to be called multiple times?

Consider the following snippet:

#include <iostream>

using namespace std;

class Temp {
    public:
    Temp() { cout << "Temp()" << endl;}
    ~Temp() { cout << "~Temp()" << endl;}
};

Temp GetTemp() {
     cout << "GetTemp" << endl;
    return Temp();
}

Temp TakeTemp(Temp temp) {
    cout << "TakeTemp" << endl;
    return temp;
}


int main()
{
    TakeTemp(GetTemp());

    return 0;
}

When I ran TakeTemp(GetTemp());, the output looks like

GetTemp                                                                                                                                                        
Temp()                                                                                                                                                         
TakeTemp                                                                                                                                                       
~Temp()                                                                                                                                                        
~Temp()     

Note that ~Temp() is called twice here (but only 1 temp obj is constructed). This seems odd since 1) the temp variable returned by GetTemp() is supposed to have its lifetime extended to the full expression, and 2) since we return temp directly in TakeTemp, return value optmization will reuse the same object.

Can anyone explain why there are multiple dstor calls here?

(Note that if we place more layers of TakeTemp() around, the number of dstor calls grows proportionally.)

mercredi 30 janvier 2019

Cant compile Windows Socket in C

i've made in my windows desktop, a c socket code, but when i compile, it gives me erros, i dnt know how to proceed, can someone help me? i am working in windows 7, but also tried this same code in windows 10, but i got the same errors, here is the c code, i also tried in c++ but got the same errors, c code below:

#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <string.h>
#pragma comment (lib, "Ws2_32.lib")

#define PORT 5555
#define HOST "192.168.1.30"
#define MAX_L 4096
int main(void){
    char bfs[MAX_L], bfr[MAX_L];
    int sockfd;
    socklen_t sin_size = sizeof(struct sockaddr_in);
    struct sockaddr_in target_addr;
    struct WSAData wsa;
    WSAStartup(MAKEWORD(2,2),&wsa);

    sockfd = socket(PF_INET, SOCK_STREAM, 0);

    target_addr.sin_port = htons(PORT);
    target_addr.sin_family = AF_INET;
    target_addr.sin_addr.s_addr = inet_addr(HOST);

    connect(sockfd, (struct sockaddr *)&target_addr, sin_size);

    while(1){

        gets(bfs);
        send(sockfd, &bfs, MAX_L, 0);
        recv(sockfd, &bfr, MAX_L, 0);
        printf("%s\n", bfr);


    }

    closesocket((SOCKET) sockfd);

    WSACleanup();


}

error:

gcc -o csocketcode csocketcode.c -lwinsock2

how to use a .lib fule in c++ Qt creator without header

i have this lib file : [mylibfile.lib][1]

The tree of library is :

|--3rdparty/LinphoneSdk/include
     ||------------------------nothing 
|--3rdparty/LinphoneSdk/lib
     |---------------------linphone++.lib

But I do not know how to use linphone++.lib file.

If anyone can help me I will be very grateful.

i use Qt Creator 4.8.0 (Enterprise)

Is it possible to use .lib file without header files ?

i use this :

#include "mainwindow.h"
#include <QApplication>
#include <linphone++/linphone.hh>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

But this throws an error :

linphone++/linphone.hh file not found

in my untitled2.pro , i have this codes :

#-------------------------------------------------
#
# Project created by QtCreator 2019-01-15T00:01:40
#
#-------------------------------------------------

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = untitled2
TEMPLATE = app

# The following define makes your compiler emit warnings if you use
# any feature of Qt which has been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

CONFIG += c++11

SOURCES += \
        main.cpp \
        mainwindow.cpp

HEADERS += \
        mainwindow.h

FORMS += \
        mainwindow.ui

INCLUDEPATH += 3rdparty/LinphoneSdk/include

LIBS += -L"3rdparty/LinphoneSdk/lib" -lLinphoneSdk

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

How to use a 2-D array as strings for each row so that they may be passes through functions in c++?

I am writing a program in c++ that stores a list of names from a file, stores the list into a 2-D array (size predetermined), and sorts the names. I am able to get a 2-D array from the names, but I am not quite sure how to approach using individual rows as seperate strings so I may pass them through functions that have 1-D char arrays as parameters, here is the relevent code.`

int main(){
cout << "Please enter the names of input and output files\n Enter file name 1.";
string filename1, filename2;
cin >> filename1;
cout << "\nEnter file name 2.";
cin >> filename2;
ifstream file1;
ofstream file2;
file1.open(filename1.c_str());
file2.open(filename2.c_str());
char names[10][9] = {'\0'};
char temp;                      // Now the files have been opened and the array created with a temp variable to store the characters being read from "file1"
for (int i = 0; i < 9; i++){
    for( int j = 0; j < 8; j++){
temp = file1.get();
file2 << temp;
names[i][j] = temp; //the 2-D array is created with a list of names
}
}

cout << "\n";

for (int i=0; i<9 ; i++){
for (int j=0; j<8 ; j++){   //printing out the names
cout << names[i][j];}
}


cout << "\n\n";

char string1[10];            //Here is where I am confused on how to do this part?? how do I use just one ROW of the array?
for (int i=0;i<9;i++){
temp = file1.get();
string1[i] << temp;
string1[i] = temp;
}
cout << string1;           
cout << myStringLength(string1);

return 0;
}

Multiple assignment into unique_ptr using make_unique

Is a multiple assignment into unique < T > pointer valid? Based on output it is, but is T destructor calling guaranteed when make_unique is called and value is assigned to already allocated memory?

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

class A{
public:
    A(){ std::cout << "Construcor" << std::endl;}
    ~A(){ std::cout << "Destrucor" << std::endl;}
    void foo(){std::cout << "foo" << std::endl;}
};

int main()
{
    std::unique_ptr<A> pointer;
    for(auto i = 0; i< 2; ++i){
        pointer = std::make_unique<A>();
        pointer->foo();
    }
}

output:

Construcor
foo
Construcor
Destrucor // Destructor is called because first instance of A is out of scope?
foo
Destrucor

Why is narrowing conversion not preventing this map.insert() of an incorrect type from failing?

Background

When inserting a std::pair<uint64_t, uint64_t> to a C++ std::map<uint64_t, int>, neither the compiler nor the program complains, even if the passed values are not possible for the data type uint64_t.

In other words, the narrowing conversion of std::pair<uint64_t, uint64_t>(2, -2) isn't working and is defaulting to the map's type std::map<uint64_t, int>

Code

When I compile and execute the following code with g++ -Wall -Wconversion -Wextra -pedantic test/test_wrong_insert.cpp && ./a.out:

#include<map>
#include<iostream>

void print_map(std::map<uint64_t, int> & m){
  std::cout << "The map is now: {";
  for (const auto & n: m){
    std::cout << '(' << n.first << ',' << n.second << ") ";
  }
  std::cout << "}\n";
}

int main(){
  std::map<uint64_t, int> m;

  ret = m.insert(std::pair<uint64_t, uint64_t>(2,-2));
  std::cout << "Tried to insert std::pair<uint64_t, uint64_t>(2,-2). ";
  std::cout << "Return: " << ret.second << '\n';
  print_map(m);
}

Result

... this is the output:

Tried to insert std::pair<uint64_t, uint64_t>(2,-2). Return: 1
The map is now: {(2,-2) }

Question

Why does std::pair<uint64_t,uint64_t> x{-1,-2} not produce an error, and how do I make it cause an error?

Efficient way of returning a lambda in a function that needs a call to an object

Following up from this past post:

A user stated:

Are you comfortable using lambdas in C++11? If yes, you simply need to return one from first_function(), and then you call the lambda in perform_action(). Of course, you need to pass the parameter to the lambda, but you wouldn't need to pass it to first_function()

I'm not quite sure how to do this or if this is even a good idea past on this other stackoverflow post

Just keep in mind that std::function employs type erasure, which can mean the cost of making a virtual function call when calling the std::function. Something to be aware of if the returned function is going to be used in a tight inner loop or other context where the slight inefficiency matter. – Anthony Hall

The call to the perform_action function template will be called in a loop. I don't understand if what Anthony above, will affect me since I plan to use that function call inside a class method.

Here's a snippet from the post link above:

// class that uses the shared_ptr

class setter {
private:

std::shared_ptr<Base> l_ptr;

public:

setter(const std::shared_ptr<Base>& input):l_ptr(input)
{}

int get_thing_a()
{
    return perform_thing<THINGA>(..);
}

int get_thing_b()
{
    return perform_thing<THINGB>(..);
}
};

So what I really want to know is if its recommended to use this solution posted:

template <>
struct thing_traits<THINGA>
{
    static int (Base::*first_function)() = &Base::get_thing_one;
    ...
}

template < thing_select T,  typename TT = thing_traits<T>>
int perform_action(Base & b)
{
   return (b.*TT::first_function)() + ...;
}

Or the suggestion of modifying it to return a lambda function instead. If so, would this mean passing the Base class parameter as a "capture" to the lambda?

If I do use a lambda, when is it appropriate to use std::function vs a function pointer (using C++11). I didn't find a lot (or didn't know how to term the search) for my case of objects calling lambda functions, from a static function in the traits class. A drafted example would help.

Boost serialization performance issue

I am using Boost serialization to serialize data from producer to consumer. I am using stringstream to serialize into a string instead of writing to a file. I am seeing significant performance overhead due to serialization. The first step I did was to change from text_archive to binary_archive, this did help. Next, I added the following which also seems to help - BOOST_CLASS_IMPLEMENTATION(MyClass,boost::serialization::primitive_type)

Can anyone help me understand what the above line of code does? I saw it somewhere when I was googling for boost serialization, I cannot use this code unless I understand what it means.

Boost serialization has a concept of a version number. I do not care for version since in my case both producer and consumer are guaranteed to use the same version. Is there anything I can do to tell boost serialization code to not worry about versions numbers. Would this reduce the overhead?

Trouble deducing return type for wrapper of member functions

I have a collection of methods with varying signatures which all need the same prefix and postfix code, so I'd like to wrap each of them up neatly. I'm trying to formulate a c++11 variadic template for a generic wrapper to my member functions, and I hit trouble when deducing the return type. Auto works, but I need the return type explicitly to provide a valid return value even if I catch an exception inside the wrapper when executing the wrappee.

So far I managed to deduce the return type for a plain wrapper function using std::result_of and I got correct behaviour for non static member functions using auto. I tried for two days now to make the std::result_of approach work for member functions, also tried a lot of variations of decltype and declval, but with no luck so far. I am running out of ideas on how to deduce the return type.

This is my working example

#include <iostream>

int foo(int a, int b) { return a + b; }
int bar(char a, char b, char c) { return a + b * c; }


template<typename Fn, typename... Args>
typename std::result_of<Fn&(Args... )>::type 
wrapFunc(Fn f, Args... args) {
  //Do some prefix ops
  typename std::result_of<Fn&(Args... )>::type ret = f(std::forward<Args>(args)...);
  //Do some suffix ops
  return ret;
}

class MemberWithAuto {
  private:
  public:
    MemberWithAuto() {};
    int foo(int i, int j) { return i + j;}

    template<typename Fn, typename... Args>
    auto wrapper(Fn f, Args... args) {
      //Do some prefix ops
      auto ret = (*this.*f)(std::forward<Args>(args)...);
      //Do some suffix ops
      return ret;
    } 
};



int main() {

  std::cout << "FuncWrapper for foo with 1 + 2 returns "         << wrapFunc<decltype(foo)>(foo, 1, 2)      << std::endl;
  std::cout << "FuncWrapper for bar with 'a' + 'b' * 1  returns "  << wrapFunc<decltype(bar)>(bar, 'a','b', 1)  << std::endl;

  MemberWithAuto meau = MemberWithAuto();
  std::cout << "MemberFunction with Auto with 6 + 1 returns  "  << meau.wrapper(&MemberWithAuto::foo, 6, 1)  << std::endl;

  return 0;
}

Both of these work well, but the wrapper method using auto doesn't get me the return type for later use. I tried lots of variations with std::result:of and decltype with the following code, but I can't get it to compile correctly

#include <iostream>

int foo(int a, int b) { return a + b; }
int bar(char a, char b, char c) { return a + b * c; }

class MemberWithDecl {
  private:
  public:
    MemberWithDecl() {};
    int foo(int i, int j) { return i + j;}

    template<typename Fn, typename... Args>
    typename std::result_of<Fn&(Args... )>::type wrapper(Fn f, Args... args) {
      //Do some prefix ops
      typename std::result_of<Fn&(Args... )>::type ret = (*this.*f)(std::forward<Args>(args)...);
      //Do some suffix ops
      return ret;
    } 
};



int main() {
  MemberWithDecl medcl = MemberWithDecl();
  std::cout << "MemberFunction with declaration also works "  << medcl.wrapper(&MemberWithDecl::foo, 6, 1)  << std::endl;
  return 0;
}

I was expecting to find a solution where the signature of Fn with Args... is correctly recognized, because auto also successfully deduces the types. My type declaration does not seems to find a matching template though, no matter the variations I tried, I get

error: no matching function for call to ‘MemberWithDecl::wrapper(int (MemberWithDecl::*)(int, int), int, int)’

If I leave the wrapper's return type to be auto and just try my declaration for the variable ret within, I get

error: no type named ‘type’ in ‘class std::result_of<int (MemberWithDecl::*&(int, int))(int, int)>’
       typename std::result_of<Fn&(Args... )>::type ret = (*this.*f)(std::forward<Args>(args)...);

After reading the standard, I think this means that result_of does not regard Fn&(Args... ) to be well-formed, but I don't know how the correct form should look like.

Any help would be much appreciated

Could not make this code cross compile between MSVC 2015 and GCC 7.3

While I was writing code for my project I found a very weird situation in which my C++11 code could not be cross compiled between GCC 7.3 and MSVC 2015. The case is basically this one:

// .H file

template <typename X>
struct Outer {
    X x = {};

    template <typename Y>
    struct Inner {
        Y y = {};
        Inner& operator++();
    };
};

// .INL file

template <typename X>
template <typename Y>
inline Outer<X>::Inner<Y>&
    Outer<X>::Inner<Y>::operator++()
{
    ++y;
    return *this;
}

// .CPP file

#include <iostream>

int main()
{
    Outer<int>::Inner<int> a;
    ++a;
    std::cout << a.y << std::endl;

    return 0;
}

GCC will not complain about the above code. But MSVC will, and the error would be:

warning C4346: 'Inner': dependent name is not a type note: prefix with
'typename' to indicate a type error C2061: syntax error: identifier
'Inner' error C2143: syntax error: missing ';' before '{' error C2447:
'{': missing function header (old-style formal list?)

As suggested by the MSVC compiler itself, writing the typename keyword on the return type will fix the issue:

template <typename X>
template <typename Y>
inline typename Outer<X>::Inner<Y>&
Outer<X>::Inner<Y>::operator++()
{
    ++y;
    return *this;
} 

But now, quite surprisingly, GCC will not compiler anymore, and its error is:

error: non-template 'Inner' used as template
     inline typename Outer<X>::Inner<Y>&
                               ^~~~~ note: use 'Outer<X>::template Inner' to indicate that it is a template error: expected
unqualified-id at end of input

Again, as suggested by the compiler itself, I tried to add the keyword template to the return type, and this will fix the issue for GCC:

template <typename X>
template <typename Y>
inline typename Outer<X>::template Inner<Y>&
Outer<X>::Inner<Y>::operator++()
{
    ++y;
    return *this;
}

But this fix will now break once again the MSVC build, and the error from the compiler is:

error C2244: 'Outer<X>::Inner<Y>::operator ++': unable to match
function definition to an existing declaration note: see declaration
of 'Outer<X>::Inner<Y>::operator ++' note: definition note:
'Outer<X>::Inner<Y> &Outer<X>::Inner<Y>::operator ++(void)' note:
existing declarations note: 'Outer<X>::Inner<Y>
&Outer<X>::Inner<Y>::operator ++(void)'

This time around, I just stopped as the compiler error message is not helpful, as the reported mismatch between definition and declaration does not exist: the signatures given by the compiler itself are perfectly matching.

At this point, not knowing any better solution, I decided to just define the function inside the Inner class scope in the .H file, and that would work for both GCC and MSVC. But some questions still remain: who is right? GCC or MSVC? Or is the C++ standard that in this case is too ambiguous?

std::is_member_function_pointer not working for noexcept member functions

I am having trouble with std::is_member_function_pointer. As far as I can tell, it's not working when given a noexcept member function. I cannot find anything in the standard declaring that it does not work for noexcept qualified member functions. Example of the problem:

#include <type_traits>

class A {
public:
    void member() noexcept { }
};

int main()
{
    // fails at compile time if A::member is a data member and not a function
    static_assert(std::is_member_function_pointer<decltype(&A::member)>::value,
                  "A::member is not a member function."); 
}

It gives me the following error:

member.cpp:11:5: error: static_assert failed due to requirement 'std::is_member_function_pointer::value' "A::member is not a member function." static_assert(std::is_member_function_pointer::value, ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1 error generated.

If I remove the noexcept qualification it compiles as it should.

This has been tested on Debian Stretch, using clang 6.0 and libstdc++ 6.3.0 Am I missing something here? From what I can read, this should work.

Call methods through macro expansion

I have this code:

class A {
public:
  bool has_foo() { return true; }
};

int main() {
  A a;

  CALL(a, foo);
}

I'd like to call the method has_foo through macro expansion:

#define CALL(object, method) do { object.has_ ## method ## (); } while(0)

The code above compiles on MSVC, but fails with GCC.

I would like to use macro expansion in order to avoid runtime overhead.

Worker threads, running in a DLL gets killed, on application shutdown, before one can gracefully shutdown them

I, for some reason, need to have a global object in a .dll, which manages a std::thread. It is implemented in a following way:

#include "Header.h"
#include <thread>
#include <condition_variable>
#include <mutex>

class Foo
    {
public:
    Foo () : m_closeThread (false)
        {
        m_thread = std::thread (&Foo::ThreadProc, this);
        }

    ~Foo ()
        {
            {
            std::unique_lock<std::mutex> lock (m_mutex);
            m_closeThread = true;
            }

        m_cv.notify_one ();
        m_thread.join ();
        }

private:
    void ThreadProc ()
        {
        while (true)
            {
            std::unique_lock<std::mutex> lock (m_mutex);
            m_cv.wait (lock, [this] () { return m_closeThread; });
            if (m_closeThread)
                break;
            }
        }

private:
    bool m_closeThread;
    std::thread m_thread;
    std::condition_variable m_cv;
    std::mutex m_mutex;
    };

Foo& GetFoo ()
    {
    static Foo foo;
    return foo;
    }

extern "C" void Function ()
    {
    auto& foo = GetFoo ();
    }

However, when, the application is closed, before the ~Foo is executed, all worker threads, of the .dll, get killed, or as the output window of MSVS2015 says:

The thread 0x1040 has exited with code 0 (0x0).

And, due to this fact (Source0, Source1), the application blocks on m_cv.notify_one (); call, if one uses Windows 7 (doesn't block on Windows 8 and above).

The fact, that it blocks on one particular version of Windows, while not on others, makes me think, that some sort of UB is to blame (such as DLL unload ordering related issue, since such issue is not reproducible if such object is not in a .dll), but I fail to think of solution, that allows me to gracefully shutdown the thread, while having the object global (since, one would need to do major application restructuring, to make it not global).

So, can one shutdown the thread gracefully, before it is killed by the Windows platform?

Side note 0:

For the sake of example completeness,

this is the DLLMain:

#include <Windows.h>

BOOL APIENTRY DllMain (HMODULE, DWORD, LPVOID) { return TRUE; }

This is the Header of the .dll:

#pragma once
extern "C" void Function ();

This is the Console application, that uses said .dll:

#include "..\Test\Header.h"
#include <chrono>
#include <thread>

int main ()
    {
    Function ();
    using namespace std::chrono_literals;
    std::this_thread::sleep_for (2s);
    }

Side note 1:

I am, currently limited to using, at most, C++11 (or, whatever functionality is present in MSVS 2015).

How to remove data from class instance after data being returned once

In my app I need to read some values from some source, keep them for a while in a storage, and then apply. After being applied, values are not needed and can be removed from the storage.

class Storage: public Singleton<...> {
public:
    void addValue(int v) {values.push_back(v);}
    // ...
private:
    std::vector<int> values;
    // ...
}

// read values from some source and keep them in the storage
void Init() {
    for (...) {
        Storage::Instance()->addValue(...);
    }
}

// a few seconds later...

// apply values somehow and get rid of them
void Apply() {
    auto &&values = Storage::Instance()->getValues();
    // ideally, at this point Storage must not contain values array
    // process values somehow
    for auto i: values {
    // ...
    }
    // values are not needed any longer
}

My question is how do I implement getValues method? Is it possible to implement it so that it clears values array in Storage after being called (using move semantics or whatsoever)? In other words, there is no need to keep values in Storage after getValues has been called once.

If it is not possible, I will have to implement additional method say Storage::clearValues which I would need to call at the end of Apply() -- this is what I am tryng to avoid.

How to make and class array to define what class use to next instance?

I usually works with python and I keep the mind of this language. So I want to make an array or struct like that:

struct instanceType = {
std::string name,
class typeOfclass
};

The idea is to run a loop to check from a string list a match with instanceType and get from this the class for instance a new object. e.g.

instanceType type1;
type1.name = "Type1";
type1.class = Class1;
instanceType type2;
type1.name = "Type2";
type1.class = Class2;
int implementTypes = 2;
instanceType typesArray[implementTypes] = {type1, type2};

// This is the goal I want
...
for(int i=0; i < implementTypes; ++i) {
    for(const std::string& objectToCreate; objectsToCreate) {
        if(typesArray[i].name==objectToCreate) {
            typesArray[i].class newObject = typesArray[i]() //"Constructor"
        }
    }
}

It could be crazy but it would be very useful to be able to use something similar.

strong type checking for user-defined types

sometimes we using using Key = uint32_t; to define the new type. The problem is - it is just alias. If you define two various types, they are not really type-checked:

using RowKey = uint32_t;
using ColKey = uint32_t;
std::map

<RowKey, std::map<ColKey, int>> myStorage;

RowKey keyR = 1;
ColKey keyC = 2;

int res1 = myStorage[keyR][keyC]; // it's ok
int res2 = myStorage[keyC][keyR]; // it's ok too, but it shouldn't compile!

A possible solution is to define a wrapper class around the int (or something else we have as key), but i think, this is overhead..

Is there any another solutions (maybe, in the new C++ standards)?

How to write a templated version of this slicing code of Eigen?

I wrote this little piece of code to slice a MatrixXd with a boolean array. I'd like to know how to turn it into a templated version, that works on both matrices and vectors? Any tips? I have not been able to get very far with MatrixBase<Derived>.

#include <Eigen/Dense>
using namespace Eigen;

MatrixXd slice(const MatrixXd & mat, const Array<bool, Dynamic, 1> & ind)
{
    assert(mat.cols() == ind.size());
    int _cols = 0;
    for(int i = 0; i < ind.size(); ++i)
    {
        if(ind[i] == 1)
        {
            _cols += 1;
        }
    }
    int _pos = 0;
    MatrixXd out = MatrixXd::Zero(mat.rows(), _cols);
    for(int i = 0; i < ind.size(); ++i)
    {
        if(ind[i] == 1)
        {
            out.col(_pos) = mat.col(i);
            _pos += 1;
        }
    }
    return out;
}

And usage is like this:

MatrixXd A(4, 4);
A << 1,2,3,4,
     5,6,7,8,
     1,5,6,3,
     9,8,6,5;
VectorXd b(4);
b << 23,-4,1234,3;
cout << A << endl;
cout << (b.array() > 5) << endl;
cout << slice(A, b.array() > 5) << endl;

Output is as such:

1 2 3 4
5 6 7 8
1 5 6 3
9 8 6 5
1
0
1
0
1 3
5 7
1 6
9 6

I'd appreciate if anyone would show me how to do this!

What C++'s equivalent to winapi's MsgWaitForMultipleObjectsEx

As I'm making the transition from native winapi calls to manage thread's message queue to c++ code, I have encountered a question which i can't fully answer.

Given the following code snippet

LRESULT QueueConsumeThread()
        {
            MSG msg = { 0 };

            HANDLE hHandles[] = { hHandle1, hHandle2 };
            while (true)
            {
                DWORD dwRes;
                switch (dwRes = ::MsgWaitForMultipleObjects(_countof(hHandles), hHandles, FALSE, INFINITE, QS_ALLEVENTS))
                {
                case WAIT_OBJECT_0 :
                    DoSomething();
                    break;
                case WAIT_OBJECT_0 + 1:
                    DoSomething2();
                    break;
                case WAIT_OBJECT_0 + _countof(hHandles):
                    ATLASSERT(msg.message == WM_QUIT);
                    return 1;
                }
            }

            return 1;
        }

I have read in many sources that a particular thread should be a associated with a single condition_variable, also, using multiple condition_variables or invoking wait_for() wait_until() doesn't sound too efficient.

The following source suggested implementing a safe_queue using condition_variables, I guess that PeekMessage/GetMessage/MsgWaitForMultipleObject work similarity, but what kind of data each cell of the queue should hold and be to receive event signal?

Edit: Asking this as I have to write a cross-platform application.

How does the vector::size() returns size of the vector in constant time?

I was going through this C++ Reference and found that using vector::size() returns the size of the vector in constant time. But, I wonder how one could get the size without actually traversing the vector.

How to access non signleton class method from different class

I have a class let say.

Class A {

static A* create (); // this will give object of A (This is not single ton)

RequestToSubscribe(){
}

onResponseTosubscribe()
{
    notify()// sending update to subscribe
}

};

I have another two class B and C . which will subscribe on class A.

    Class B {

  /* creation of object of A */

     RequestToSubscribe() // call to subscribe

    notify(){
            // will receive notification from A
    }

    };


    Class C {
    /* creation of object of A */

     RequestToSubscribe() // call to subscribe

    notify(){
            // will receive notification from A
    }

    };

Now if both B and C subscribe using RequestToSubscribe(). How to send update to both B and C from A when onResponseTosubscribe is received? when both B and C are subscribe successfully.

mardi 29 janvier 2019

Can you use std::bind (or something else) to change return type?

Say I've got a function,

bool my_func(bool input_val) { return !input_val; }

and I want to pass it around as a function that returns void and takes nothing, so it would be something like:

bool the_truth = true;
func_taking_a_void_func([the_truth]() -> void { my_func(the_truth); });

I tried using std::bind, but the compiler says something about the function returning a value, and being unable to convert.

func_taking_a_void_func(std::bind(my_func, the_truth));

Is it possible to do something like this without a lambda? I'm using C++11 on VS2013, but anything else is good too.

Is base case function mandatory or could it be automatically synthesized?

In the following code :

void print()
{
    // This is our base case fn
    ;; // Do nothing
}

template <typename type1, typename... argspack>
void print(type1 a, argspack... args_rest)
{
    cout << a << ((sizeof...(args_rest) != 0) ? "," : "\n");
    print(args_rest...); // I guess this recursive call is inevitable
}

If the recursive call to variadic function is inevitable, the base case function is also inevitable. If so, is there a language feature, perhaps one that comes with modern c++, that help a programmer get away without writing a base case function?

the data method of vector has some wrong

I use the data method of vector in C++, but I have some problems, the code is in belows:

#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector (5);

  int* p = myvector.data();

  *p = 10;
  ++p;
  *p = 20;
  p[2] = 100;

  std::cout << "myvector contains:";
  for (unsigned i=0; i<myvector.size(); ++i)
    std::cout << ' ' << myvector[i];
  std::cout << '\n';

  return 0;
}

the result is myvector contains: 10 20 0 100 0, but why the result is not myvector contains: 10 20 100 0 0, the first one *p = 10; is 10, the second one ++p;*p = 20; is 20, that's all right, but the third one p[2] = 100; should be 100, but it is 0, why?

Deducing template return type based on operator?: result

Consider this code:

template <typename T1, typename T2>
auto max(T1 t1, T2 t2) -> decltype(true?t1:t2)
{
  return t2 < t1 ? t1 : t2;
}

When calling this function with ::max(5, 7.2) I'm expecting the returned type to be int as decltype(t1) is in this case int.

Why is the deduced return type double in the above code when using operator?: inside the decltype?

If I do -> decltype(t1) I get the expected return type int.

Set the request body while calling the API with C++Rest SDK

I'm want to call the Face API of Microsoft Computer Vision to post a picture with the C++Rest SDK. I have succeed with GET method but I don't know what to do with POST method. I have figure it out that the problem is in "request.set_body" method. I want to use it in two ways, one is posting a picture from my computer, another is posting a picture from a link of the website. If anyone knows about this problem, please help me. Thank you.

Here is the link of Face API: https://westcentralus.dev.cognitive.microsoft.com/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395236 And here is the code. In this code, I try to post a picture from a website:

{
    http_client client(U("https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect"));

    http_request request(methods::POST);
    request.headers().set_content_type(L"application/json");

    uri_builder builder;
    // Append the query parameters: [?returnFaceId][&returnFaceLandmarks]
    builder.append_query(U("returnFaceId"), U("true"));
    builder.append_query(U("returnFaceLandmarks"), U("false"));
    builder.append_query(U("subscription-key"), U("*********************"));

    web::json::value requestParameters;
    requestParameters[U("bar")] = web::json::value::object(U("https://cdn.explus.vn/media.phunutoday.vn/files/upload_images/2016/02/02/my-tam-cam-ngan-mo-5-phunutoday_vn.jpg"));

    utility::stringstream_t paramStream;
    requestParameters.serialize(paramStream);

    request.set_body(paramStream.str());
    request.set_request_uri(builder.to_uri());

    auto path_query_fragment = builder.to_string();

    // Make an HTTP GET request and asynchronously process the response
    return client.request(request).then([](http_response response)

how to covert string array to char**

I want to send the values manually here

void processArgs(int argc, char** argv);

if I sending like this

char* cwd[] = {"./comDaemon", "--loggg=pluginFramework:debug"};

parser->processArgs(2, cwd);

compiler showing warning as

warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]

 char* cwd[] = {"./comDaemon", "--loggg=pluginFramework:debug"};

How to run google Test from command line with --std=c++11 flag enabled

I installed gtest development package in ubuntu as follow:

  sudo apt-get install libgtest-dev
  sudo apt-get install cmake # install cmake
  cd /usr/src/gtest
  sudo cmake CMakeLists.txt
  sudo make
  # copy or symlink libgtest.a and libgtest_main.a to your /usr/lib folder
  sudo cp *.a /usr/lib

In order to compile and run the tests:

ubuntu@XPS:/hm/an/folder$ cmake CMakeLists.txt
-- The C compiler identification is GNU 5.5.0
-- The CXX compiler identification is GNU 5.5.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Found GTest: /usr/lib/libgtest.a  
-- Looking for pthread.h
-- Looking for pthread.h - found
-- Looking for pthread_create
-- Looking for pthread_create - not found
-- Looking for pthread_create in pthreads
-- Looking for pthread_create in pthreads - not found
-- Looking for pthread_create in pthread
-- Looking for pthread_create in pthread - found
-- Found Threads: TRUE  
-- Configuring done
-- Generating done
-- Build files have been written to: /hm/an/folder/

After which I run make

Scanning dependencies of target runTests
[ 50%] Building CXX object CMakeFiles/runTests.dir/test.cpp.o
In file included from /hm/an/folder/test.cpp:1:0:
/hm/an/folder/myfunc.cpp: In function ‘std::__cxx11::string test(std::__cxx11::string)’:

The content of my CMakeLists.txt:

cmake_minimum_required(VERSION 3.5.1)

# Locate GTest
find_package(GTest REQUIRED)
include_directories(${GTEST_INCLUDE_DIRS})

# Link runTests with what we want to test and the GTest and pthread library
add_executable(runTests test.cpp)
target_link_libraries(runTests ${GTEST_LIBRARIES}  pthread)

I understood that the problem that, while compiling the compiler isn't able to recognize the std::string. Could anyone help me to fix the issue? So it's looking for --std=c++17 flag!

I can run my program on the command line using: g++ --std=c++17 myfunc.cpp -o main, but not my test case which I have written using gtest. Any suggestions on what I am doing wrong?

Function not declare in the scope c++ error [duplicate]

This question already has an answer here:

I have a code block which throw error.

Here it is

#include <iostream>
#include <string>
using namespace std;
int main()
{
    int x = 0;
    mysterious (x, x);//getting error in this line
    cout << x << endl;
    return 0;  
}
void mysterious(int i, int &k) {
     i = 1;
     k = 2;
} 

error: In function 'int main()': error: 'mysterious' was not declared in this scope

What is the reason behind this error. Is there any syntactical flaw?

Are there algorithms are or patterns that can be applied to polymorphic class - methods?

Historically, I've been using trait classes to hold information and apply that into a "generic" function that runs the same "algorithm." Only differed by the trait class. For example: https://onlinegdb.com/ryUo7WRmN

enum selector { SELECTOR1, SELECTOR2, SELECTOR3, };

// declaration
template < selector T> struct example_trait;

template<> struct example_trait<SELECTOR1> {  
static constexpr size_t member_var = 3;  
static size_t do_something() { return 0; }
};

template<> struct example_trait<SELECTOR2> {  
static constexpr size_t member_var = 5; 
static size_t do_something() { return 0; }  
};


// pretend this is doing something useful but common
template < selector T, typename TT = example_trait<T> > 
void function() { 
std::cout << TT::member_var << std::endl; 
std::cout << TT::do_something() << std::endl;
}

int main()
{
    function<SELECTOR1>();
    function<SELECTOR2>();
    return 0;
}

I'm not sure how to create "generic" algorithms this when dealing with polymorphic classes.

For example: https://onlinegdb.com/S1hFLGC7V

Below I have created an inherited class hierarchy. In this example I have a base catch-all example that defaults all the parameters to something (0 in this case). And then each derived class sets overrides specific methods.

#include <iostream>
#include <memory>
#include <type_traits>
#include <assert.h>    

using namespace std;

struct Base {
 virtual int get_thing_one() {
     return 0;
    }

 virtual int get_thing_two() {
     return 0;
    }

 virtual int get_thing_three() {
     return 0;
    }

 virtual int get_thing_four() {
     return 0;
    }    
};

struct A : public Base {
    virtual int get_thing_one() override {
     return 1;
    }

  virtual int get_thing_three() override {
     return 3;
 }  
};

struct B : public Base {
    virtual int get_thing_one() override {
     return 2;
    }    

    virtual int get_thing_four() override{
     return 4;
 }    
};

Here I created a simple factory, not elegant but for illustrative purposes

// example simple factory
std::shared_ptr<Base> get_class(const int input) {
    switch(input)
    {
        case 0:
            return std::shared_ptr<Base>(std::make_shared<A>());
        break;

        case 1:
            return std::shared_ptr<Base>(std::make_shared<B>());
        break;

        default:
            assert(false);
        break;
    }
}

So this is the class of interest. It is a class does "something" with the data from the classes above. The methods below are a simple addition example but imagine a more complicated algorithm that is very similar for every method.

// class that uses the shared_ptr
class setter {
    private:

    std::shared_ptr<Base> l_ptr;

    public:

    setter(const std::shared_ptr<Base>& input):l_ptr(input)
    {}

    int get_thing_a()
    {
        return l_ptr->get_thing_one() +  l_ptr->get_thing_two();
    }

    int get_thing_b()
    {
        return l_ptr->get_thing_three() +  l_ptr->get_thing_four();
    }
};

int main()
{
    constexpr int select = 0;
    std::shared_ptr<Base> example = get_class(select);
    setter l_setter(example);

    std::cout << l_setter.get_thing_a() << std::endl;
    std::cout << l_setter.get_thing_b() << std::endl;

    return 0;
}

How can I make the "boilerplate" inside the setter class more generic? I can't use traits as I did in the example above because I can't tie static functions with an object. So is there a way to make the boilerplate example more common?

netCDF basic troubleshooting on C++11

So I'm trying to use netCDF along with C++. The installation is correct (I know since I'm running on a cluster and I know it works for other people there). Yet not even the example codes from the netCDF webpage are working...

I am using g++ -std=c++11 to compile. Whenever I try to compile one of the several example codes I have for using netCDF I get a bunch of errors, and I have no idea what's going on...

#include <vector>
#include <netcdf>
using namespace netCDF;
int main() {
  int nx = 6, ny = 12;
  int dataOut[nx][ny];
  for(int i = 0; i < nx; i++)
    for(int j = 0; j < ny; j++)
    dataOut[i][j] = i * ny + j;
  // Create the netCDF file.
  NcFile dataFile("1st.netCDF.nc",NcFile::replace);
  // Create the two dimensions.
  NcDim xDim = dataFile.addDim("x",nx);
  NcDim yDim = dataFile.addDim("y",ny);
  std::vector<NcDim> dims(2);
  dims[0] = xDim;
  dims[1] = yDim;
  // Create the data variable.
  NcVar data =  dataFile.addVar("data", ncInt, dims);
  // Put the data in the file.
  data.putVar(&dataOut);
  // Add an attribute.
  dataFile.putAtt("Creation date:",
  "12 Dec 2014");
  return 0;
}

The expected result is a correct compilation of the code, and once it's run to get a .nc file with the dataOut recorded into it. This is my actual output when I try to compile:

/tmp/ccyuchst.o: In function main': rarray_2_netcdf.cc:(.text+0x1c6): undefined reference tonetCDF::NcFile::NcFile(std::__cxx11::basic_string, std::allocator > const&, netCDF::NcFile::FileMode)' rarray_2_netcdf.cc:(.text+0x234): undefined reference to netCDF::NcGroup::addDim(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, unsigned long) const' rarray_2_netcdf.cc:(.text+0x2a2): undefined reference tonetCDF::NcGroup::addDim(std::__cxx11::basic_string, std::allocator > const&, unsigned long) const' rarray_2_netcdf.cc:(.text+0x322): undefined reference to netCDF::NcDim::operator=(netCDF::NcDim const&)' rarray_2_netcdf.cc:(.text+0x34b): undefined reference tonetCDF::NcDim::operator=(netCDF::NcDim const&)' rarray_2_netcdf.cc:(.text+0x399): undefined reference to netCDF::ncInt' rarray_2_netcdf.cc:(.text+0x3a1): undefined reference tonetCDF::NcGroup::addVar(std::__cxx11::basic_string, std::allocator > const&, netCDF::NcType const&, std::vector > const&) const' rarray_2_netcdf.cc:(.text+0x3d5): undefined reference to netCDF::NcVar::putVar(void const*) const' rarray_2_netcdf.cc:(.text+0x441): undefined reference tonetCDF::NcGroup::putAtt(std::__cxx11::basic_string, std::allocator > const&, std::__cxx11::basic_string, std::allocator > const&) const' rarray_2_netcdf.cc:(.text+0x4d6): undefined reference to netCDF::NcFile::~NcFile()' rarray_2_netcdf.cc:(.text+0x63e): undefined reference tonetCDF::NcFile::~NcFile()' /tmp/ccyuchst.o: In function void std::_Construct<netCDF::NcDim>(netCDF::NcDim*)': rarray_2_netcdf.cc:(.text._ZSt10_ConstructIN6netCDF5NcDimEJEEvPT_DpOT0_[_ZSt10_ConstructIN6netCDF5NcDimEJEEvPT_DpOT0_]+0x2e): undefined reference tonetCDF::NcDim::NcDim()' /tmp/ccyuchst.o: In function netCDF::NcGroupAtt::~NcGroupAtt()': rarray_2_netcdf.cc:(.text._ZN6netCDF10NcGroupAttD2Ev[_ZN6netCDF10NcGroupAttD5Ev]+0x20): undefined reference tonetCDF::NcAtt::~NcAtt()' collect2: error: ld returned 1 exit status

Exception specification in ˋtypedefˋ completely forbidden or only at toplevel?

In C++14 Sec 15.4;2 it is stated, that ... An exception-specification shall not appear in a typedef declaration or alias-declaration.

That mean following is forbidden:

typedef void (*fn)(int) noexcept;

But does the the wording shall not appear mean the token ˋnoexceptˋ cannot appear anywhere in a typedef declaration?

For instance are these both are forbidden as well?

typedef void (*fn1)(void (*)(int) noexcept);
typedef decltype(std::declval<void (*)(int)noexcept>()) fn2;

These both try to define a type ˋfn1ˋ and ˋfn2ˋ being able to point to a function that takes a pointer to a function taking an ˋintˋ and returning nothing while promising to never throw an exception.

So in my examples the exception-specification is not applied to the toplevel type ˋfn1ˋ resp. ˋfn2ˋ that are introduced by ˋtypedefˋ but to the parameters these function may receive.

So should I take 15.4;2 verbatim and therefore my both examples are invalid? Or is only application to a type-definition forbidden and my examples are correct?

C++ bad_alloc exception on future.get

My C++ program is exiting with a bad_alloc exception. I'm trying to find the cause, but don't quite know how to debug these kind of exceptions.

So far, I compiled the program in debug mode, run it with gdb and set a breakpoint before throwing the exception (b 'std::bad_alloc::bad_alloc()').

After the exception was thrown, I inspected the stack (bt), which showed the following:

(gdb) bt
#0  0x00007ffff752f1f7 in raise () from /lib64/libc.so.6
#1  0x00007ffff75308e8 in abort () from /lib64/libc.so.6
#2  0x00007ffff7f0a7fd in __gnu_cxx::__verbose_terminate_handler () at ../../../../libstdc++-v3/libsupc++/vterminate.cc:95
#3  0x00007ffff7f08876 in __cxxabiv1::__terminate (handler=<optimized out>) at ../../../../libstdc++-v3/libsupc++/eh_terminate.cc:47
#4  0x00007ffff7f088c1 in std::terminate () at ../../../../libstdc++-v3/libsupc++/eh_terminate.cc:57
#5  0x00007ffff7f0886a in std::rethrow_exception (ep=...) at ../../../../libstdc++-v3/libsupc++/eh_ptr.cc:259
#6  0x0000000000419001 in std::__basic_future<void>::_M_get_result (this=0x55b9a0)
    at /soft/EB_repo/devel/programs/foss/2016b/GCCcore/5.4.0/include/c++/5.4.0/future:683
#7  0x0000000000416da6 in std::future<void>::get (this=0x55b9a0) at /soft/EB_repo/devel/programs/foss/2016b/GCCcore/5.4.0/include/c++/5.4.0/future:846
#8  0x00000000004d152f in cluster_reads (reads=..., kmer_size=14, t_s=0.10000000000000001, t_v=500, bv_threshold=0.40000000000000002, 
    min_bv_threshold=0.20000000000000001, bv_falloff=0.050000000000000003, min_reads_cluster=0, n_threads=8) at cluster.cpp:81
#9  0x000000000040910b in main (argc=8, argv=0x7fffffffc028) at main.cpp:106

As you can see in #7, the exception is being thrown when getting the std::future? Here is the piece of code from cluster_reads (#8) that is crashing (I marked line 81 with an arrow).

    std::vector<std::vector<kmer_t>> kmers(reads.size());
    std::vector<std::vector<kmer_t>> rev_kmers(reads.size());

    std::vector<kmer_bv_t> bv_kmers(reads.size());
    std::vector<kmer_bv_t> rev_bv_kmers(reads.size());

    std::vector<std::future<void>> tasks;
    for (int t = 0; t < n_threads; ++t) {
        tasks.emplace_back(std::async(std::launch::async, [t, &reads, n_threads, kmer_size, &kmers, &rev_kmers, &bv_kmers, &rev_bv_kmers] {
            for (int i = t; i < reads.size(); i+=n_threads) {
                read_kmers_t k1 = extract_kmers_from_read(reads[i].seq, kmer_size);

                kmers[i] = k1.list_forward;
                rev_kmers[i] = k1.list_reverse;
                bv_kmers[i] = k1.bv_forward;
                rev_bv_kmers[i] = k1.bv_reverse;
            }
        }));
    }

    for (auto &&task : tasks) {
        task.get(); <------------------- line 81
    }

How can I debug further this issue? I'm pretty new to gdb. Any idea on what might be causing the bad_alloc exception?

run time error in dynamically allocated array to delete an element in c++

I have written a program in c++ to delete an element in a dynamically allocated array, i can see the array with the deleted element but after that it giving some error which i can't understand please help. i have included the images to the error as i wasn't able to copy the error message using debian 9, 32 bit //if that helps. compiler clang. ide code::blocks.

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

int main()
{
    int *ar,arsize,lp1,lp2,lp3,lp4,ele,pos;
    ar=nullptr;
    cout<<"enter the size of array to be created:- "; cin>>arsize;
    ar=new int[arsize];
    if(!ar)
    {
        cout<<"Aborting";
        exit(1);
    }
    else
    {
    cout<<"enter the elements for array:- ";
    for(lp1=0;lp1<arsize;lp1++)
    {
        cin>>ar[lp1];
    }
    cout<<"Enter element to be deleted:- "; cin>>ele;
    for(lp2=0;lp2<arsize;lp2++)
    {
        if(ar[lp2]==ele)
        {
            ar[lp2]=0;
            pos=lp2;
            break;
        }
    }
    for(lp3=pos;lp3<arsize;lp3++)
    {
        ar[lp3]=ar[lp3+1];
    }
    ar[arsize]=0;
    cout<<"new array is:-"<<endl;
    for(lp4=0;lp4<arsize-1;lp4++)
    {
        cout<<"\t"<<ar[lp4]<<endl;
    }
    delete[]ar;
    return 0;
    }
}

Error thrown is:

code error 1 code error 2

Function argument as __builtin_constant_p?

Is it possible to have a function argument which is __builtin_constant_p?

This macro works fine:

#define FOO(a) {\
    static_assert(__builtin_constant_p(a));\
}

void bar() {
    FOO("abc");
}

I would like to turn FOO into a function. However, this doesn't work:

void foo(const char* a) { // how to change argument to make this work?
    static_assert(__builtin_constant_p(a)); // Fails with: Static_assert failed due to requirement '__builtin_constant_p(a)
}

void bar() {
    foo("abc");
}

How can I change the argument of foo to make it work? Possibly using templates / std::forward or something similar?

Does std::string move constructor actually move?

So here i got a small test program:

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

class Test
{
public:
  Test(const std::vector<int>& a_, const std::string& b_)
    : a(std::move(a_)),
      b(std::move(b_)),
      vBufAddr(reinterpret_cast<long long>(a.data())),
      sBufAddr(reinterpret_cast<long long>(b.data()))
  {}

  Test(Test&& mv)
    : a(std::move(mv.a)),
      b(std::move(mv.b)),
      vBufAddr(reinterpret_cast<long long>(a.data())),
      sBufAddr(reinterpret_cast<long long>(b.data()))
  {}

  bool operator==(const Test& cmp)
  {
    if (vBufAddr != cmp.vBufAddr) {
      std::cout << "Vector buffers differ: " << std::endl
        << "Ours: " << std::hex << vBufAddr << std::endl
        << "Theirs: " << cmp.vBufAddr << std::endl;
      return false;
    }

    if (sBufAddr != cmp.sBufAddr) {
      std::cout << "String buffers differ: " << std::endl
        << "Ours: " << std::hex << sBufAddr << std::endl
        << "Theirs: " << cmp.sBufAddr << std::endl;
      return false;
    }
  }

private:

  std::vector<int> a;
  std::string b;
  long long vBufAddr;
  long long sBufAddr;
};

int main()
{
  Test obj1 { {0x01, 0x02, 0x03, 0x04}, {0x01, 0x02, 0x03, 0x04}};
  Test obj2(std::move(obj1));

  obj1 == obj2;


  return 0;
}

Software i used for test:

Compiler: gcc 7.3.0

Compiler flags: -std=c++11

OS: Linux Mint 19 (tara) with upstream release Ubuntu 18.04 LTS (bionic)

The results i see here, that after move, vector buffer still has the same address, but string buffer doesn't. So it looks to me, that it allocated fresh one, instead of just swapping buffer pointers. What causes such behavior?

assign std::unique_ptr to std::function

There is a custom defined map, with an element std::function()>. The lambda code is working, but I don't know how to expand it to a normal formation. The code is following.

class TestA{
public:
    TestA() {}
    ~TestA() {}

    TestA(const TestA &) {}

    static void print()
    {
        cout << __FUNCTION__ << endl;
        return;
    }
};

void testComplexMap1()
{

    typedef map<string, std::function<std::unique_ptr<TestA>()>> TempMap;
    TempMap m;
    // the lambda format code, it works
    //m.insert({ "TestA", []() {return std::unique_ptr<TestA>(new TestA());}});

    // I want to expand it, but failed.
    TestA *t = new TestA();
    //function<unique_ptr<TestA>()> fp(unique_ptr<TestA>(t));
    function<unique_ptr<TestA>()> fp(unique_ptr<TestA>(t)()); //warning here
    //m.emplace("TestA", fp);              // compile error here
}

Any help will be greatly appreciated.

How is this shared_ptr automatically converted to a raw pointer?

I'm studying enable_shared_from_this of C++11 now; one example made me confused: how the shared_ptr type returned by shared_from_this() can convert to this raw pointer?

#include <iostream>
#include <memory>
#include <functional>

struct Bar {
    Bar(int a) : a(a) {}
    int a;
};

struct Foo : public std::enable_shared_from_this<Foo> {
    Foo() { std::cout << "Foo::Foo\n"; }
    ~Foo() { std::cout << "Foo::~Foo\n"; }

    std::shared_ptr<Bar> getBar(int a)
    {
        std::shared_ptr<Bar> pb(
            new Bar{a}, std::bind(&Foo::showInfo, shared_from_this(), std::placeholders::_1)
        );
        return pb;
    }

    void showInfo(Bar *pb)
    {
        std::cout << "Foo::showInfo()\n";
        delete pb;
    }

};

int main()
{
    std::shared_ptr<Foo> pf(new Foo);
    std::shared_ptr<Bar> pb = pf->getBar(10);
    std::cout << "pf use_count: " << pf.use_count() << std::endl;
}

friend function defined inside a template class

A friend function named test() is defined inside a template class A:

template <typename T> class A {
public:
    friend void cs() {/* code */}
}

Another class inherits from template class A:

class B : public A<B> {}

In main function, I failed to call cs(), the compiler can not see its declaration if I don't provide a function declaration in the global scope:

int main(){
    cs()
}

But things are different when cs takes its template class T as a argument:

template <typename T> class A{
public:
    void cs(const T& t) {}
}

Now cs() can be successfully called in the main function without any decalration:

int main(){
    B b;
    cs(b);
}

If a function takes a user-defined class as its argument, I know the compiler would search the scope of the user-defined class. So which scope exactly is cs() defined? How it is possible that cs() is successfully called in the second case?

How to correct this code to avoid old-style-cast warnings with C++

I'm new to c++ and I'm trying to avoid old-style-cast warning in a piece of code during compilation. The code is a part of an old opensource code. Here is the code itself:

#define ROUND_TO_BYTE(X)      ((BYTE)((X)+0.499))
#define ROUNDS(X)             ((short)((X)+0.499))
#define TRUNC(X)              ((short) (X))

#define CONVERT_DOUBLE_TO_FLOAT(val) \
  ( (val) >= SMALLFLOAT \
    ? ( (val) < LARGEFLOAT \
        ? (float)(val) \
        : (float)LARGEFLOAT \
      ) \
    : ( (val) <= -SMALLFLOAT  \
        ? ( (val) > -LARGEFLOAT \
            ? (float)(val) \
            : (float)-LARGEFLOAT \
          ) \
        : (float)0.0 \
      ) \
  )

I have tried as follow and the code does compile without any warning:

#define ROUND_TO_BYTE(X)      (static_cast<BYTE>((X)+0.499))
#define ROUNDS(X)             (static_cast<short>((X)+0.499))
#define TRUNC(X)              (static_cast<short>(X))


#define CONVERT_DOUBLE_TO_FLOAT(val) \
  ( (val) >= SMALLFLOAT \
    ? ( (val) < LARGEFLOAT \
        ? static_cast<float>(val) \
        : static_cast<float>(LARGEFLOAT) \
      ) \
    : ( (val) <= -SMALLFLOAT  \
        ? ( (val) > -LARGEFLOAT \
            ? static_cast<float>(val) \
            : static_cast<float>(-LARGEFLOAT) \
          ) \
        : static_cast<float>(0.0) \
      ) \
  )

However I'm not sure if I get the following lines right:

#define TRUNC(X)              ((short) (X))

to

#define TRUNC(X)              (static_cast<short>(X))

and

        ? (float)(val) \

to

        ? static_cast<float>(val) \

I don't understand why using (float)(val) instead of (float)val and whether I need to change the code to:

#define TRUNC(X)              (static_cast<short>((X)))
? static_cast<float>((val)) \

Question on atomic spin lock and std::this_thread::yield()

I've been trying to implement C++ a thread pool with STL that takes in tasks in queues and dispatch the tasks to the threads for execution. The queue uses a atomic spin-lock when pushing and popping, and everything seemed to work well with the following code:

void push(const std::function<bool()>& func){
    while(in_use.exchange(true, std::memory_order_acquire));
    //Actually push the queue, deal with possible exceptions, etc.
    in_use.store(false, std::memory_order_release);
}

std::function<bool()> pop(){
    while(in_use.exchange(true, std::memory_order_acquire));
    //Actually push the queue, deal with possible exceptions, etc.
    in_use.store(false, std::memory_order_release);
}
.....//other functions for determining size, etc.

Later I decided that std::this_thread::yield may be a good choice in the loop.

(I tanked my PC when I was testing with a task that pushes the same task into the pool, and then polls the pool, when I set the process execution priority to Real-time...)

However, when I changed the line

while(in_use.exchange(true, std::memory_order_acquire));

to

while(in_use.exchange(true, std::memory_order_acquire)) std::this_thread::yield();

Under the same condition (task being pushing a same task to pool, with more tasks than threads in the pool.) with no other modification, all of the threads that pushes into the pool's master queue got blocked in deadlock, all waiting for variable to be released after running a few minutes.

I was wondering what exactly the yield function can do to a atomic variable operation that could lead to this problem.

PS: CPU hardware: Intel Core i5, OS Windows 10 1803, VS 2017 SDK version 10.0.17763.0.

lundi 28 janvier 2019

Error: expression cannot be used as an function

I'm new to lambdas, I made my own binary heap class with custom comparator function. It went well until I got a compilation error and I don't know how to fix.

I tried to change my line of code a bit, instead of

this(capacity, [](int a, int b){return a - b;});

I changed to this:

function<int(int, int)> cmp = [](int a, int b){return a - b;};
this(capacity, cmp);

I got the same result. How to deal with this error?

binary heap class:

class binaryheap
{
private:
    int *heap;
    int size;
    int capacity;
    function<int(int, int)> cmp;
    int parent(int i);
    int left_child(int i);
    int right_child(int i);
    void swap(int *a, int *b);
    void heapify(int i);
public:
    binaryheap(int capacity);
    binaryheap(int capacity, const function<int(int, int)>& cmp);
    ~binaryheap();
    bool empty();
    int heap_size() const;
    int get_root() const;
    int extract_root();
    void decrease_key(int i, int value);
    void insert_key(int key);
    void delete_key(int i);
};

The part of my code with a compilation error

binaryheap::binaryheap(int capacity)
{
    this(capacity, [](int a, int b){return a - b;});//binaryheap.cpp:51:58: error: expression cannot be used as a function
}

binaryheap::binaryheap(int capacity, const function<int(int, int)>& cmp)
{
    this->capacity = capacity;
    this->heap = new int[capacity + 1];
    this->size = 0;
    this->cmp = cmp;
}

passing SDL windows by reference/address

I have recently started trying to learn SDL. I've been following tutorials so far on how to make SDL projects, i wanted to set up the structure for one myself and i didn't want to use global variables for the SDL_Window and SDL_Renderer and any textures. So i declared the window, renderer and texture at the top of main() and passed them to my init() function:

   bool init(SDL_Window* &window, SDL_Renderer* &renderer, const int height, const int width)
{
    if (SDL_Init(SDL_INIT_VIDEO) < 0)
    {
        std::cout << "SDL_Init() failed SDL error: " << SDL_GetError() << '\n';
        return false;
    }
    else
    {
        window = SDL_CreateWindow("SDL Window", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, 0);
        if (window == NULL)
        {
            std::cout << "SDL_CreateWindow() failed SDL error: " << SDL_GetError() << '\n';
            return false;
        }
        else
        {
            renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
            if (renderer == NULL)
            {
                std::cout << "SDL_CreateRenderer() failed SDL error: " << SDL_GetError() << '\n';
            }
        }
    }

    return true;

}

the caller in main():

if (!init(window, renderer, WINDOW_HEIGHT, WINDOW_WIDTH))
{
    std::cout << "init() failed SDL error: " << SDL_GetError() << '\n';
}

declarations at the top of main():

    SDL_Texture* texture{};
    SDL_Window* window{};
    SDL_Renderer* renderer{};
    int WINDOW_HEIGHT = 480;
    int WINDOW_WIDTH = 640;

as you can see in my init() function, it takes the window and renderer as arguments and puts them into one of these: SDL_Window* &window; initially i tried putting them in : SDL_Window* window; however this would result in the renderer and window being null when the program returned to main(). I don't understand why my initial method did not work but using SDL_Window* &window; does work

As far as i understand window is a pointer (a variable which holds an address) to a SDL struct called SDL_Window and therefore when i pass window to parameter SDL_Window* window, it should give the parameter the address to my window i declared in main() and therefore any changes made to the window in init() should also be made to it in main(), however this was not true and SDL_Window* &window as parameter ended up having the desired effect.

If possible could someone explain why this is.

thank you

Can class member be initialized with another class member in the initializer list?

Suppose I have class with two members,

class App
{
public:
   App() : window(1366, 768, "Title"), drawer(w) {}
private:
   Window window;
   Drawer drawer;
}

and the Drawer class has constructor Drawer(const Window&).
Is it valid to initialize the App class member Drawer with the another class member Window, like in this example?

Sorting or printing of set of objects is incorrect

I truly don't know whether my sorting or my printing of a set of obejcts is wrong but when I print the whole set, the result is unsorted AND it contains one duplicate. The object Person has a surname, a familyname and year of birth (all 3 are strings). I first sort by year of birth, then by familyname and then by surname. Per se, there are no identical persons (but even if was the case, it should be eliminated as they get inserted into the set ).

To be more concrete, I create a set of persons like this:

std::set <Person> greatUncles; 

and insert them like this:

greatUncles.insert(Person("bla", "bla", "1900"));

Here's are the essential things from class Person:

class Person {
public:
  ...

  Person(std::string s, std::string f, std::string y)
    :surname(s), familyname(f), yearOfBirth(y)
  {
  }

  ...

  std::string getSurname() const {
    return surname;
  }

  std::string getFamilyname() const {
    return familyname;
  }

  std::string getYearOfBirth() const {
    return yearOfBirth;
  }

private:
  std::string surname;
  std::string familyname;
  std::string yearOfBirth;
};

//to print the set, overload the '<<' operator
std::ostream &operator<<(std::ostream &o, const Person &person) {
  o << person.getSurname() << " "
    << person.getFamilyname() << " "
    << person.getYearOfBirth() << std::endl;
  return o;
}

//to order the set, overload the '<' operator
bool operator< (Person const &p1, Person const &p2) {
  int compareYearOfBirth = p1.getYearOfBirth().compare(p2.getYearOfBirth());

  if (compareYearOfBirth == 0) {
    int compareFamilyname = p1.getFamilyname().compare(p2.getFamilyname());
    if (compareFamilyname == 0) {
      return p1.getSurname().compare(p2.getSurname());
    } else
      return compareFamilyname;
  } else
    return compareYearOfBirth;
}

and here is how I print the set of great-uncles:

void printGreatUncles(std::set <Person> &greatUncles) {
    std::ofstream outputFile;
    outputFile.open("greatuncle.dat");

    if (outputFile.is_open()) {
      for(Person const & person:greatUncles) {
        outputFile << person;
      }
      outputFile.close();
    }
  }

Now the output in a certain case should look like this (sorted by year):

Sebastian Furtweger 1942
Nikolaus Furtweger 1951
Archibald Furtweger 1967

but it looks like this:

Archibald Furtweger 1967
Sebastian Furtweger 1942
Nikolaus Furtweger 1951
Archibald Furtweger 1967

I can't figure it for my life what (things) I'm doing wrong.

C++ Operator<< Overloading to Print Member Variable Values

All -- I have checked existing discussion topics and/or questions on this, and none seems to address this. Hence posting this question. Happy to be referred to an existing link that might already be addressing this exact issue, if I overlooked it.

Below is my snippet of code:

class MyBook{
  public:
    MyBook(): bidPrices(10, 0.0),
              askPrices(10, 0.0),
              bidSizes(10, 0),
              askSizes(10, 0) {}
    std::vector<double> bidPrices;
    std::vector<double> askPrices;
    std::vector<int> bidSizes;
    std::vector<int> askSizes;
};

// Forward declaration
std::unordered_map<std::string, std::unique_ptr<MyBook>> myBookMap;

// Overload << to print.

std::ostream&* operator<<(std::ostream& os, MyBook& mbk)
{
  os << "bid price: " << mbk.bidPrices[0] <<  " "
     << "bid size: " << mbk.bidSizes[0] <<  " "
     << "ask price: " << mbk.askPrices[0] <<  " "
     << "ask size: " << mbk.askSizes[0] << endl;
  return os;
}

Later inside main():

std::unordered_map<std::string, std::unique_ptr<MyBook>>::iterator it = myBookMap.begin();
while (it != myBookMap.end())
{
  std::cout << it->first;
  std::cout << it->second;
}

At compile time, I see "error: no match for 'operator<<'" error.

It possibly couldn't be because of the differing data types between sizes and prices, and even if it is that, I don't see how I can use a template for that when I am passing in the object (mbk) as opposed to a vector (int vector vs. double vector) as the argument to the operator<< overloading function.

Thanks for any insights. Happy to be crucified, although I'm still a newbie.

Best wishes.

Can anyone tell me whats wrong with my code?

I'm new to programming and to c++. If this sounds stupid then you know why. I'm having problems with my code. For some reason, not all strings with 4 letters don't go to my array when I made a function to make that happen. Plus, strings with 6 letters also go to my array that are only supposed to store in 4 or anything that the user wants to put.

I've tried a lot that I can't even list them down.

#include <iostream>
#include <string>
#include <windows.h>

using namespace std;

int main()
{
    string LetterInput, LetterLoad, input;
    string Words[] = {"camera","lotion","fire","eggs","roll"};
    string PossibleAnswers[] = {};
    int Number;
    int Size;
    bool YesorNo = false;

cout << "Lets play HANGMAN! " << endl;
Sleep(500);

cout << "Think of a word and type in the number" << endl;
cout << "of letters there are" << endl;
cin >> Size;

for (int i = 1; i <= Size; i++){
    LetterLoad += "_";
}

for (int i = 0; i <= sizeof(Words)/sizeof(string); i++){
    if (Size == Words[i].size()){
        PossibleAnswers[i] = Words[i];
    }
}

cout << PossibleAnswers[0] << endl;
cout << PossibleAnswers[1] << endl;

My expected results are for the array to only show "fire","eggs","rolls" in that order. But the actual results are, "camera","lotion","fire","eggs". Lol what is the problem.

A variadic function that accepts Strings and Ints, Format the latter and concatenate all?

I'm trying to use the answer from DanielKO in this question for my needs but i'm not familiar with templates and variadic functions, and i don't get what should i do.

What i'd need is a variadic c++(11) function which i can call like this:

 String NewMsg = CreateMessage("SET",16,1,17,0,"RED",47);

and have NewMsg= "SET,0010,0001,0011,0000,RED,002F".

I'm not even able to get where should i add the comma between the arguments. And then: How could i distinguish between integers and string while parsing the args, so to format each integer to hexadecimal strings?

how enable to enable diffrent output directory with diffrent envirement build settings in vscode?

I have a cmake program that run on both x86 and arm, so i need two build configurations and two output build directories.

how is it possible to add different build directory and settings?

Using range-based for loop with CGAL types

Consider a CGAL::Arrangement_2. Right now, I have to iterate through it like this:

using MyArrangement = CGAL::Arrangement_2<MyTraits, MyDcel>;
for(MyArrangement::Face_handle face = map.faces_begin(); face != map.faces_end(); ++face)
{
    do_stuff(face);
}

If I try to migrate this to using a C++11-style range-based for loop like this:

for(auto face : gMap)
{
    do_stuff(face)
}

I get the following error (emphasis mine):

Error:(1385, 13) invalid range expression of type 'CGAL::Arrangement_2 > >, true>, std::__1::vector > >, true> >, std::__1::allocator > >, true> > > >, CGAL::Arr_consolidated_curve_data_traits_2 > >, true> >, int> >, CGAL::Arr_extended_dcel > >, true>, std::__1::vector > >, true> >, std::__1::allocator > >, true> > > >, CGAL::Arr_consolidated_curve_data_traits_2 > >, true> >, int> >, GIS_vertex_data, GIS_halfedge_data, GIS_face_data, CGAL::Arr_vertex_base > >, true> > >, CGAL::Gps_halfedge_base > >, true> >, CGAL::_Unique_list > >, CGAL::Gps_face_base> >'; no viable 'begin' function available

The error is the same if I change the for loop to use auto &face or const auto &face.

Does anyone have a workaround for this, or some nice wrapper to make it work? I'm trying to avoid having to resort to using this monstrosity with a lambda argument:

template<typename F>
void for_each_face(MyArrangement &map, F callback)
{
    for(MyArrangement::Face_handle f = map.faces_begin(); f != map.faces_end(); ++f) 
    {
        callback(f); 
    }
}