samedi 31 août 2019

c++ map internal implementation source [on hold]

I need to know how the map implemented in c++. And also I need to understand the source code of map in c++.

Please, anyone, write an internal implementation of the map in c++ and explain it.

Unexpected function behavior

I have the following function. It just multiplies some powers of primes:

int solve(int n){
    long long solution = 1;

    for (int i=2; i<=n; i++){
        if (primes[i]){
            //std::cout << "p" << i << " : " << std::pow(i, find_last_power(n, i)) << std::endl;
            solution *= std::pow(i, find_last_power(n, i));
        }
    }
    return solution;
}

  • primes is an array of n+1 booleans whose value primes[i] is true if i is prime and false if i is composite.
  • find_last_power(n, p) returns the exponent (int) of the largest power of p that is less than or equal to n.

If you uncomment the debug line and run solve(20) it writes out:

p2 : 16
p3 : 9
p5 : 5
p7 : 7
p11 : 11
p13 : 13
p17 : 17
p19 : 19
232792237 // this is the return value of solve(20)
          // it is supposed to be the product of the numbers on the right (16,9...)

But the returned number is a product of all numbers except 19. I find this bizzare since the debug line clearly shows that the program went over the multiplication line. Moreover, after running the program in a debugger (GDB) the program executes correctly.

If anyone wants the full code it's here. It's only about 40 lines. Any help is appreciated.

Data in `std::vector` different when using `std::unique_ptr`

I have written a custom class that stores images and eventually computes a calibration based on those images, but I am encountering an issue in the way that the images are stored. I have two overloaded functions that do this, with one reading the images from file using cv::imread, and the other using an intermediate Snapshot data structure for holding the data. The function using cv::imread works fine, but the one using the custom data structure does not. I am trying to store three images right now, and the issue is that as I push the images into a vector, the data for the second images is copied into the first one.

This is the working function:

bool CalibClass::AddImage(const std::string& snapshotPath) {
    cv::Mat img = cv::imread(snapshotPath);

    // _snapshots is a private member declared as a std::vector<cv::Mat>
    _snapshots.push_back(img);

    return true;
}

This is the function that is not working:

bool CalibClass::AddImage(const ImageSet& snapshot) {

    RGBImage *rgb_image_ptr = snapshot.GetRGBImage();

    std::vector<unsigned char> img_data(rgb_image_ptr->GetData());
    cv::Mat img(rgb_image_ptr->GetHeight(), rgb_image_ptr->GetWidth(), CV_8UC3, img_data.data());

    _snapshots.push_back(img);

    return true;
}

The ImageSet class stores images as an std::unique_ptr<RGBImage>. The RGBImage class stores the image data as a std::vector<unsigned char>.

This is how the images are loaded into the class from the main:

cv::Mat img1 = cv::imread("img1.png");
cv::Mat img2 = cv::imread("img2.png");      
cv::Mat img3 = cv::imread("img3.png");

int length = img1.total() * img1.elemSize();

std::vector<unsigned char> data1;
std::vector<unsigned char> data2;
std::vector<unsigned char> data3;
for (int i = 0; i < length; i++) {
    data1.push_back(img1.data[i]);
}

for (int i = 0; i < length; i++) {
    data2.push_back(img2.data[i]);
}

for (int i = 0; i < length; i++) {
    data3.push_back(img3.data[i]);
}


CalibClass calib_test;

std::unique_ptr<RGBImage> rgb_image_ptr1(new RGBImage(img1.rows, img1.cols, data1));
ImageSet new_snap1(rgb_image_ptr1, nullptr, 0);
calib_test.AddImage(new_snap1);


std::unique_ptr<RGBImage> rgb_image_ptr2(new RGBImage(img2.rows, img2.cols, data2));
ImageSet new_snap2(rgb_image_ptr2, nullptr, 0);
calib_test.AddImage(new_snap2);

std::unique_ptr<RGBImage> rgb_image_ptr3(new RGBImage(img3.rows, img3.cols, data3));
ImageSet new_snap3(rgb_image_ptr3, nullptr, 0);
calib_test.AddImage(new_snap3);

When I put a break point inside the function and check the content of the _snapshots, the first element is the second image, and the second and third elements are the third image. When I set a break point after all the AddImage() calls, the content of _snapshots has the second image as the first element, the third image as the second element, and the third element has a cv::Mat with invalid data.

What is the reason why the two methods are storing the images differently? What would be the way to fix this issue?

ThreadSanitizer detects a data race, where is the problem?

In this sample program, I'm trying to avoid using forward declaration and cyclic dependency exploiting a lambda function (called data_race)

struct B{
    int x;
    std::thread* tid;

    B(int _x){
        x = _x;
        tid = NULL;
    }

    ~B(){
        if(tid != NULL) delete tid;
    }

    void run(std::function<void(B*)> f){
        auto body = [&f, this](){
            f(this);
        };

        tid=new std::thread(body);
    }

    void wait(){
        tid->join();
    }
};

struct A{
    int x;
    std::mutex mtx;

    A(int _x){
        x = _x;
    }

    void foo(B* b){
        std::unique_lock<std::mutex> lock(mtx);
        x = b->x;
    };
};

int main(){
    A a(99);
    std::vector<B> v;

    auto data_race = [&a](B* b){ a.foo(b);};

    for(int i=0; i<10; i++){
        v.push_back(B(i));
    }

    for(int i=0; i<v.size(); i++){
        v[i].run(data_race);
    }

    for(int i=0; i<v.size(); i++){
        v[i].wait();
    }

    return 0;
}

However ThreadSanitizer detects a data race coming from the lambda function data_race. Can you help me understand why? The mutex inside A should be enough to avoid it.

Compile time calculation of constants fails, some const not yet initialized

I want to initialize a constant struct with using a function at compile time. All the inputs for this function are constants so it should theoretically be possible. but some const values used by the function are seemingly not yet initialized by the compiler, leading to an incorrect value.

timer_setup.c:

const int TIMER_PRESCALER_1_2    = 1;

timer_setup.h:

extern const int TIMER_PRESCALER_1_2;

(I don't see extern "C" in the header file of this library)

abstraction_layer.cpp

typedef struct
{
  uint16_t value;
  //const int *option;
  int option;
  uint64_t div_min;
  uint64_t div_max;//value*65536 but potentially higher with post divider
  uint8_t shift;
}
prescaler_t;

#define PRESCALER_DEF(p,s) {p,TIMER_PRESCALER_1_##p,p*1,65536ULL*p,s}

#if defined(_SAM3XA_)

static const prescaler_t prescalers[] = {
  PRESCALER_DEF(2,1),
  PRESCALER_DEF(8,3),
  PRESCALER_DEF(32,5),
  PRESCALER_DEF(128,7),
};

#else

static const prescaler_t prescalers[] = {
  PRESCALER_DEF(1,0),
  PRESCALER_DEF(8,3),
  PRESCALER_DEF(64,6),
  PRESCALER_DEF(256,8),
  PRESCALER_DEF(1024,10)
};
#endif

[...]

timer_divider_settings_t timer_divider_settings_calc(double frequency_hz,double period_s)
{
  int8_t index;
  uint64_t divider_min_1;
  uint64_t total_divider;
  timer_divider_settings_t settings;

  total_divider = total_divider_calc(frequency_hz,period_s);  

  index = prescaler_index_find(total_divider);

  settings.option = prescalers[index].option;
  settings.divider_min_1 = (total_divider >> prescalers[index].shift) -1;

  return settings;
}

static const timer_divider_settings_t BIT_PERIOD_S          = timer_divider_settings_calc(0,LN_BIT_PERIOD_S);

This constant is not correct.

I expect the value to be the same regardless whether it is calculated at compile time or run-time. I expect it to be the same regardless of the target platform.

The constant is incorrect if I compile it for Arduino Due target, the AVR boards do not have this issue. If I initialize the constant at run-time in a function it works, but I want them filescope and const. One thing that does work is to use a pointer in the struct in stead of copying the value, but I do not want that work around.

Create a list of pointers to random generated int

I'm having some difficulty in generating a random int* and store it into a list<int*>.

I have tried the following:

std::list<int*> generateInt(){
   std::list<int*> randomInt;

   int i = 0;

   // initialize random seed
   srand (time(NULL));

   while (i < 5){
      int* random = (int*)std::rand();
      std::cout << "Random int generated: " << random << std::endl;

      randomInt.push_back(random);
      i++;
   }

   return randomInt;
}

But I get compiler issue as following

error: cast to pointer from integer of different size [-Werror=int-to-pointer-cast]
       int* random = (int*)std::rand();
                                     ^

I'm not sure if i'm missing something important here? Any help or advice would be very appreciated. Thanks!

'error: invalid use of incomplete type' when linking MatLab to C++

I need to get some data from a MatLab script and use them in a C++ project using MinGW, CMake and CLion. More precisely, I have to link the MatlabEngine and MatlabDataArray libraries to get the coordinates of some Kinect v2 vertices and draw them in an OpenGL 3D world. I've followed several tutorials like this (this is the second part, where it shows how to include the engine.h file) and this. Adapting these tutorials to CMake, I've come up with this CMakeLists.txt file:

    cmake_minimum_required(VERSION 3.13)
    project(3D_avatar)

    set(CMAKE_CXX_STANDARD 14)
    set( CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}" ${CMAKE_MODULE_PATH} )

    include_directories("D:/Matlab/extern/include" "D:/Matlab/extern/lib/win64/microsoft/")

    add_executable(3D_avatar main.cpp glad.c Shader.h stb_image.h Camera.h utils.h)
    target_link_libraries(3D_avatar -lglew32 -lglfw3 -lopengl32 -lglu32 -lgdi32 -lMatlabEngine -lMatlabDataArray)

Everything seems to look good, since CMake doesn't give me any error. But, when I compile the code, I get:

    In file included from D:/Matlab/extern/include/MatlabEngine.hpp:14,
             from C:\Users\fredd\CLionProjects\3D_avatar\main.cpp:23:
    D:/Matlab/extern/include/MatlabEngine/engine_future.hpp:23:72: error: invalid use of incomplete type 'class std::future<std::unique_ptr<matlab::engine::MATLABEngine> >'
     class FutureResult<std::unique_ptr<MATLABEngine>>: public std::future<std::unique_ptr<MATLABEngine>>{
                                                                    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    In file included from D:/Matlab/extern/include/MatlabExecutionInterface/exception.hpp:10,
             from D:/Matlab/extern/include/MatlabExecutionInterface.hpp:10,
             from D:/Matlab/extern/include/MatlabEngine.hpp:9,
             from C:\Users\fredd\CLionProjects\3D_avatar\main.cpp:23:
    c:\mingw\lib\gcc\mingw32\8.2.0\include\c++\future:125:11: note: declaration of 'class std::future<std::unique_ptr<matlab::engine::MATLABEngine> >'
 class future;
       ^~~~~~
    In file included from D:/Matlab/extern/include/MatlabEngine.hpp:14,
             from C:\Users\fredd\CLionProjects\3D_avatar\main.cpp:23:
    D:/Matlab/extern/include/MatlabEngine/engine_future.hpp:138:56: error: field 'future' has incomplete type 'std::future<std::unique_ptr<matlab::engine::MATLABEngine> >'
         std::future<std::unique_ptr<MATLABEngine>> future;
                                                    ^~~~~~
    In file included from D:/Matlab/extern/include/MatlabExecutionInterface/exception.hpp:10,
             from D:/Matlab/extern/include/MatlabExecutionInterface.hpp:10,
             from D:/Matlab/extern/include/MatlabEngine.hpp:9,
             from C:\Users\fredd\CLionProjects\3D_avatar\main.cpp:23:
    c:\mingw\lib\gcc\mingw32\8.2.0\include\c++\future:125:11: note: declaration of 'class std::future<std::unique_ptr<matlab::engine::MATLABEngine> >'
 class future;
       ^~~~~~

Plus a bunch of similar errors, but with other functions of the same library. So, since I haven't edited the MatLab library in any way, that makes me wonder if I have linked the library correctly, but I can't really say what's wrong. What can I do?

Why can't I get the argument count of a template function at compile-time? [duplicate]

This question already has an answer here:

template<typename... Types>
constexpr std::size_t getArgCount(Types&&...) noexcept
{
    return sizeof...(Types);
}

struct A
{
    int n;

    void f()
    {
        static_assert(getArgCount(n) > 0); // not ok, why?
    }
};

int main()
{
    int n;
    static_assert(getArgCount(n) > 0); // ok
}

Why can't I get the argument count of a template function at compile-time?

vendredi 30 août 2019

g++.exe ignores platform-specific-macro if-else in code

So, in my cpp project, I have a portion of code where I want to wait for some seconds. Because of platform-specific differences to sleep() or Sleep() , I use some platform-specific macros. However, g++.exe errored:

$ mkdir Debug && cd Debug
$ g++ -MM -std=c++11 ../RichmanMA.cpp
RichmanMA.o: ../RichmanMA.cpp ../libs/utils.h ../libs/cttrie.h \
 ../libs/cstr.h ../libs/getindex.h ../libs/stringview.h \
 ../libs/cttrie_sw32.tcc ../libs/cttrie_sw256.tcc
(Note: all fine here)
$ g++ -O0 -g3 -Wall -c -fmessage-length=0 -std=c++11 -MMD -MP -MF"RichmanMA.d" -MT"RichmanMA.o" -o "RichmanMA.o" "../RichmanMA.cpp"
(Note: this time g++.exe exited with 1)
$ g++  -o $TRAVIS_OS_NAME ./RichmanMA.o
(Note: g++.exe exited with 1 again here)



../RichmanMA.cpp:193:6: error: 'sleep' was not declared in this scope
      sleep(3);
      ^~~~~
44../RichmanMA.cpp:193:6: note: suggested alternative: 'Sleep'
      sleep(3);
      ^~~~~
      Sleep

But the place where the compiler errored was supposed to be circumvented by a macro-specific #if #else! Here's the context:

#ifdef __WIN32__
                    system("start Drumrool.mp3");
                    Sleep(7000);
#else
                    system("open Drumrool.mp3");
                    sleep(7);
#endif
                    printf("Details in https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode!\n");
#ifdef __WIN32_
                    Sleep(3000);
#else
                    sleep(3);//Error here
#endif

Now, I have two questions:

  1. Why did g++.exe error on the fourth macro?
  2. How do I make g++.exe not error?

Is reference return type not allowed in std::function?

When I was trying to setup a bypass function argument, I found that given reference return type will bring SEGV because of invalid address. I have a piece of toy code you can play with. When I replace the reference return type by pointer, everything works fine.

/* This doc is to investigate the issue brought by reference return type of a
 * functor argument std::function. We expect it can pass the bypass function
 * defined in top layer to less-context bottom layer and still work as designed.
 * However we see weird behavior when it is std::function<const std::string&(int)>.
 * Instead, std::function<const string*(int)> works fine...
*/
#include <iostream>
#include <vector>
#include <unordered_map>
#include <string>
#include <functional>

using namespace std;

// This class stores vectror of numbers and divisors. API getRemainderRing picks
// those numbers' remainder equal to given number after division. Bypass function
// is passed in as argument to print the names.
class Elements {
public:
    Elements() = default;
    Elements(int32_t maxNum, int32_t divisor) : _div(divisor) {
        _data.clear();
        _data.reserve(maxNum);
        for (int32_t i = 0; i < maxNum; i++) {
            _data.push_back(i);
        }
    }

    void getRemainderRing(int32_t rmd, const std::function<const string&(int32_t)>& getName, string* output) {
        output->clear();
        for (int32_t i : _data) {
            if (i % _div == rmd) {
                // crashes here. getName(i) pointing to address 0
                *output += getName(i) + " ";
            }
        }
    }

private:
    vector<int32_t> _data;
    int32_t _div;
};

int main () {
    unordered_map<int32_t, string> numToStr;
    numToStr[0] = "null";
    numToStr[1] = "eins";
    numToStr[2] = "zwei";
    numToStr[3] = "drei";
    numToStr[4] = "vier";

    // The functor
    std::function<const string&(int32_t)> getName = [&numToStr](int32_t i) { return numToStr[i]; };

    Elements smallRing(4, 2); // contains {0,1,2,3}, divisor: 2
    string result;
    // This is actually to get all odd numbers < 4
    smallRing.getRemainderRing(1, getName, &result);

    // BOOM!
    cout << result << endl;

    return 0;
}

I expect the output to be "eins drei ". I checked the doc of std::function https://en.cppreference.com/w/cpp/utility/functional/function, nowhere mentioned that return type R cannot be a reference. I am wondering if this is a known defect/hole in specification, or I made some silly mistakes on using it.

Iteration through std::vector seems to be broken in only one function

I have a vector of struct elements and in one function, when iterating through it, differente errors related to bound are thrown.

I am implementing an UDP Server-client connection where some messages must be acknowledged. I implement a vector of struct elements where each contains the message sent, and the time in milliseconds it was sent. I don't think this is really relevant, for I have tried the same function storing a std::string instead of the struct, but, just in case.

When I receive an ACK message, I iterate through this vector with no problem at all:

///WORKING CODE IN OTHER FUNCTIONS
auto it = mACKExpected.begin();
for (; it != mACKExpected.end(); it++)
{
    if (it->msg.msgCount() == count)
    {
        break;
    }
}

However, I have a separate method connected to a QTimer timeout that checks if an acknowledgeable message sent more than a second ago has not been acknowledged yet:

///CODE 1
for (auto it = mACKExpected.begin();it!=mACKExpected.end();)
{
    if ((curTime - it->millis) > mquiMsgTimeout)
    {
        debug() << "Message" << it->msg.raw() << "(count: " << it->msg.msgCount() << ") not acknowledged.";
        send(QtStrMsg::newMsg(it->msg.msgType(), getCount(), it->msg.msgData()).raw());
    }
    ++it;
}

I have also tried by iterating as:

///CODE 2
for (auto it : mACKExpected)
{
    if ((curTime - it.millis) > mquiMsgTimeout)
    {
        debug() << "Message" << it.msg.raw() << "(count: " << it.msg.msgCount() << ") not acknowledged.";
        send(newMsg(it.msg.msgType(), getCount(), it.msg.msgData()).raw());
    }
}

Also by using const iterators, but there are always errors. In the CODE 1 example, a "can't increment vector iterator past end" exception is thrown in the ++it; line. In the last code, an std::bad_alloc{} instead, but in the for(... line. If I erase the current iterator by doing this:

if ((curTime - it->millis) > mquiMsgTimeout)
    {
        debug() << "Message" << it->msg.raw() << "(count: " << it->msg.msgCount() << ") not acknowledged.";
        send(QtStrMsg::newMsg(it->msg.msgType(), getCount(), it->msg.msgData()).raw());
        it=mACKExpected.erase(it);
    }
else
    ++it;

a "vector erase iterator outside range" error is risen in the erase line.

What can I do? I have been stuck with this for two days. I have tried using QVector instead, but the same problem occurs. It seems to me that something gets broken when calling this function, but I don't know what else to try. Thanks.

Can't get segmentation fault exit code from boost child process

I am trying to get the exit code of a child process (using boost::process and boost::asio) when that child process is killed due to a segmentation violation or divide be zero or any other kill signal. The exit code and error code always return with 0 and success.

I am running this on CentOS 7 using g++ 4.8.5

If I run the same code with a child process that simply returns a non-zero exit code it successfully returns that exit code.

#include <iostream>
#include <boost/process.hpp>
#include <boost/asio/io_service.hpp>

namespace bp = boost::process;
using namespace std;

int main (int argc, char** argv)
{
   string exe = "./crashes";

   vector<string> data;
   boost::asio::io_service ios;

   int exit_code;
   error_code ec;
   future<string> ostr;

   bp::child c(exe,
               (bp::std_out & bp::std_err) > ostr,
               ios,
               bp::on_exit=[&exit_code, &ec](int exit, const error_code& ecin)
                                             {exit_code = exit; ec = ecin;});

   ios.run();

   cout << "Exit Code = " << exit_code << endl;
   cout << "Error Code = " << ec.message() << endl;
   cout << "child stdin & stderr:\n";
   cout << ostr.get() << endl;
   return exit_code;
}

and the crashes code

int main (int argc, char** argv)
{
   int* y = 0;
   int c = *y;
}

The results show a 0 exit code and Success error_code

Exit Code = 0
Error Code = Success
child stdin & stderr:


running the crashes executable alone returns an exit code of 139

bash-4.2$ ./crashes 
Segmentation fault (core dumped)
bash-4.2$ echo $?
139

Templated return type specialisation for expression templates

I am dealing with several kinds of expressions template and I need to know what those expressions evaluate to (eg double). Some of these expression templates come from 3rd party library.

I am defining the traits:

template <typename X1>
struct EvaluatedType

Since I cannot specialize a template with arguments that are themselves a template ( eg EvaluatedType<MyExpression<T>> ), I do not specialize it but rather rely on a function evaluate1 that I can overload (including some templated overloads):

template <typename X1>
struct EvaluatedType
{
    using Type = decltype(evaluate1(std::declval<X1>()));
};

evaluate1 cannot be a member function because it has to accept types such as double and support 3rd party expression template types.

The first problem I am encountering is (MWE):

#include <type_traits>
#include <string>

std::string evaluate1(std::string a)
{return a;}

double evaluate1(double a)
{return a;}

template <typename X1>
struct EvaluatedType
{
    using Type = decltype(evaluate1(std::declval<X1>()));
};

int main()
{

EvaluatedType<double>::Type a;

a = 0.0;
(void) a+5.0;
}


This code fails to compile with:

error: invalid operands of types ‘void’ and ‘double’ to binary ‘operator+’
 (void) a+5.0;

a is of type void but I do not understand why because the return type of evaluate1(double) is double.

My other problem is that if I move the definition of evaluate1(double) after the definition of EvaluatedType, it fails to create EvaluatedType<double>::Type (it only sees the string version which is defined before). This is problematic because I would like other developers to be able to add new version of evaluate1 for their expression templates and be able to use EvaluatedType in other traits to know the type an expression will evaluate to.

Is there a way to define such a type:

template <typename X1>
struct EvaluatedType;

in a way that EvaluatedType<X1>::Type will be the return type of calling evaluate1 with argument of type X1.

Thank you.

Note: I have to support gcc 4.8.5 which is mostly c++11 compliant.

Please create the below json using rapidjson

Need Help Creating JSON using rapidjson

{ "fileList": { "file": [ { "mediaMetadata": { "creationTS": "198765432189", "filename": "image1.jpg", "filetype": "image/jpg", "fileIdentifier": "20190178965436521a" }, "filePartInfo": [ { "filePartType": "media", "filePartURL": "https://pcs.example.com/pcs/v1/media/20190178965436521a", "fileSize": "102408" }, { "filePartType": "thumbnail", "filePartURL": "https://pcs.example.com/pcs/v1/thumbnail/20190178965436521a" }, { "filePartType": "metadata", "filePartURL": "https://pcs.example.com/pcs/v1/metadata/20190178965436521a" } ] }, { "mediaMetadata": { "creationTS": "19843218909865", "filename": "image2.jpg", "filetype": "image/jpg", "fileIdentifier": "20181098765431z" }, "filePartInfo": [ { "filePartType": "media", "filePartURL": "https://pcs.example.com/pcs/v1/media/20181098765431z", "fileSize": "108987" }, { "filePartType": "thumbnail", "filePartURL": "https://pcs.example.com/pcs/v1/thumbnail/20181098765431z" }, { "filePartType": "metadata", "filePartURL": "https://pcs.example.com/pcs/v1/metadata/20181098765431z" } ] } ] }, "cursor": "98yuhdkd9848328" }

Integer Division up to 100 digits long and base value can be 2 ,3 4,5,6 C++ [on hold]

Need help to solve this if someone can help me out from this.

Integer Division up to 100 digits long and base value can be 2 ,3 4,5,6 C++

Why unknown type name 'Complejo'?

This is a simple example.

EXAMPLE 1 If for example I declare this code (with class Complejo in same file):

#include <iostream>
#include <string>

using namespace std;

int main()
{
  Complejo com(1,1);

  cout << com << endl;

}


class Complejo
{
private:
  double real;
  double imaginario;
public:
  //Complejo();
  Complejo(double real, double imaginario)
  {
    real = 1;
    imaginario = 2;
  }
  double getReal() { return real; }
  double getImaginario() { return imaginario; }
};

ostream &operator<<(ostream &stream, Complejo& comp)
{
  stream << comp.getReal() << " + " << comp.getReal()<< endl;
  return stream;
}

My compiler says me:

sobrecarga_ostream.cpp:15:3: error: unknown type name 'Complejo'

EXAMPLE 2 But If I create sobrecarga_ostream.cpp:

#include <iostream>
#include <string>
#include "Complejo.h"
using namespace std;

int main()
{    
  Complejo com(1,1);


  cout << com << endl;

}

and Complejo.h:

#include <iostream>

using namespace std;

class Complejo
{
private:
  double real;
  double imaginario;
public:
  //Complejo();
  Complejo(double real, double imaginario)
  {
    real = 1;
    imaginario = 2;
  }
  double getReal() { return real; }
  double getImaginario() { return imaginario; }
};

ostream &operator<<(ostream &stream, Complejo& comp)
{
  stream << comp.getReal() << " + " << comp.getReal()<< endl;
  return stream;
}

Then, it works well.

Why does not "main + class" work in the same file and if I separate files then works?

Thanks!

Why I get these wrong results?

Hello I am asked to write a program that prints the first three students from a vector of class Student. I thought of using std::tuple<Student, Student, Student>. I also should write a member function of class Student::sort which sorts students by average. Everything works fine but I have a problem: I get the avgs inside the function get_best_three as wished but in main I get weird results:

#include <iostream>
#include <vector>
#include <tuple>


class Student {
    public:
        Student(const std::string&, std::size_t, const std::vector<double>&);
        std::string name_;
        std::size_t age_;
        std::vector<double> marks_;
        double avg_;

        friend bool sort(const Student&, const Student&);
};

Student::Student(const std::string& name, std::size_t age, const std::vector<double>& marks) :
    name_(name), age_(age), marks_(marks) {

}




bool sort(const Student& rhs, const Student& lhs) {
    return rhs.avg_ > lhs.avg_;
}

std::tuple<Student, Student, Student> get_best_three(std::vector<Student>& studs) {
    for (auto& e : studs) {
        double sum = 0;
        for (const auto& d : e.marks_)
            sum += d;
        e.avg_ = sum / e.marks_.size();
        std::cout << e.avg_ << std::endl; // ok
    }

    std::sort(studs.begin(), studs.end(), sort);
    return std::make_tuple(*studs.begin(), *(studs.begin() + 1), *(studs.begin() + 2));
}


int main() {

    std::vector<Student> vstuds;
    vstuds.push_back(Student("Haroun Kdz", 37, std::vector<double>{ 12.97, 7.23, 14.55, 11.00 }));
    vstuds.push_back(Student("Hafid Lyd", 39, std::vector<double>{ 7.11, 9.49, 11.67, 8.19 }));
    vstuds.push_back(Student( "Ahmed Rhn", 38, std::vector<double>{ 15.57, 14.83, 12.67, 19.57 } ));
    vstuds.push_back(Student("Babay lsmr", 40, std::vector<double>{ 12.13, 9.99 , 7.23, 14.63 }));
    vstuds.push_back(Student("Zouhir Dj" , 38, std::vector<double>{ 8.72 , 15.67, 11.67, 8.85 }));
    vstuds.push_back(Student("Sabri Soc" , 39, std::vector<double>{ 6.99 , 8.12, 1042, 9.45 }));


    auto three_best = get_best_three(vstuds);

    // wrong results
    std::cout << std::get<0>(three_best).name_ << "   " << std::get<0>(three_best).avg_ << std::endl;
    std::cout << std::get<1>(three_best).name_ << "   " << std::get<0>(three_best).avg_ << std::endl;
    std::cout << std::get<2>(three_best).name_ << "   " << std::get<0>(three_best).avg_ << std::endl;
}

Here is the output:

11.4375 9.115 15.66 10.995 11.2275 266.64 Sabri Soc 266.64 Ahmed Rhn 266.64 Haroun Kdz 266.64

Passing a string by value, reference and rvalue

I'm just comparing the performance of passing a string to a function. The benchmark results are interesting.

Here's my code:

void add(std::string msg)
{
    msg += "world";
}

void addRvalue(std::string&& msg)
{
    msg += "world";
}

void addRef(std::string& msg)
{
    msg += "world";
}

void StringCreation() {
    add(std::string("hello "));
}

void StringCopy() {
    std::string msg("hello ");
    add(msg);
}

static void StringMove() {
    std::string msg("hello ");
    add(std::move(msg));
}

void StringRvalue() {
    std::string msg("hello ");
    addRvalue(std::move(msg));
}

void StringReference() {
    std::string msg("hello ");
    addRef(msg);
}

StringCreation(), StringRvalue() and StringReference() are equivalent. I'm surprised StringMove() is the least performant - worse than pass by value which involves a copy.

Am I right in thinking that calling StringMove() involves one move constructor followed by a copy constructor when it calls add()? It doesn't just involve one move constructor? I thought move construction was cheap for a string.

Get a list of file paths created over a period of time in C++

Is there a way to get a list of file paths created over a period of time in C++?

If using the command find, it is possible like following:

$ find ./* -mmin -2880 -mmin +1440

C++ implementing object equality with multiple levels of iheritance

i need to implement an isEqual method to multiple objects that are have multiple levels of inheritance. For this reason i have decided to create not a interface since the method are not pure virtual but just a class that i can use later as a tag.

Those classes implement a single method isEqual. Since i need a default behavior defined those methods are not pure virtual.

class A_Interface {
    virtual isEqual(shared_ptr<A_Interface> obj);
    ...
    virtual otherMethod1();
}


class B_Interface : public virtual A_Interface {
    virtual isEqual(shared_ptr<B_Interface> obj);
    ...
    virtual otherMethod2()c++;
}


class C_Interface : public virtual B_Interface {
    virtual isEqual(shared_ptr<C_Interface> obj);
    ...
    virtual otherMethod3();
}

each class implements it's own "interface like" tag class mentioned above and inherits from the parent like this:

class A : public virtual A_interface;
{
    isEqual(shared_ptr<A_Interface> obj){
    ...
    }
};



class B : public virtual A, 
          public virtual B_interface 
                {
    using A::isEqual;
    isEqual(shared_ptr<B_Interface> obj){
    ...
    }
};


class C : public virtual B,
          public virtual C_interface 
  {
    using B::isEqual;
    isEqual(shared_ptr<C_Interface> obj){
    ...

    bool parentIsEquals = B::isEqual(obj);

    ...
    }
};

In order to avoid name hinding in Class B i explicitelly declared the

using A::isEqual;

statement which solved the problem but now in class C when i want to reffer to the method "isEqual" parent class B and explicitelly specifing it like that

bool parentIsEquals = B::isEqual(obj);

i get the error

"B::isEqual' is ambiguous"

which I also understand since i have two signatures i.e.

using A::isEqual;
isEqual(shared_ptr<B_Interface> obj);

what i do not know is how to address this issue since the argument in this case "obj" does match bought signatures. I would like to understand if there a better pattern/proposition of implementing this problem.

std::lock_guard seems to give thread safety despite scoped block

mutex m;
void thread_function()
{
    static int i = 0;

    for(int j =0; j<1000; j++)
    {
        { //this scope should make this ineffective according to my understanding
        lock_guard<mutex> lock(m);
        }
        i++;

       cout<<i<<endl;
    }
}

Without the mutex, the result varies from 1990 to 2000 as expected when printing i (due to non atomic int i). Inserting the lock guard without the scoped block prevents this.

However, by my understanding, having the scoped block around it should make it acquire and release the lock immediatly, hence there is no longer thread safety when writing to int i. However, I notice i to be 2000 always. Am I misunderstanding something?

jeudi 29 août 2019

why and when do we reserve memory for vectors to add new elements to a std::vector

For std::vector i can add new elements using Push_Back.

std::vector< int > Channels;
Channels.push_Back(5);
Channels.push_Back(7);
Channels.push_Back(8);

why should i reserve memory first and than add elements.

 Channels.reserve( 3 );
 Channels.push_Back(5);
 Channels.push_Back(7);
 Channels.push_Back(8);

Will range-for in c++ calls item's copy constructor?

PanelItem is a class that does not have copy constructor(=Deleted). I use QList<PanelItem> m_arrPanelItems to store them.

When I call QList::append(const T &value), an error 'PanelItem::PanelItem(const PanelItem &)': attempting to reference a deleted function occur. I think it calls PanelItem::PanelItem(const PanelItem &) inside the function.

When I use range-for, the error appeared again. I use the const auto& in range_declaration. So I think the copy constructor PanelItem::PanelItem(const PanelItem &) will not be used.

// QList<PanelItem> m_arrPanelItems
for (const auto& t_item : this->m_arrpPanelItems) {
    // do something 
}

Why?

How to assign a lambda method to an argument by reference

I would like to assign a lambda method by reference in a method.

Here is what I tried:

QList<double> MyClass::calculate( QList<double> input, 
                                  std::function <QString( const double &value )> &myMethod )
{
  double stdDev = standardDeviation(input);
  double mean = mean(input);

  valueToLabel = [ stdDev ]( const double &value ) -> QString
  {
    double normalized = ( value - mean ) / stdDev;
    return QString::number( normalized, 'f', 2 ) + " Std Dev";
  };
}

This compiles. But I fail to get how to call this:

std::function <QString( const double &value )> valueToLabel;
const QList<Break> breaks = calculate( input, &valueToLabel );

Here is the error:

qgsclassificationmethod.cpp:153:91: error: non-const lvalue reference to type 'std::function' cannot bind to a temporary of type 'std::function *' qgsclassificationmethod.h:277:57: note: passing argument to parameter 'valueToLabel' here.

How should I do this. Later, I would like to save this lambda in a variable to use it later.

How to overload a method in an inherited class so that the base class sees the inherited version?

I'd like for an inherited class B to overload a member function func() of its base class, A. I know that when accessed by an object of B, then B::func() will be called and A::func() will be hidden unless explicitly referenced via A:: or using.

Suppose now that A has another method another_func(), which calls func(). Assuming all members and inheritance are public, of course B will inherit another_func().

Now if I call func() from B::another_func(), I want B::func() to be called, but when I try it, A::func() is called. Is there a way to achieve the behaviour I'm looking for, for the given code structure?

I found this, but it's not quite the same thing.

The answer here is helpful in general, but doesn't really address my question.

In case the wording was confusing, here it is in code form:

Header:

#include <iostream>

class A
{
public:

    void func() { std::cout << "Called A::func()" << std::endl; };
    void another_func() { func(); };

};

class B: public A
{
public:

    void func() { std::cout << "Called B::func()" << std::endl; };

};

Source:

int main(int argc, char** argv)
{
    B B_obj;
    B_obj.func();
    B_obj.another_func(); // I want this to call B::func?
    return 0;
}


The output of this code is:

Called B::func()                                                                                                              
Called A::func()

The ouput I want is:

Called B::func()                                                                                                              
Called B::func()

The obvious answer is to directly do B::func() instead of B::another_func(), but my actual situation is more complicated, and it would be very useful for me to be able to do something similar to the above.

Function call ambiguity (user-defined conversion and Derived2Base pointer conversion)

What is the reason for ambiguity in the function call in the code below?

I get that there are two viable functions here, as the compiler tells in the ERROR message (shown below at the end)

1) candidate: operator==(Base*, Base*)

-> requires user defined conversion from SmartPtr to Base* for the first parameter

-> requires Derived* to Base* implicit (?) conversion

2)candidate: bool operator==(const SmartPtr&, const Base*)

-> requires addition of top level const (exact match) for first parameter

-> requires Derived* to Base* implicit (?) conversion

From above it is quite clear that operator== defined inside SmartPtr is the better match (considering the first parameter and second one being same)

CODE:

#include <iostream>

using namespace std;

template<class T> class SmartPtr
{
    public:

    operator T*() { return pointee__;}

    inline friend bool operator==(const SmartPtr& lhs, const T* rhs){
        return lhs.pointee__ == rhs;
    }

    private:

    T* pointee__;
};

struct Base{};

class Derived:public Base{};

int main()
{
    SmartPtr<Base> sp;
    Derived * dp;

    cout<<"Hello World"<< (sp==dp);

    return 0;
}

ERROR:

main.cpp: In function ‘int main()’:
main.cpp:38:30: error: ambiguous overload for ‘operator==’ (operand types are ‘SmartPtr’ and ‘Derived*’)
     cout<<"Hello World"<< (sp==dp);
                            ~~^~~~
main.cpp:38:30: note: candidate: operator==(Base*, Base*) 
main.cpp:19:24: note: candidate: bool operator==(const SmartPtr&, const Base*)
     inline friend bool operator==(const SmartPtr& lhs, const T* rhs){
                        ^~~~~~~~

Thanks!

Build Graphics with result google benchmark for code c++

I wrote my first C ++ software and now I want to do some benchmarking with the google library.

I managed to do my first benchmarks with the result on the console, now I want to ask you a hand to understand the operations it does to make the results persistent and create a graph (I think the graph requires a separate library, right?)

There are my benchmarking inside one file cpp

#include <experimental/filesystem>

#include <benchmark/benchmark.h>
#include <glog/logging.h>

#include "../../core/ConfiguratorSingleton.h"
#include "../../core/SpyCBlock.h"

using namespace spyCBlock;
using namespace std;

string getRootPath()
{
  return experimental::filesystem::current_path();
}

const string FILE_DIR = getRootPath() + "/file/";

void createGraphTxOneFile();
void createGraphIdWalletOneFile();
void decodeJsonOneFile();

//BM
void BM_createGraphTxOneFile(benchmark::State& state)
{
    while (state.KeepRunning())
    {
        createGraphTxOneFile();
    }
}

void BM_decodeJsonOneFile(benchmark::State& state)
{
    while (state.KeepRunning())
    {
        decodeJsonOneFile();
    }
}

BENCHMARK(BM_createGraphTxOneFile)->Arg(8);
BENCHMARK(BM_decodeJsonOneFile)->Arg(8);

//Multi threding
BENCHMARK(BM_createGraphTxOneFile)->ThreadRange(2,16);
BENCHMARK(BM_decodeJsonOneFile)->ThreadRange(2,16);


void createGraphTxOneFile()
{
    string pathLogRoot = ConfiguratorSingleton::getInstance().getPathFileLogTest() + "/";
    FLAGS_minloglevel = 2;
    FLAGS_logtostderr = false;
    google::SetLogDestination(google::ERROR, pathLogRoot.append("unserialize_block_test.log").c_str());



    SpyCBlock spyCBlock;
    spyCBlock.convertBlkIntoGraphForm(FILE_DIR, FILE_DIR);
    benchmark::DoNotOptimize(pathLogRoot);
    benchmark::DoNotOptimize(spyCBlock);
}

//for this I need configure bitcoind with mainet
void createGraphIdWalletOneFile()
{
    string pathLogRoot = ConfiguratorSingleton::getInstance().getPathFileLogTest() + "/";
    FLAGS_minloglevel = 2;
    FLAGS_logtostderr = false;
    google::SetLogDestination(google::ERROR, pathLogRoot.append("unserialize_block_test.log").c_str());

    SpyCBlock spyCBlock;
    spyCBlock.convertBlkIntoGraphFormPubKey(FILE_DIR, FILE_DIR);

    benchmark::DoNotOptimize(pathLogRoot);
    benchmark::DoNotOptimize(spyCBlock);
}

void decodeJsonOneFile()
{
    string pathMockRoot = ConfiguratorSingleton::getInstance().getPathFileMockTest() + "/";
    string pathLogRoot = ConfiguratorSingleton::getInstance().getPathFileLogTest() + "/";

    FLAGS_minloglevel = 2;
    FLAGS_logtostderr = false;
    google::SetLogDestination(google::ERROR, pathLogRoot.append("unserialize_block_test.log").c_str());

    SpyCBlock spyCBlock;
    spyCBlock.convertBlkIntoJson(FILE_DIR, FILE_DIR);
    benchmark::DoNotOptimize(pathLogRoot);
    benchmark::DoNotOptimize(spyCBlock);
}


BENCHMARK_MAIN();

How to deallocate memory through delete with if statement in c++ [duplicate]

This question already has an answer here:

I have allocated memory to object using new, calling function through that object withing if statement then where should i use delete keyword?

class *obj =null;
obj = new class();
if(failed(obj->Add()))
{ 
    cout<<"function call failed"; 
}

Confusion about scope of smart pointers

Suppose I have the following function with some hypothetical class Obj that can hold a (smart) pointer to an object of type Foo:

Obj* getObj() {
  std::shared_ptr<Foo> fooPtr = std::make_shared<Foo>(new Foo());
  Obj *obj = new Obj();
  obj->setFoo(fooPtr);
  return obj; 
}

When will my smart pointer be deleted?

  1. When we return from getObj because it's now out of the function's scope and obj is not pointed-at "smartly"?
  2. Whenever obj is deleted later in my program?

My tests make me think its 2., but a colleague thinks it's 1.

I couldn't find documentation that would answer my question, as all explanations of smart pointers I read didn't do anything with the pointer that would make it escape the scope of its creator...

How to use remove_if to remove only leading and trailing spaces c++ [duplicate]

This question already has an answer here:

I'm trying to remove the leading and trailing spaces only from a string read by getline.

i.e: " John Smith ".

I used emp_name.erase(remove_if(..) Could it be used without removing the space between words?

cout << "\nEnter Employee First and Last Name: ";
cin.ignore();
getline(cin, emp_name);
emp_name.erase(remove_if(emp_name.begin(), emp_name.end(), ::isspace), emp_name.end());

I'm trying to get "John Smith"

fixed and setprecision in c++

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

int main()
{
    float c = 5.0;
    float far = (9/5)*c + 32;
    cout << fixed << "Temperature in Fahrenheit is "<< setprecision(2) << 
    far;
    return 0;
} 

I expected the output to be 41.00, but the actual output is 37.00.

how to deep copy a vector of unique_ptr

I have a class Container with a data member.

std::vector< std::unique_ptr<Sum_Function> > Functions;

I want to do a deep copy in my copy constructor , how can i do a deep copy of std::unique_ptr.

Call a function with std::function as argument with a lambda

The basis from my question I took from here: Failure to deduce template argument std::function from lambda function The question in this thread is: Why this code can't pass the lambda to the function:

#include <iostream>
#include <functional>

template <typename T>
void call(std::function<void(T)> f, T v)
{
    f(v);
}

int main(int argc, char const *argv[])
{
    auto foo = [](int i) {
        std::cout << i << std::endl;
    };
    call(foo, 1);
    return 0;
}

The answer in this thread is, since a lambda isn't a std::function. But why is this code compiling:

#include <iostream>
#include <functional>

template <typename T>
void call(std::function<void(T)> f, T v)
{
    f(v);
}

int main(int argc, char const *argv[])
{
    auto foo = [](int i) {
        std::cout << i << std::endl;
    };
    call({foo}, 1); // changed foo to {foo}
    return 0;
}

mercredi 28 août 2019

how to pass a Unique Pointer

I have a class Container, having a data member.

std::vector< std::unique_ptr<Sum_Function> > Functions;

This is how i add value to the vector.

MaxSize is the child of Sum_Function.

void WavefrontRenderer::AddMaxSize()
 {
     Container cont;
     std::unique_ptr<Sum_Function> ptrMaxSize = std::make_unique<SumMaxSize>();
     cont.AddFunction(ptrMaxSize);
}

this is the defination for Function in the Container class.

void Container::AddFunction(std::unique_ptr<Sum_Function> &func)
 {
   std::unique_ptr< Sum_Function > function(std::move(func));
   this->Functions.push_back(function);
 }

Is this the correct way to add Unique pointer to a vector.

Casting of smart pointers

I have been using Raw pointers for a while , now i am trying to use Smart Pointers.

if ClassB is child of ClassA.

I can do this with raw pointers.

 ClassA* ptr = new ClassB;

Will this line be equivalent to the above line.

std::shared_ptr<ClassA> ptr = std::shared_ptr<ClassB>(new ClassB);

when ptr goes out of scope the memory will be cleared.

How to insert to C++11 stdmap?

I am trying to insert a set of pair values into a std::map in C++11. However the values don't seem to insert into the std::map. Please do go over my code about the same. I appreciate any and all help.

    #include<iostream>
    #include<string>
    #include<algorithm>
    #include<vector>
    #include<map>
    #include<cstdlib>
    #include<utility>
    #include<ctime>

    #include "print.h"

    class ReportCard
    {
       private:
       std::map<std::string, double> m_report_card;

       public:

    std::map<std::string, double> getReportCardInstance()
    {
        return m_report_card;
    }

    };


    class Student
    {

      private:
        int m_roll_no;
        std::string m_name;

        ReportCard m_reportCard;

        public:
              Student(int inRollNo, const std::string& inName) : 
        m_roll_no(inRollNo), m_name(inName)
    {

    }

    std::string getName()
    {
        return m_name;
    }

    int getRollNo()
    {
        return m_roll_no;
    }

    ReportCard getReportCard()
    {
        return self.m_reportCard;
    }

    int getReportCardSize()
    {
        return m_reportCard.getReportCardInstance().size();
    }
    };

    class Driver
    {
        private:
          std::vector<Student> student_list;
          std::vector<Student> temp;

        public:
          void studentTestPopulate()
          {
             student_list.push_back(Student(1, "Tim"));
             student_list.push_back(Student(2, "Matt"));
             student_list.push_back(Student(100, "Luke"));
             student_list.push_back(Student(68, "Lissy"));
             student_list.push_back(Student(20, "Tony"));
             student_list.push_back(Student(33, "Joseph"));
             student_list.push_back(Student(14, "Sid"));
             student_list.push_back(Student(15, "Roby"));
             student_list.push_back(Student(44, "Rohan"));
             student_list.push_back(Student(11, "Kevin"));
             student_list.push_back(Student(19, "George"));
        }


        void reportCardPopulate()
        {
            for (auto& student : student_list)
            {
            std::cout << student.getName() << std::endl;

 student.getReportCard().getReportCardInstance().insert(std::make_pair<std::string, double>("Math", generateMark));

//This is the function that does not work. No marks are printed!!
            for (auto& mark : student.getReportCard().getReportCardInstance())
            {
                std::cout << mark.first << " " << mark.second;
            }

            //student.getReportCard().getReportCardInstance().insert(std::make_pair("Science", generateMark));
            //student.getReportCard().getReportCardInstance().insert(std::make_pair("Geography", generateMark));
            //student.getReportCard().getReportCardInstance().insert(std::make_pair("French", generateMark));
            //student.getReportCard().getReportCardInstance().insert(std::make_pair("History", generateMark));
        }
    }

    void showAllStudentDetails()
    {
        for (auto& student : student_list)
        {
            std::cout << student.getName() << std::endl;
            std::cout << student.getRollNo() << std::endl;

            std::cout << "REPORT CARD : " << student.getReportCardSize() << std::endl << std::endl;

            for (auto& mark : student.getReportCard().getReportCardInstance())
            {
                std::cout << mark.first << std::endl;
                std::cout << mark.second << std::endl;
            }
        }
    }
};

int main()
{
    srand(time(NULL));

    Driver driver;
    driver.studentTestPopulate();
    driver.reportCardPopulate();
    //driver.showAllStudentDetails();
}

The reportCardPopulate() function is supposed to insert pairs of values into a report_card map. However, the insert function doesn't seem to work. When we try to print the values within the reportCardPopulate() function, it doesn't print anything. When I try to print the size of the map, it prints 0. When I printed the size using sizeof() it prints the same size before and after the insertion.

How to remove duplicated characters from char* with delemeter parameter

I'm trying to remove duplicated characters from char* with delemeter parameter using Cstring library in UTF-8 characters, but unfortunately, it doesn't work me. My code should be similar to this

char* RemoveDuplicateWord(char* buffer,char* del,char* word)

{

char* newBuffer=0x0;



return newBuffer;

}

Is there a library I can use to stitch together 16-bit images?

I am working on a C++ project where I need to stitch together multiple 16-bit images which overlap horizontally and vertically, and then save the stitched image. Is there a library which I can use to accomplish this task?

I have tried to use OpenCV to no success because the following exception was thrown:

terminate called after throwing an instance of 'cv::Exception'
  what():  OpenCV(4.0.1) /home/rar/opencv_build/opencv/modules/stitching/src/exposure_compensate.cpp:317: error: (-215:Assertion failed) _image.type() == CV_8UC3 in function 'apply'

Other people seem to have faced the same problem as I have [https://answers.opencv.org/question/34795/stitching-16bits-greyscale-images/]

Is this an object destructor?

I am trying to understand a C++ code. The Following is written in the *.h file

Sys(int w, int h, Eigen::Matrix3f K, bool enableSys = true);
Sys(const Sys&) = delete;
Sys& operator=(const Sys&) = delete;
~Sys();

What is the interpretation of Line 2 and Line 3?

Are those destructors?
Why are they needed?
Is this a good practice?

How to pass time_t by reference into a function

I have a function definition like this:

double getPriceTimeByPtr(const StrategyParams* ptr, const int applied_price, const int timeframe, const int shift, const int shift_delta, const bool normalized, time_t &time);

but when I compile this code it errors just before the &time part so clearly there is a problem passing a time_t object by reference.

How do I fix this please?

I recently added the time_t parameter to the function and the error occurred since then.

Here's the errors generated:

Severity    Code    Description Project File    Line    Suppression 
State
Error   C2143   syntax error: missing ')' before '&'        
Error   C2143   syntax error: missing '{' before '&'        
Error   C2059   syntax error: '&'   
Error   C2059   syntax error: ')'       

The syntax seems correct to me but the compiler doesn't like it.

Reading Datatype from Node Attribute

I'm trying to write values to some OPC UA nodes with Qt and open62541. For that I have to know the different data types of the nodes. Every time I try to read the data type of a node, I get a Boolean type instead of an int32. It is the correct node in the list and I can read all nodes. Can someone please help me?

First I did:

_nodeList->at(index)->readAttributes(QOpcUa::NodeAttribute::DataType);

Second after read was finished:

qDebug() << _nodeList->at(index)->attribute(QOpcUa::NodeAttribute::DataType).value();

The output of qDebug is QOpcUa::Boolean, but it should be QOpcUa::Int32

Error C2664 'void IVerify::SetParams(void)': cannot convert argument 1 from 'std::wstring' to 'wchar_t *'

When I am calling SetParams function from the below function, it is throwing an error "cannot convert argument 1 from 'std::wstring' to 'wchar_t *'"

Can anyone please help me on this?

int main()
{

IVerify* pReader = new BCReader();
std::wstring oemPathKey;

pReader->SetParams(oemPathKey, L"read");

delete pReader;
return 0;
}


void BCReader::SetParams(wchar_t* wszParams, wchar_t* wszParamType)
{
    m_wszParamType = wszParamType;
    m_wszParams = wszParams;
}

The member variables are declared like as shown below:

class IVerify
{
private:

wchar_t* m_wszParams;
wchar_t* m_wszParamType;
};

Best way of organizing data read from memory (for debugging) c++

I am not a software engineer which means I am not really good at organizing my code, so this task might look very simple for you.

I have a qt c++ application for 32-bit ARM device (with lubuntu). The application contains a window which is used to debug the external custom instruction memory (64 rows of 32-bit instructions) of a different embedded device. I have created a function:

bool memoRead(uint32_t *memoRowData, uint8_t memoRowNumber); 

This function reads data stored in a given row.

I want to create a different function which uses the given function to read and display content of 8 rows from the memory. Example: When I call

memoDebug(0);

The output should be data stored in rows 0 to 7, and when I call

memoDebug(1);

The output should be data stored in rows 8 to 15

The obvious way is to create 8 different uint32_t variables, read each row separately and assign their values to the created 8 different variables and display/print them (which I have already done and succeeded). But I want to use something like array or struct instead and everything inside for loop to improve the code. In the future the memory size might increase significantly (65536 rows, and read 64 rows or more each time instead of 8).

What is the best and most efficient way of organizing my data and how should I use that?

Tracking User-Defined `struct` Members with a Designated Initializer Syntax

For a unit-testing library that I'm writing, rexo, I would like to implement an automatic test registration mechanism compatible with both C99 and C++11.

Automatic test registration usually goes along the lines of:

  • providing macros for the users to define test suites and test cases.
  • having the macros instantiate file-level structures that contain the data needed to fully describe their respective test suites/cases.
  • having some logic that can somehow discover these structure instances at run-time.

I've got most of this sorted out but one bit: providing a nice interface for defining additional data to be attached to each test suite/case.

The (non-public) data structure to attach looks like this:

struct rx__data {
    const char *name;
    int value;
    rx_run_fn run;
};

I managed to get a RX__MAKE_DATA() macro working with a designated initializer syntax, as follows:

/* https://github.com/swansontec/map-macro ----------------------------------- */

#define EVAL0(...) __VA_ARGS__
#define EVAL1(...) EVAL0(EVAL0(EVAL0(__VA_ARGS__)))
#define EVAL2(...) EVAL1(EVAL1(EVAL1(__VA_ARGS__)))
#define EVAL3(...) EVAL2(EVAL2(EVAL2(__VA_ARGS__)))
#define EVAL4(...) EVAL3(EVAL3(EVAL3(__VA_ARGS__)))
#define EVAL(...)  EVAL4(EVAL4(EVAL4(__VA_ARGS__)))

#define MAP_END(...)
#define MAP_OUT

#define MAP_GET_END2() 0, MAP_END
#define MAP_GET_END1(...) MAP_GET_END2
#define MAP_GET_END(...) MAP_GET_END1
#define MAP_NEXT0(test, next, ...) next MAP_OUT
#define MAP_NEXT1(test, next) MAP_NEXT0(test, next, 0)
#define MAP_NEXT(test, next)  MAP_NEXT1(MAP_GET_END test, next)

#define MAP0(f, x, peek, ...) f(x) MAP_NEXT(peek, MAP1)(f, peek, __VA_ARGS__)
#define MAP1(f, x, peek, ...) f(x) MAP_NEXT(peek, MAP0)(f, peek, __VA_ARGS__)

#define MAP(f, ...) EVAL(MAP1(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0))

/* -------------------------------------------------------------------------- */

typedef int (*rx_run_fn)();

struct rx__data {
    const char *name;
    int value;
    rx_run_fn run;
};

int run() { return 999; }

#ifdef __cplusplus
#define RX__WRAP_ASSIGNMENT(x) out x;
#define RX__MAKE_DATA(...)                                                     \
    []() -> struct rx__data {                                                  \
        struct rx__data out = {};                                              \
        MAP(RX__WRAP_ASSIGNMENT, __VA_ARGS__);                                 \
        return out;                                                            \
    }()
#else
#define RX__MAKE_DATA(...) { __VA_ARGS__ }
#endif

static const struct rx__data foo
    = RX__MAKE_DATA(.name = "abc", .value = 123, .run = run);

It's all good except that, since the rx__data struct can be attached to both test suites and test cases, I'd like to have a mechanism that allows me to know if a data member has been explicitely set or not by the user. This way, I can infer the final data to apply to a test case by:

  • retrieving the data to inherit from the parent test suite.
  • overriding only the members from the test suite that were explicitely set onto the test case.

For example

RX_TEST_SUITE(my_suite, .name = "abc", .value = 123, .run = run);

RX_TEST_CASE(my_suite, my_case, .value = 666)
{
    ...
}

would result in ‘my_case’ having the data {.name = "abc", .value = 666, .run = run} attached to it.

For this to work, I thought of adding a boolean value for each field, to keep track of what has been explicitely defined or not by the user:

typedef int (*rx_run_fn)();

struct rx__data {
    const char *name;
    int value;
    rx_run_fn run;

    int name_defined;
    int value_defined;
    int run_defined;
};

int run() { return 999; }

#ifdef __cplusplus
#define RX__ARG(field, value) out.field = value; out.field##_defined = 1
#define RX__MAKE_DATA(...)                                                     \
    []() -> struct rx__data {                                                  \
        struct rx__data out = {};                                              \
        __VA_ARGS__;                                                           \
        return out;                                                            \
    }();
#else
#define RX__ARG(field, value) .field = value, .field##_defined = 1
#define RX__MAKE_DATA(...) { __VA_ARGS__ }
#endif

#define RX_NAME_ARG(x) RX__ARG(name, x)
#define RX_VALUE_ARG(x) RX__ARG(value, x)
#define RX_RUN_ARG(x) RX__ARG(run, x)

static const struct rx__data foo
    = RX__MAKE_DATA(RX_NAME_ARG("abc"), RX_VALUE_ARG(123), RX_RUN_ARG(run));

And it's all working great here again, except that the user now has to set the arguments using macros instead of the previous designated initializer syntax.

So the questions is: how can I keep track of these user-defined struct members while preserving the designated initializer syntax?

Note: if possible, I'd really like to have a robust way of detecting if a member was defined, so no in-band indicators—that is, no ”if this member has this magic value, then it's likely that is wasn't explicitely set”.

mardi 27 août 2019

compile error when a template function call a template static function in a template class

A compile error when I write template in c++, hard to understand for me. This is the code

template<typename T>
struct S
{
    template<typename U>
    static void fun()
    {
    }
};

template<typename T>
void f()
{
    S<T>::fun<int>(); //compile error, excepted primary expression before `int`

}

How to use std::enable_if on method of templated class with seperate declaration and definition via specialization

I'm trying to have a templated class split between a header file and implementation using specialization, but I want one method to only appear in some specializations.

Header file:

template <typename T>
class A
{
  public:
  void foo();
  void bar();

  template<typename U = T, typename std::enable_if<std::is_convertible<int,U>::value>>::type*=nullptr>
  void special();
};

The implementation:

template<typename T>
void A<T>::foo()
{
  ...
}

template<typename T>
void A<T>::bar()
{
  ...
}

template<typename T, typename std::enable_if<std::is_convertible<int,T>::value>::type>
void A<T>::special()
{
  ...
}

// generate specializations
template
class A<float>;

template
class A<int>;

template
class A<std::string>;

However I keep getting error: declaration is incompatible with function template "void A<T>::special()" when I try it like this, or when I move the std::enable_if to be the return type. How should the definition be to match the declaration of this method special()?

move constructor is not getting called when I am calling constructor explicitly as a parameter

I am trying to learn about move constructors. I wrote the below program.

#include <iostream>
#include <algorithm>

using namespace std;

class myclass {
    public:
        myclass() { 
            cout << "In Constructor" << endl;
        }

        ~myclass() {
            cout << "In Destructor" << endl;
        }

        myclass(const myclass &obj) {
            cout << "In Copy Constructor" << endl;
        }

        myclass(myclass &&obj) {
            cout << "In Move Constructor" << endl;
        }
};

int main()
{
    myclass obj = myclass();       // Line 1
    myclass obj(myclass());        // Line 2
}

Line 1 is working as expected, move constructor is getting called. But for line 2, nothing is happening. Not even constructor is getting called. I thought that move constructor will be called for line 2 also. But no function is getting called. I know if I call the constructor explicitly, the object will be destroyed at the end of the expression. But I am not sure why even constructor is not getting called. Can any one please let me know what is wrong with Line 2?

Using std::async slower than non-async method of populating a vector

I am experimenting with std::async to populate a vector. The idea behind it is to use multi-threading to save time. However, running some benchmark tests I find that my non-async method is faster!

#include <algorithm>
#include <vector>
#include <future>

std::vector<int> Generate(int i)
{
    std::vector<int> v;
    for (int j = i; j < i + 10; ++j)
    {
        v.push_back(j);
    }
    return v;
}

Async:

std::vector<std::future<std::vector<int>>> futures;
for (int i = 0; i < 200; i+=10)
{
  futures.push_back(std::async(
    [](int i) { return Generate(i); }, i));
}

std::vector<int> res;
for (auto &&f : futures)
{
  auto vec = f.get();
  res.insert(std::end(res), std::begin(vec), std::end(vec));
}

Non-async:

std::vector<int> res;
for (int i = 0; i < 200; i+=10)
{
   auto vec = Generate(i);
   res.insert(std::end(res), std::begin(vec), std::end(vec));
}

My benchmark test shows that the async method is 71 times slower than non-async. What am I doing wrong?

C++11 template deduction fails when using std::function for parameter [duplicate]

Compiling with g++ 7.4.0, with --std=c++11 option, the following code works perfectly:

template<typename T, typename funcT>
size_t find_index( // wrapper over std::find_if to return the element index
    const std::vector<T>& v,
    funcT&& func // function type is a template
) {
    typename std::vector<T>::const_iterator it =
        std::find_if(v.cbegin(), v.cend(), std::move(func));
    return it == v.cend() ? -1 : it - v.cbegin();
}

int main() { // usage example
    std::vector<int> nums = {10, 20, 30};
    size_t x = find_index(nums,
        [](const int& i) -> bool { return i == 10; });
    return 0;
}

However, if I change the function signature to this:

// This is how I'd like to write the function!
template<typename T>
size_t find_index(
    const std::vector<T>& v,
    std::function<bool(const T&)>&& func // function type is explicit now!
) {
    typename std::vector<T>::const_iterator it =
        std::find_if(v.cbegin(), v.cend(), std::move(func));
    return it == v.cend() ? -1 : it - v.cbegin();
}

Template deduction fails, and I receive the error:

a.cpp: In function ‘int main()’:
a.cpp:30:57: error: no matching function for call to ‘find_index(std::vector<int>&, main()::<lambda(const int&)>)’
                [](const int& i) -> bool { return i == 10; });
                                                                            ^
a.cpp:8:12: note: candidate: template<class T> size_t find_index(const std::vector<T>&, std::function<bool(const T&)>&&)
    size_t find_index(
                ^~~~~~~~~~
a.cpp:8:12: note:   template argument deduction/substitution failed:
a.cpp:30:57: note:   ‘main()::<lambda(const int&)>’ is not derived from ‘std::function<bool(const T&)>’
                [](const int& i) -> bool { return i == 10; });

In the other hand, if I explicit the function call template parameter, it works:

// I don't want to have to write it this way...
size_t x = find_index<int>(nums, // note explicit <int> template parameter
    [](const int& i) -> bool { return i == 10; });

Why can't the compiler deduce the int template parameter? What am I missing?

How can we change the type of void pointer to int type or float type?

I want to convert a void pointer to integer pointer type or float pointer type. My code takes input like what's the data type and on the basis of that, I want to create an array of that kind of data type. So for this, I have created a void pointer and I am trying to cast it to respective data types. And now I have overloaded three functions of the same name with different data types. Or how can I achieve this with void pointer??

   while (1) {
    printf("(1)Integer\n(2)Float\n(3)Char\n");
    ReadMenu(inp);

    if (StrCmp(inp, "1")) {

        arr_int = (int*)arr;
        arr = arr_int ;
        what = 'i' ;
    } else if (StrCmp(inp, "2")) {

        arr = (float*)arr;
        arr = arr_float ;
        what = 'f' ;
    } else if (StrCmp(inp, "3")) {

        arr_char = (char*)arr;
        arr = arr_char ;
        what = 'c' ;
    } else {
        PrintErrInp();
        continue;
    }
while (1) {
    printf("(1)Insert\n(2)Top\n(3)Pop(4)IsEmpty\n(5)Exit\n");
    ReadMenu(inp);
    if (StrCmp(inp, "1")) {

        cout << "Enter an Element: ";
        bool isit = '\0';
        ReadString(str);
        if (what == 'i') {

            isit = IsInt(str) ;
        } else if (what == 'f') {

            isit = IsFloat(str) ; 
        } else {

            isit = IsChar(str) ;
        }
        if (isit) {

            InsertStack(arr, inp, size) ;
        } else {
            PrintErrInp() ;
            continue ;
        }
    }

Q2_1.cpp(230): error C2665: 'InsertStack': none of the 3 overloads could 
convert all the argument types
Q2_1.cpp(131): note: could be 'void InsertStack(char [],char,size_t &)'
Q2_1.cpp(84): note: or       'void InsertStack(double [],double,size_t &)'
Q2_1.cpp(36): note: or       'void InsertStack(int [],int,size_t &)'
Q2_1.cpp(230): note: while trying to match the argument list '(void *, 
char *, size_t)'

Union cannot be defined in a type specifier

I try to include a c code library from Github in my C++ application but encountered some compile error.

Errors for the original code:

'_u16' cannot be defined in a type specifier


non-constant-expression cannot be narrowed from type 'int' to 'uint8_t' (aka 'unsigned char') in initializer list [-Wc++11-narrowing]

The application is compiled by Clang 10.0.1 using CMake on macOS with following in CMakeLists.txt:

set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c11")

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

Following is the original code:

inline static void UInt16SetBE(void *b2, uint16_t u)
{
    *(union _u16 { uint8_t u8[16/8]; } *)b2 = (union _u16) { (u >> 8) & 0xff, u & 0xff };
}

Following is my code after adding casting to try to resolve the error:

inline static void UInt16SetBE(void *b2, uint16_t u)
{
    *(union _u16 { uint8_t u8[16/8]; } *)b2 = (union _u16) { (uint8_t)((u >> 8) & 0xff), (uint8_t)(u & 0xff) };
}

Errors after my change:

'_u16' cannot be defined in a type specifier

Does anyone know what the syntax of the declaration means? *(union _u16 { uint8_t u8[16/8]; } *)b2

If an object is created locally and thrown as an exception in C++, how can a local object be valid outside is scope .i.e., in catch block?

Inside a try block, a function "fun()" is invoked. A local object of class "abc" is created inside "fun" and an exception is thrown. This local object is catched in "catch" block, and this has printed a proper value. As this object was created locally, shouldn't it have printed "0(default value)" as the stack unwinding would have happened when throw was called.

#include <iostream>

using namespace std;

class abc
{
    int var;
    public:
    abc():abc(0){}
    abc(int i):var(i){}
    void print()
    {
        cout << "inside abc : " << var << endl;
    }
};

void fun()
{
    cout << "inside fun()" << endl;
    abc obj(10);
    throw obj;
}

int main()
{
    try
    {
        cout << "inside try" << endl;
        fun();
    }catch(abc& ob)
    {
        ob.print();
    }
    return 0;
}

Output : inside try
inside fun()
inside abc : 10

My expectation: inside try
inside fun()
inside abc : 0enter code here

Inline lambdas in header files

This is similar to other questions I've seen, but given C++17's introduction of inline variables, it's worth asking. Consider this pattern:

auto to_ref = [](auto const& ptr) -> decltype(auto) { return *ptr; }

std::vector<std::unique_ptr<Foo>> foo_ptrs = from_somewhere();
for (Foo const& foo : foo_ptrs | transform(to_ref)) {
}

The to_ref generic lambda is...well, generic...so it makes sense to put it in a header so people aren't duplicating it everywhere.

My question: do the linkage considerations for templates also apply for generic lambdas? In other words, it is the responsibility of the compiler/linker to ensure that ODR is not violated for multiple instantiations of a given template with the same template arguments. Can I rely on that same behavior, or should I prepend the inline specifier to the auto to_ref = ...; specification?

How to print all combinations starting with A

How would I modify my code so it only prints combinations with only A as the starting character.

This will print all combinations for all starting characters.

So for an 8 char string it should be. AAAAAAAAA - AZZZZZZZZ

#include <string>
#include <iostream>


void print_str(const char*,std::string,const int, const int);

int main()

{

    int lenght = 2;

    char str[] = {'A', 'B', 'C', 'D'};



    int n = sizeof str;

    print_str(str, "", n, lenght);  //Note: this function works on all cases and not just the case above

    return 0;

}

// The main recursive method to print all possible strings of length "length"
    void print_str(const char str[],std::string prefix,const int n, const int lenght)

    {

        if (lenght == 1)

            {

                for (int j = 0; j < n; j++)

                std::cout << prefix + str[j] << std::endl;

            }//Base case: lenght = 1, print the string "lenght" times + the remaining letter

        else

            {


               // One by one add all characters from "str" and recursively call for "length" equals to "lenght"-1
                for (int i = 0; i < n; i++)

                // Next character of input added
                print_str(str, prefix + str[i], n, lenght - 1);
                // "lenght" is decreased, because we have added a new character

            }

    }

How to disambiguate overloaded template functions

There is a problem with the following code. While 1 part is OK, problem is with the 2nd part of the main(). On compilation an ambiguous error message is displayed. How can I change the code to resolve the ambiguity?

template<typename Arg> void func(Arg arg) 
{  
    arg();
}
template<typename Arg, typename... Args> void func(Arg arg, Args... args) 
{  
    func(args...);
    arg();
}
template<typename Container> void func(Container & c) 
{
    for (typename Container::reverse_iterator i = c.rbegin(); i != c.rend(); ++i ) 
    { 
        (*i)();
    } 
}

void f()
{
    std::cout << "+" ;
}

int main()
{
    //1
    func(f,f,f);

    //2    
    std::vector<std::function<void()> > v{f,f};
    func(v);
}

Link to code: cpp.sh/3wxrc

How do I set the time line for multiple instances?

I am working on creating a single dialog multi window video playback application using libvlc.I have taken help from https://www.codeproject.com/Articles/38952/VLCWrapper-A-Little-C-wrapper-Around-libvlc. I have made some progress in terms of the playing multiple videos at the same time.The video information is stored in a text file having name,starttime,endtime structure.The timeline can differ for each media. I have created an array of vlc instance pointers and storing media information in that. What I need to do now is to have a slider control which runs from min/max time and plays media from file when the position is equal to the time in the file.I am able to do that. The problem I am facing is in setting the correct position,synchronization and slider events. Here is what I have tried till now..

void SetControlsPosition()
{
    m_nTimer++;
    m_nMinusTimer--;
    if(m_nMinusTimer == m_nMediaTimeDiff)//m_nMediaTimediff is diff of file time
    {
        CString sMedia = get<2>(MediaVector[DiffIndex]);
        PMediaInstArr[DiffIndex]->SetScreenResource(pStaticArr[DiffIndex].GetSafeHwnd());
        PMediaInstArr[DiffIndex]->AttachEventController(EventControl,this);
        PMediaInstArr[DiffIndex]->InitializeAndOpenMedia(sMedia);
        PMediaInstArr[DiffIndex]->StartPlaying();
        if((MediaVector.Size()-1)>DiffIndex))
        {
            m_nMediaTimeDiff = get<0>(MediaVector[DiffIndex])-get<0> 
           (MediaVector[DiffIndex+1]);
        }
        m_nMinusTimer = 0;
        DiffIndex+=1;
    }
//Media1 start time = 11:30:15 Media2 start time = 11:30:30 then m_nMediaTimeDiff = 15
//MediaVector has the contents of media information and is a vector of tuples
//pStaticArr  is static control array created at runtime
//DiffIndex index for the time diff calculation
//Now setting the slider control
    if(PMediaInstArr.GetSize()>0)
    {
        nMediaLen =  PMediaInstArr[0]->GetMediaLength();//returns media len in millisec
        long newpos =  PMediaInstArr[0]->GetTime();//current time in millis
        CTimeSpan len(static_cast<time_t>(nMediaLen /1000);
        CTimeSpan actualPos(static_cast<time_t>(newpos /1000);
        CTimeSpan newTime = StartTimeStamp+actualPos;
        CTimeSpan TimeInterval= EndTimeStamp - StartTimeStamp;
        int nNewPosForSlider = nMediaLen ?static_cast<int>((static_cast<double> 
       (newpos)/static_cast<double>(nMediaLen)*100)):0;
        m_Slider.SetPos(nNewPosForSlider );
    }

Now this works as intended for a single media which I play separately. My question is how can I make it work for more than one media. I want to make it like a video debriefing kind of application.How do I handle HScroll events for slider for multiple medias.

Thanks.

Finding pair values in a given range

I have an array or N pairs (v1, v2) where v1 <= v2. These are supposed to represent events in time that start at v1 and end at v2. they can be equal, then the event is instantaneous. The array is sorted by starting time, v1.

For a given range (L, R), I would like to find any pair where L <= v1 <= R or L <= v2 <= R. The idea here is to get events starting, happening or ending in the given range.

My main problem is efficiency. The array could contains hundreds of thousands of events. So just a linear search going through all pairs is not an option.

I read a bit about kd-tree but the problem with it is that it excludes the boundaries of the range and would only return L <= v1 <= R AND L <= v2 <= R. That is, would only return events that actually happen (start AND end) in the range whereas I need start OR end (or both obviously).

I thought also about keeping 2 lookup tables (I use double for time)

std::map<double, Event*> startPoints;
std::map<double, Event*> endPoints;

and the use the std::find algorithm in both of them and merge the results.

Just looking for an advise, wether it's a good solution or if there is a more clever way.

When replacing from "wcslen" to "strnlen_s", is it the correct way to typecast with "const char*"?

When replacing from "wcslen" to "strnlen_s", is it the correct way to typecast with "const char*"?

In the below function, I am replacing

if (szPath[wcslen(szPath) - 1] != L'\')

with

if (szPath[strnlen_s((const char*)szPath, sizeof(szPath)) - 1] != L'\')

Below is the code snippet:

bool Activation::Execute()
{
    HRESULT hr = S_OK;
    typedef ULONG(APIENTRY *ActivateNowProc)(int);

    wchar_t szPath[MAX_PATH];

    std::fill_n(szPath, MAX_PATH, L'\0');
    //Gets the  CSIDL Program files path
    hr = SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES, NULL, NULL, szPath);
    if (SUCCEEDED(hr))
    {
        _tcscat_s(szPath, sizeof(szPath) / sizeof(TCHAR), MSC_PATH);
    }

    if (IsDirectoryExist(szPath))
    {
        std::wstringstream strActivationLibPath;
        strActivationLibPath << szPath;
        //if (szPath[wcslen(szPath) - 1] != L'\\') 
        if (szPath[strnlen_s((const char*)szPath, sizeof(szPath)) - 1] != L'\\')
            strActivationLibPath << L"\\";
        strActivationLibPath << OOBE_FOLDER_NAME << L"\\" << ACTIVATION_LIB_NAME;

        DWORD dwErr = McValidateModule(strActivationLibPath.str().c_str());
        if (dwErr != ERROR_SUCCESS) 
        {
            return false;
        }

        HMODULE hModule = LoadLibrary(strActivationLibPath.str().c_str());
        if (hModule == 0)
        {
            return false;
        }

        ActivateNowProc ActivateNow = (ActivateNowProc)GetProcAddress(hModule, ACTIVATION_PROC_NAME);
        if (ActivateNow)
        {
            long retVal = ActivateNow(1);
            if (retVal == E_FAIL)
            {
                FreeLibrary(hModule);
                return false;
            }
            else
            {
                ::Sleep(2000);
                CheckProcessRunningAndWait(SYNCPROCESSNAME);
            }
        }
        else
        {
            FreeLibrary(hModule);
            return false;
        }
        FreeLibrary(hModule);
        return true;
    }
    return false;
}

How to compile c++98 code written on RedHat 5 on RedHat 7 Linux

I have a c++ application written and compiled on a RedHat5 Linux machine using NetBeans. (c++ and gcc version 4.1.2) I want to compile it on a RedHat7 machine(c++ and gcc version 4.8.5). My problem is that all functions related to the c++ std library are showing an error.

I tried changing the c++ compiler to c++98 and c++11 but both didn't work. All header includes remained the same.

`// A simple split function that returns vector of double
std::vector<double> ConfigParser::split(std::string combined, char separator){
    std::vector<double> separated;`
    std::replace(combined.begin(), combined.end(), separator, ' ');`
    std::stringstream ss(combined);
    std::string temp;
    while (ss >> temp)
    {
        separated.push_back(atof(temp.c_str()));
    }

    return separated;
}

ConfigParser.cpp:34:5: error: ‘replace’ is not a member of ‘std’

ConfigParser.cpp:39:46: error: ‘atof’ was not declared in this scope

Return conditional `range_expression`

What's the most efficient way of iterating over one of several known ranges based on some condition?

pseudo-code for a binary condition:

for element in (condition ? range_a : range_b)
  // do work

This 'example' shows my intention using a range-based for loop but as std::initializer_list has reference semantics it won't work.

constexpr auto some_range(bool c) -> std::initializer_list<int> {
  if (c) {
    return {1,2};
  } else {
    return {3, 4, 5};
  }
}

bool cond = true; // false

for(auto x : some_range(cond)) {
  // things
}

yields: warning: returning address of local temporary object [-Wreturn-stack-address]

During run-time I could return a std::vector but that would involve constructing a new vector every call:

auto some_range(bool c) -> std::vector<int> {
  if (c) {
    return {1,2};
  } else {
    return {3, 4, 5};
  }
}

I could use a fixed size std::array of std::optional<int> but I would rather resort to a C++14 or c++11 solution.

Any help would be greatly appreciated.

C++: Release barriers required in constructor?

If I create a thread in a constructor and if that thread accesses the object do I need to introduce a release barrier before the thread accesses the object? Specifically, if I have the code below (wandbox link) do I need to lock the mutex in the constructor (the commented out line)? I need to make sure that the worker_thread_ sees the write to run_worker_thread_ so that is doesn't immediately exit. I realize using an atomic boolean is better here but I'm interested in understanding the memory ordering implications here. Based on my understanding I think I do need to lock the mutex in the constructor to ensure that the release operation that the unlocking of the mutex in the constructor provides synchronizes with the acquire operation provided by the locking of the mutex in the threadLoop() via the call to shouldRun().

class ThreadLooper {
 public:
   ThreadLooper(std::string thread_name)
       : thread_name_{std::move(thread_name)}, loop_counter_{0} {
        //std::lock_guard<std::mutex> lock(mutex_);
        run_worker_thread_ = true;
        worker_thread_ = std::thread([this]() { threadLoop(); });
        // mutex unlock provides release semantics
   }

   ~ThreadLooper() {
     {
        std::lock_guard<std::mutex> lock(mutex_);
        run_worker_thread_ = false;
     }
     if (worker_thread_.joinable()) {
       worker_thread_.join();
     }
     cout << thread_name_ << ": destroyed and counter is " << loop_counter_
          << std::endl;     
   }

 private:
  bool shouldRun() {
      std::lock_guard<std::mutex> lock(mutex_);
      return run_worker_thread_;
  }

  void threadLoop() {
    cout << thread_name_ << ": threadLoop() started running"
         << std::endl;
    while (shouldRun()) {
      using namespace std::literals::chrono_literals;
      std::this_thread::sleep_for(2s);
      ++loop_counter_;
      cout << thread_name_ << ": counter is " << loop_counter_ << std::endl;
    }
    cout << thread_name_
         << ": exiting threadLoop() because flag is false" << std::endl;
  }

  const std::string thread_name_;
  std::atomic_uint64_t loop_counter_;
  bool run_worker_thread_;
  std::mutex mutex_;
  std::thread worker_thread_;
};

This also got me to thinking about more generally if I were to initialize a bunch of regular int (not atomic) member variables in the constructor that were then read from other threads via some public methods if I would need to similarly lock the mutex in the constructor in addition to in the methods that read these variables. This seems slightly different to me than the case above since I know that the object would be fully constructed before any other thread could access it, but that doesn't seem to ensure that the initialization of the object would be visible to the other threads without a release operation in the constructor.

const ok, but not constexpr?

With a constexpr-specified function foo_constexpr I have code such as shown below:

const auto x = foo_constexpr(y);
static_assert(x==0);

Under which circumstances could the code then fail to compile, when the declaration of x is changed to constexpr? (After all, x must already be a constant expression for use in the static_assert.) That is:

constexpr auto x = foo_constexpr(y);
static_assert(x==0);

lundi 26 août 2019

About the wavelet transform

I'm just starting out with wavelet transform, and I want to do pitch detection.So I downloaded gnu's GSL computing library.But I don't understand a few lines of code in the wavelet transform function, can someone help me explain it?I posted the function related code.thank you

#define ELEMENT(a,stride,i) ((a)[(stride)*(i)])

int
gsl_wavelet_transform (const gsl_wavelet * w, 
                       double *data, size_t stride, size_t n,
                       gsl_wavelet_direction dir, 
                       gsl_wavelet_workspace * work)
{
  size_t i;

  if (work->n < n)
    {
      //GSL_ERROR ("not enough workspace provided", GSL_EINVAL);
    }

  if (binary_logn (n) == -1)
    {
      //GSL_ERROR ("n is not a power of 2", GSL_EINVAL);
    }

  if (n < 2)
    {
      return GSL_SUCCESS;
    }

  if (dir == gsl_wavelet_forward)
    {
      for (i = n; i >= 2; i >>= 1)
        {
          dwt_step (w, data, stride, i, dir, work);
        }
    }
  else
    {
      for (i = 2; i <= n; i <<= 1)
        {
          dwt_step (w, data, stride, i, dir, work);
        }
    }

  return GSL_SUCCESS;
}

static void
dwt_step (const gsl_wavelet * w, double *a, size_t stride, size_t n,
          gsl_wavelet_direction dir, gsl_wavelet_workspace * work)
{
  double ai, ai1;
  size_t i, ii;
  size_t jf;
  size_t k;
  size_t n1, ni, nh, nmod;

  for (i = 0; i < work->n; i++)
    {
      work->scratch[i] = 0.0;
    }


  **nmod = w->nc * n;** //Can not understand the meaning of this code
  **nmod -= w->offset;**    //Why does it need to be offset        /* center support */

  **n1 = n - 1;**
  **nh = n >> 1;**

  if (dir == gsl_wavelet_forward)
    {
      for (ii = 0, i = 0; i < n; i += 2, ii++)
        {
          double h = 0, g = 0;

          **ni = i + nmod;** //What meaning

          for (k = 0; k < w->nc; k++)
            {
              **jf = n1 & (ni + k);**  //What meaning
              h += w->h1[k] * ELEMENT (a, stride, jf);
              g += w->g1[k] * ELEMENT (a, stride, jf);
            }

          work->scratch[ii] += h;
          work->scratch[ii + nh] += g;
        }
    }

/* else { for (ii = 0, i = 0; i < n; i += 2, ii++) { ai = ELEMENT (a, stride, ii); ai1 = ELEMENT (a, stride, ii + nh); ni = i + nmod; for (k = 0; k < w->nc; k++) { jf = (n1 & (ni + k)); work->scratch[jf] += (w->h2[k] * ai + w->g2[k] * ai1); } } } */ for (i = 0; i < n; i++) { ELEMENT (a, stride, i) = work->scratch[i]; } }

Why is no compile-time error when calling an ambiguous ctor?

#include <iostream>
#include <vector>

int main()
{
    auto v1 = std::vector<std::size_t>(std::size_t{8});
    std::cout << v1.size() << std::endl;

    auto v2 = std::vector<std::size_t>{std::size_t{8}};
    std::cout << v2.size() << std::endl;
}

The code outputs:

8
1

I know this is a well-known problem in C++ because of:

std::vector<std::size_t>(std::size_t{8}) calls

explicit vector(size_type count) while

std::vector<std::size_t>{std::size_t{8}} calls

vector(std::initializer_list<T> init, const Allocator& alloc = Allocator()).

To my surprise:

Why does the second call not trigger a compile-time error for overload ambiguity?

How to pass raw string literals to [[deprecated(message)]] attribute?

I want to pass a raw string literals to [[deprecated(message)]] attribute as the message. The message is used again and again. So I want to avoid code repeat.

First, I tried to use static constexpr variable.

static constexpr auto str = R"(
Use this_func()
Description: ...
Parameter: ...
)";

[[deprecated(str)]] 
void test1() {
}

I got the error "deprecated message is not a string". It seems that static constexpr variable isn't accepted by [[deprecated(message)]].

I tried to define the row string literals as preprocessor macro.

#define STR R"(
Use this_func()
Description: ...
Parameter: ...
)"

[[deprecated(STR)]]
void test2() {
}

It works as I expected as follows on clang++ 8.0.0.

prog.cc:38:5: warning: 'test2' is deprecated: 
Use this_func()
Description: ...
Parameter: ...
 [-Wdeprecated-declarations]
    test2();
    ^

Demo: https://wandbox.org/permlink/gN4iOrul8Y0F76TZ

But g++ 9.2.0 outputs the compile error as follows:

prog.cc:19:13: error: unterminated raw string
   19 | #define STR R"(
      |             ^
prog.cc:23:2: warning: missing terminating " character
   23 | )"
      |  ^

https://wandbox.org/permlink/e62pQ2Dq9vTuG6Or

#define STR R"(  \
Use this_func()  \
Description: ... \
Parameter: ...   \
)"

If I add backslashes on the tail of each line, no compile error occurred but output message is different from I expected as follows:

prog.cc:38:11: warning: 'void test2()' is deprecated:   \\nUse this_func()  \\nDescription: ... \\nParameter: ...   \\n [-Wdeprecated-declarations]

I'm not sure which compiler works correctly.

Is there any way to pass the raw string literals variable/macro to [[deprecated]] attribute?