samedi 30 juin 2018

Is there any way to extend the lifetime of a temporary object in C++?

I wrote a scope guard which resets a value when the scope exits:

template <class T>
struct ResetGuard
{
    T old_value;
    T& obj_to_reset;
    ResetGuard(T& obj_to_reset, const T& new_value) :
        old_value(obj_to_reset),
        obj_to_reset(obj_to_reset)
    {
        obj_to_reset = new_value;
    }

    ~ResetGuard() { obj_to_reset = old_value; }
};

When this scope guard is returned from a function, is there any way to prevent the immediate destruction of the scope guard if it wasn't saved?

For example:

int GLOBAL_VALUE = 0;
ResetGuard<int> temporarily_set_global_value(int new_val) {
    return { GLOBAL_VALUE, new_val }; //updates the global variable
}
void foo() {
    //Ideally, someone calling this function
    //Wouldn't have to save the returned value to a local variable
    temporarily_set_global_value(15);
    std::cout << "GLOBAL_VALUE is " << GLOBAL_VALUE << std::endl;
}

I need to check if thrown exception from operator=?

given the following code:

template <class T>
class A {
     T* arr;
     int size;
public:
A(int size) : arr(new T[size]) , size(size) {
}
//..

A& operator=(const A& a){
     if(this == &a){
          return *this;
     }
     this->size = a.size;
     T* ar=new T[a.size];
     for(int i=0 ; i<size ; i++){
          ar[i]=a.arr[i]; // I need to do it at "try-catch" ?
     }
     this->arr=ar;
     return *this;
}
     //...
};

While I copies the elements from the given array, I need to do it at try-catch or no? It's a good idea or not?

Why my c++ array element changed into a large number?

#include<iostream>
using std::cin;
using std::cout;
using std::endl;

int main()
{

 long long  n,i;
 cin>>n;

 long long arr[n];**strong text**
 for(i=0;i<n;i++){
  cin>>arr[n];
 }
 long long index=0;
 for(i=1;i<n;i++)
 {
   if(arr[i]>arr[index])
   {
     index=i;
   }
   else
   continue;
 }

 for(i=0;i<n;i++){
  cout<<arr[i]<<endl;    
 }
}

Eg:- Input:- 5

12 33 22 11 5

Output:-

84785773116751

8476457385632857804

8065190381340

208132006536

18037221972114776

Can Anyone explain me why I am getting such weird output when all I did just print my array without changing it's value?

C++ 11 thread_local and "foreign" threads

I would like to use C++ 11 thread_local, but our application embeds a JVM, and sometimes C++ methods are called from Java-created thread via JNI. This could be the same thing as if an external "C" library created a thread and called back into my C++ code. Is the behavior of thread_local variables defined under these circumstances? Is there any way for my code to compensate for the unexpected appearance of a foreign thread? What about destruction on thread exit? Thanks john

Loop over template types

I have a function with two template arguments, one for a vector data type (int, float, double, etc.) and one for an integer type (int, int16_t, uint32_t, etc.):

template <typename T, typename I>
void
add(std::vector<T> array, std::vector<I> idx) {
  // ...
}

For tests, I would now like to loop over every possible combination of data/integer types, e.g.,

// pseudo code
for I in [int, int16_t, int32_t, ...] {
    for T in [float, double, int, int16_t, ...] {
        // create arguments a, b
        add<T, I>(a, b);
    }
}

Is it possible to loop over types at all? How?

I'm getting " no match for 'operator[]' 'std::vector

vector<int>g2[10000];
    for(int u=0;u<N;u++) //N is the number of vertices
      { for(vector<int>::iterator it=v[u].begin();it!=v[u].end();it++) 
          {g2[v[*it]].push_back(u);}}

//v is of vectorv[1000],it consists a adjaceny list representation of a graph

Im getting the error->

     prog.cpp:74:8: error: no match for 'operator[]' (operand types are 'std::vector<int> [10001]' and 'std::vector<int>')
   g2[v[*it]].push_back(u);
    ^    

can you guys please help me!

Why do infinite loops delay printing? [duplicate]

This question already has an answer here:

This is a backstory, you can skip to the question in bold below if you don't wanna read it.

Recently while solving a problem I accidentally had an infinite loop in it. But I didn't know so I tried to debug the code, and obviously a good way to debug ( or at least a way that I'm used to ) is to place a few flags in the code, that would print to the console that the program has finished successfully until that part. But later I saw that even when I place the flag as the first thing in the program, it still wouldn't print anything. I managed to fin the bug by using return 0 instead of placing flags, but this got me wondering,

Why doesn't the following program print "A" right away?

#include<bits/stdc++.h>
using namespace std;
int main(){
    cout<<"A";
    int k=1;
    while(k)k++;
}

vendredi 29 juin 2018

C/C++ regexec crashes with compiler optimization -Og

I have a C/C++ function that uses regexec function. When optimization -Og was specified, it crashed. If -Og was deleted, it worked fine. Any one help for a solution? Thanks

Initializing a union with anonymous structs

I am merging together a tree structure into a library. The library in question has a compile time check prevent users from leaving uninitialized variables while merging, among other checks. The tree structure I am trying to merge has the a structure like

struct TreeNode
{
  int Dimension;
  int ChildIndex;
  union {
    struct
    { 
      float LMax;
      float RMin;
    } Node;
    struct
    {
      int Start;
      int Size;
    } Leaf;
  };

  TreeNode()
    : Dimension()
    , ChildIndex()
  {}
};

When I have this class merged, and I compile the library, I get -Wmissing-field-initializers warnings for the union which is not initialized by me.

I am looking for a way to initialize the union in the constructor of the TreeNode. Can anyone please point me to how this could be done? I also seek advice if the TreeNode can be structured in a better way.

C++ vector not storing class

I am writing a simple feed-forward neural network in c++, however when I try to store my neuron class in my layer structure, it crashes and gives this output:

terminate called after throwing an instance of 'std::bad_array_new_length'

what(): std::bad_array_new_length

This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.

Here is my program:

#include <iostream>
#include <random>
#include <vector>
using namespace std;
random_device e;

int randomG(int min, int max){
  return (e()%(max-min))+min;
}

int f(int v){
  return v+5;
}

class neuron{
public:
  neuron(int _insN, int _funtype){
    insN=_insN;funtype=_funtype;
  }
  float out;
  void genWeights(){
    for (int i = 0; i < insN; i++){
      weights[i]=float(randomG(1,1000))/100;
    }
  }
  float parceOut(float* ins){
    float preOut=0;
    for (int i = 0; i < insN; ++i){
      preOut+=(weights[i]*ins[i]);
    }
    out=activation(preOut, funtype);
  }
private:
  float ReLU(float f){
    if (f<=0){return f*0.01;}
    else {return f;}
  }
  float Softmax(float f){
    return f;
  }
  float activation(float f, int function){
    switch(function){
    case(1): return ReLU(f); break;
    case(2): return f; break;
    case(3): return Softmax(f); break;
    }
  }
  int insN;
  int funtype;
  float* weights = new float[insN];
};

struct layer{
  int insN=1, neuronN=1;
  float* outs=new float[neuronN];
  vector<neuron> nS;
  void generateNeurons(){
    for(int i=0;i<1;i++){
      nS.push_back(neuron(insN,1));
    }
  }
};

int main(int argc, char *argv[])
{
  layer input;
  input.insN=1;
  input.neuronN=5;
  input.generateNeurons();
  cin.get();
  return 0;
}

I don't think that it is to hard to understand, but if it is I am trying to make a vector with my neuron class in my layer structure, but even when I put just one neuron in the vector it says that there is not enough memory allocated to the program. I have tried converting the neuron class into a structure, but that did not help.

decltype((void)T{}) in template Partial Specialization not deduce?

template<typename T,typename U = void>
struct Test
{
    static const int value = 0;
};
template<typename T>
struct Test<T, decltype((void)T{})>
{
    static const int value = 2;
};

template<typename T>
struct Test<T*,  decltype((void)T{})>
{
    static const int value = 1;
};

int main(){       
   cout<<Test<int*>::value<<endl;
    return 0;
}

code on gcc/clang both get error:ambiguous ,but decltype change to void_t is ok.why?

Combine multiple class template specializations

Given the example below, what's the best way to condense the template specializations such that one or two instructions would suffice to define all of the special values? Variadics, perhaps?

enum class PositiveDigit
{ Zero, One, Two, Three, Four, Five, Six, Seven, Eight, Nine };

// Base class template
template <std::underlying_type_t<PositiveDigit>>
struct IsNum
{ static constexpr bool aPrimeDigit = false; };

// Specialized class templates to define which positive digits are prime 
// HOW TO BEST COMBINE/CONDENSE THESE? VARIADIC?? Ideally, something like:
//    template <PositiveDigit::One, PositiveDigit::Two, ……> ……   OR,
//    template <> …… (PositiveDigit::One, PositiveDigit::Two, ……) ……   OR??
template <>
struct IsNum<static_cast<std::underlying_type_t<PositiveDigit>>(PositiveDigit::One)>
{ static constexpr bool aPrimeDigit = true; };
template <>
struct IsNum<static_cast<std::underlying_type_t<PositiveDigit>>(PositiveDigit::Two)>
{ static constexpr bool aPrimeDigit = true; };
template <>
struct IsNum<static_cast<std::underlying_type_t<PositiveDigit>>(PositiveDigit::Three)>
{ static constexpr bool aPrimeDigit = true; };
template <>
struct IsNum<static_cast<std::underlying_type_t<PositiveDigit>>(PositiveDigit::Five)>
{ static constexpr bool aPrimeDigit = true; };
template <>
struct IsNum<static_cast<std::underlying_type_t<PositiveDigit>>(PositiveDigit::Seven)>
{ static constexpr bool aPrimeDigit = true; };

int main() {
    // Note: It's perfectly okay to pass integers beyond the range of the
    //  enum class, they'll simply provide a false result
    IsNum<-5>::aPrimeDigit; // false
    IsNum<13>::aPrimeDigit; // false
    IsNum< 7>::aPrimeDigit; // true!
}

Please assume as given that the enum must remain strongly-typed. The real-world issue has a large enum class, many potential specializations, and has nothing whatsoever to do with digits or primes; this was just a simple example.

These similar questions don't appear to address the issue at hand (unless I'm missing something):

2D array removes its elements after exiting the loop

Input is: hello world
The following program should record "hello" in words[0] and "world in words[1]

int rowIndex= 0;
char words [100][100];
for (int x = 0 ; x < input.length(); x++)
{
  if (input[x]>='a'&&input[x]<='z' || input[x]>='A'&&input[x]<='Z')
 // This condition is to avoid recording spaces in the array
  {
      words[rowIndex][x]= input[x];
      cout << words[rowIndex][x]<<" ";
  }
  else {
    rowIndex++;
    // Once it finds a space, it records the following characters into the next index
    cout << " Index: " << rowIndex <<endl;
  }
}

output:
h e l l o
Index: 1
w o r l d

cout <<"Index 0: "<< words[0] <<endl;

Output: hello

cout <<"Index 1: "<< words[1] <<endl;

Output: " doesn't output anything" ( Why doesn't it output "world")
*****************************************************
Why doesn't the array hold the characters in words[1] and only holds the characters in words[0]
Note: I tried doing it with dynamic 2D array and same problem happened.

C++ Break out of a function at an early stage

I have two questions. The first is about working with functions. I need to break out of a function at an early stage under a condition.

For example:

std::string concat(std::string& x, std::string& y, std::vector<std::string>& vec)
{
    if (atoi(x.c_str()) < 0)
    {
        return;
    }
    else {
        std::string concatStr = y + x;

        top_back(vec);
        top_back(vec);

        return concatStr;
    }
}

As you can see, the function must return a string, but if the string x(which i of course convert to int) is less than 0, then i theoretically should break out of the function.

The problem with writing just return; is that the compiler tells me that it needs to return a value.

The second question is how can i remove the last line from the console? That's connected with the first question, as someone suggested that return ""; is a good workaround, but it writes a blank space into the console, which in my case with the program i'm writing is not good and causes problems.

Conversion operator vs deleted constructor

Please see the following code:

struct X;

struct Y {
  Y() {}
  Y(X&) = delete;
};

struct X {
  X() {}
  operator Y() {
    return{};
  }
};

int main() {
  X x;
  static_cast<Y>(x);
}

Here, the Y's constructor taking an X is explicitly deleted, while X has a conversion operator into Y. Among these directly contradicting two, it seems that =delete always win; I tested on some recent versions of GCC, Clang, and VC++.

The question: is it the "right" behavior? I thought there is no particular precedence between conversion constructor and conversion operator, so the code above should produce an overload resolution ambiguity error. But it doesn't. It complains about usage of the deleted function. Is it because of the guaranteed copy elision?

I googled and found Conversion constructor vs. conversion operator: precedence. In that question, the conversion operator has been chosen because it was a better match due to presence of const in the conversion constructor. However, in my case replacing Y(X&) to Y(X const&) changed nothing.


Actually, the situation I want to have is the following:

X x;
Y y1(x);                  // Error
Y y2 = static_cast<Y>(x); // OK

Yes, one may call this silly, but indeed there are built-in types that behave just like that: substitute X <- int&, Y <- int&&. Inability to make a user-defined type that exactly mimics a built-in reference type seems to be a really desperately missing piece in current C++...

ifstream checking read error

I found the following code for reading whole file into a string. Unfortunately, I do no know how to properly check if whole file content has been loaded. There is is_open function, however it does not provide all information. Will be grateful for any help!

std::ifstream file(fileName);
std::string content = std::string((
  std::istreambuf_iterator<char>(file)),
  std::istreambuf_iterator<char>());

Move constructor comment not getting printed

I have a small program like below:

    class boovector{
    private: int size;
            char *arr;
    public:
            boovector(){size=1;arr=new char[size];cout<<" boovector default constructor called"<<endl;}
            boovector(const boovector &b)
            {
                cout<<"boovector copyconstructor called"<<endl;
                size = b.size;
                arr =  new char[size];
                strncpy(arr,b.arr,size);
            }
            boovector(boovector &&b)
            {
                cout<<"boovector move assignment operator called"<<endl;
                size =b.size;
                arr = b.arr;
                b.arr = nullptr;
            }
            ~boovector()
            {
                delete []arr;
            }

    };
    boovector createboovector()
    {
        boovector v;
        return v;
    }
    void foo(boovector v)
    {

    }
    int main(int argc, char *argv[])
    {
        boovector vet = createboovector();
        foo(vet);
        foo(createboovector());
        return 0;
    }

Output

boovector default constructor called
boovector copyconstructor called
boovector default constructor called

I was hoping to see "boovector move assignment operator called" in the output.

If I comment move constructor "boovector(boovector &&b)", i get compiler error

  invalid initialization of non-const reference of type 'boovector&' from an 
  rvalue of type 'boovector'

I want to understand the logic behind the move constructor not being called.

Initialize a string vector using 2 strings ("June","July") and Create a dynamic 2D char array that can store 2 strings in c++

Initialize a string vector using 2 strings ("June","July")

Create a dynamic 2D char array that can store 2 strings and copy the above strings from vector to the array.

Prevent any memory leakage using proper allocation and dealloction method.

Ans: I've wrote some code but couldn't arrive the solution when copying the vector data to array, below is the code which i'm trying.

Customizing QComboBox

I want to customize QComboBox. The behavior I'd like to see is a combo box where it's button (the down facing arrow), takes the whole area of the combo box when it's collapsed. I know that QComboBox is a QPushButton with a QListWidget (or some other widget). I'd like to change the QPushButton to take up the whole area. I'd like to also get rid of the area where the current selection is being displayed. Any tips will be appreciated!

Defining a code section within which a different code path is executed

Is it possible to define a section or scope in my code within which a different code path is executed, without using a global or passed-down state variable?

For debugging purposes, I want to be able to surround a section of faulty code with a scope or #define to temporarily switch on pre-defined debugging behavior within this section, e.g. use debug data, a more precise data type, an already validated algorithm, … This needs to work in a multi-threaded application in which multiple threads will likely execute the same shared code concurrently, but only some of them have called this code from within the defined section.

For example, here is some pseudo-code that is not working, but might illustrate what I'd like to do. A static expensive function that is called from several places concurrently:

Result Algorithms::foo()
{
#ifdef DEBUG_SECTION
    return Algorithms::algorithmPrecise(dataPrecise);
#else
    return Algorithms::algorithmOptimized(dataOptimized);
#endif
}

Three classes of which instances need to be updated frequently:

Result A::update()
{
    return Algorithms::foo();
}

Result B::update()
{
    Result result;

#define DEBUG_SECTION
        ...

        result = a.update() + 1337;

        ...
#undef DEBUG_SECTION

    return result;
}

Result C::update()
{
    return a.update();
}

As you can see, class A directly calls foo(), whereas in class B, foo() is called indirectly by calling a.update() and some other stuff. Let us assume B::update() returns a wrong result, so I want to be able to use the debug implementation of foo() only from this location. In C::update(), the optimized version should still be used.

My conceptual idea is to define a DEBUG_SECTION around the faulty code which would use the debug implementation at this location. This, however, does not work in practice, as Algorithms::foo() is compiled once with DEBUG_SECTION not being defined. In my application, Algorithms, A, B, and C are located in separate libraries.

I want that within a section defined in the code, a different code section within shared code is executed. However, outside of this section I still want execution of the original code, which at runtime will happen concurrently, so I cannot simply use a state variable. I could add a debugFlag parameter to each call within the DEBUG_SECTION that is passed down in each recursive call that is then provided to Algorithms::foo(), but this is extremely prone to errors (you must not miss any calls, but the section could be quite huge, spread over different files, …) and quite messy in a larger system. Is there any better way to do this?

I need a solution for C++11 and MSVC.

Multi threaded rendering (command buffer generation) in Vulkan is slower than single threaded

I am trying to implement multi threaded command buffer generation (using per-thread command pool and secondary command buffers), but there are little performance gain of using multiple threads.

First, I thought that my thread pool code was incorrectly written, but I tried Sascha Willems's thread pool implementation, and nothing changed (so I don't think that's an issue)

Second, I searched for multi threading performance issues and I found that accessing same variables/resources from different thread causes performance drop, but still i can't figure out the problem in my case.

I also downloaded Sascha Willems's multi threading code, run it, and it worked just fine. I modified the number of working threads and the performance gain using multiple threads is clearly visible.

Here are some FPS results for rendering 600 objects (same model). You can see what my problem is:

core count      Sascha Willems's        my result
              result ( avg. FPS)       (avg. FPS)

    1               45                      30
    2               83                      33
    4               110                     40
    6               155                     42
    8               162                     42
    10              173                     40
    12              175                     40

This is where i prepare the thread data

void prepareThreadData
{
primaryCommandPool = m_device.createCommandPool (
    vk::CommandPoolCreateInfo (
        vk::CommandPoolCreateFlags(vk::CommandPoolCreateFlagBits::eResetCommandBuffer),
        graphicsQueueIdx
    )
);

primaryCommandBuffer = m_device.allocateCommandBuffers (
    vk::CommandBufferAllocateInfo (
        primaryCommandPool,
        vk::CommandBufferLevel::ePrimary,
        1
    )
)[0];

threadData.resize(numberOfThreads);

for (int i = 0; i < numberOfThreads; ++i)
{
    threadData[i].commandPool = m_device.createCommandPool (
        vk::CommandPoolCreateInfo (
            vk::CommandPoolCreateFlags(vk::CommandPoolCreateFlagBits::eResetCommandBuffer),
            graphicsQueueIdx
        )
    );

    threadData[i].commandBuffer = m_device.allocateCommandBuffers (
        vk::CommandBufferAllocateInfo (
            threadData[i].commandPool,
            vk::CommandBufferLevel::eSecondary,
            numberOfObjectsPerThread
        )
    );

    for (int j = 0; j < numberOfObjectsPerThread; ++j)
    {
        VertexPushConstant pushConstant = { someRandomPosition()};
        threadData[i].pushConstBlock.push_back(pushConstant);
    }
}
}

Here is my render loop code where i give job for each thread:

while (!display.IsWindowClosed())
{
display.PollEvents();

m_device.acquireNextImageKHR(m_swapChain, std::numeric_limits<uint64_t>::max(), presentCompleteSemaphore, nullptr, &currentBuffer);

primaryCommandBuffer.begin(vk::CommandBufferBeginInfo());
primaryCommandBuffer.beginRenderPass(
    vk::RenderPassBeginInfo(m_renderPass, m_swapChainBuffers[currentBuffer].frameBuffer, m_renderArea, clearValues.size(), clearValues.data()),
    vk::SubpassContents::eSecondaryCommandBuffers);

vk::CommandBufferInheritanceInfo inheritanceInfo = {};
inheritanceInfo.renderPass = m_renderPass;
inheritanceInfo.framebuffer = m_swapChainBuffers[currentBuffer].frameBuffer;

for (int t = 0; t < numberOfThreads; ++t)
{
    for (int i = 0; i < numberOfObjectsPerThread; ++i)
    {
        threadPool.threads[t]->addJob([=]
        {
            std::array<vk::DeviceSize, 1> offsets = { 0 };
            vk::Viewport viewport = vk::Viewport(0.0f, 0.0f, WIDTH, HEIGHT, 0.0f, 1.0f);
            vk::Rect2D renderArea = vk::Rect2D(vk::Offset2D(), vk::Extent2D(WIDTH, HEIGHT));

            threadData[t].commandBuffer[i].begin(vk::CommandBufferBeginInfo(vk::CommandBufferUsageFlagBits::eRenderPassContinue, &inheritanceInfo));
            threadData[t].commandBuffer[i].setViewport(0, viewport);
            threadData[t].commandBuffer[i].setScissor(0, renderArea);
            threadData[t].commandBuffer[i].bindPipeline(vk::PipelineBindPoint::eGraphics, m_graphicsPipeline);
            threadData[t].commandBuffer[i].bindVertexBuffers(VERTEX_BUFFER_BIND, 1, &model.vertexBuffer, offsets.data());
            threadData[t].commandBuffer[i].bindIndexBuffer(model.indexBuffer, 0, vk::IndexType::eUint32);
            threadData[t].commandBuffer[i].pushConstants(pipelineLayout, vk::ShaderStageFlagBits::eVertex, 0, sizeof(VertexPushConstant), &threadData[t].pushConstBlock[i]);
            threadData[t].commandBuffer[i].drawIndexed(model.indexCount, 1, 0, 0, 0);
            threadData[t].commandBuffer[i].end();
        });
    }
}

threadPool.wait();

std::vector<vk::CommandBuffer> commandBuffers;
for (int t = 0; t < numberOfThreads; ++t)
{
    for (int i = 0; i < numberOfObjectsPerThread; ++i)
    {
        commandBuffers.push_back(threadData[t].commandBuffer[i]);
    }
}

primaryCommandBuffer.executeCommands(commandBuffers.size(), commandBuffers.data());
primaryCommandBuffer.endRenderPass();
primaryCommandBuffer.end();

submitQueue(presentCompleteSemaphore, primaryCommandBuffer);
}

If you have any idea on what am I missing / what i'm doing wrong, please let me know.

Fast random string

I'm trying to generate random string ID for a program (the ID has to be unique only during the execution of the program). I first did it in Python without any issue :

class RandomIdGenerator:
    _base_62_chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

    @classmethod
    def get_base_62(cls, length):
        return "".join([random.choice(RandomIdGenerator._base_62_chars) for _ in range(length)])

But as I need my program to be in C++, I'm trying to generate the same string with it. This is what I do now :

void Node::setId()
{
    QString allow_symbols("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
    qsrand(QTime::currentTime().msec());

    for (int i = 0; i < ID_LENGTH; ++i) {
        id_.append(allow_symbols.at(qrand() % (allow_symbols.length())));
    }
}

I have two main issues with it. First it doesn't use C++11 (I don't know how Qt works but I don't think it's C++11) and the ID generated are all the same. If I generate four of them I get :

"R4NDM1xM"
"R4NDM1xM"
"R4NDM1xM"
"R4NDM1xM"

I tried using the C++11 method but I got the same result, even worse, at each execution, I got the exact same result :

void Node::setId()
{
    id_ = "";

    const std::string str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    std::random_device rd;
    std::mt19937 generator(rd);
    std::uniform_int_distribution<int> dist(0, str.size() - 1);

    for (int i = 0; i < Node::ID_LENGTH; ++i)
        id_ += str[dist(generator)];
}

How can I generate random string ID at each call of a method?

Variadic templates have duplicate symbols in object files?

I have the following test program:

#include <cstdio>

template<int i, int j, int k>
struct Dispatcher {
  template<typename... F>
  static inline void call1(bool a, bool b, int* output, F...) {
    *output = i;
    if (a) *output += j;
    if (b) *output += k;
  }

  template<typename F>
  static inline void call2(bool a, bool b, int* output, F) {
    *output = i;
    if (a) *output += j;
    if (b) *output += k;
  }
};


int main() {
  int output;
  Dispatcher<1, 2, 3>::call1(true, false, &output, 1337);
  printf("%i\n", output);
  Dispatcher<1, 2, 3>::call2(true, false, &output, 1337);
  printf("%i\n", output);
  return 0;
}

The program builds and runs as expected, but "nm -C" shows that it contains the following symbols:

000000000040065a W void Dispatcher<1, 2, 3>::call1<int>(bool, bool, int*, int)
000000000040065a W void Dispatcher<1, 2, 3>::call1<int>(bool, bool, int*, int)
00000000004006a4 W void Dispatcher<1, 2, 3>::call2<int>(bool, bool, int*, int)

Without unmangling, they are:

000000000040065a W _ZN10DispatcherILi1ELi2ELi3EE5call1IIiEEEvbbPiDpT_
000000000040065a W _ZN10DispatcherILi1ELi2ELi3EE5call1IJiEEEvbbPiDpT_
00000000004006a4 W _ZN10DispatcherILi1ELi2ELi3EE5call2IiEEvbbPiT_

Why does the function "call1" show up twice but "call2" shows up only once? It looks like it has something to do with the variadic template argument...

I am building using gcc version 4.8.5 with the "-std=c++11 -O0" flags. (I get the issue even with -03 in my real code but the test program gets inlined without -O0.)

How can I fix this error "the value of 'x1' is not usable in a constant expression" ? static_assert

Given the following code ( only for the example) :

    int x1 = 4;
    int x2 = 5;
    static_assert(x1 != x2 ,"Error");

I get the following error:

the value of 'x1' is not usable in a constant expression

How can I fix it ?


Note: I looking for a way to fix it without change the definitions of the variables in this way:

const int x1 = 4;
const int x2 = 5;

But, I want to fix it only by change the the line of static_assert(..)

Do a file containing words separated by newline and a vector of strings for those words in C++ have same size?

The file is of the following form:

word1
word2
word3
...

And I create vector of strings after reading those words from the file like this:

std::vector<string> words;
string w;
ifstream file("input");
while(getline(file,w))
    words.push_back(w);
file.close();

Will the size of physical memory occupied by the vector be same as the size of input file? Why?

gsl_function alternative for c++

I am switching from C to C++, and I would like to optimally use the additional features that become available and avoid things considered 'C-style' like void * pointers. Specifically, I am trying to make a gsl_function-like interface (NOT a wrapper to use gsl in C++).

In C, I wrote several routines for root-finding, integration ... that use a gsl_function-like interface to pass mathematical functions to these routines. This interface looks like this:

struct Function_struct
{
  double (* p_func) (double x, void * p_params);
  void * p_params;
};
typedef struct Function_struct Function;

#define FN_EVAL(p_F,x) (*((p_F)->p_func))(x,(p_F)->p_params)

and can be used in the following way:

struct FuncParams_struct { double a; double b; double c; };

double my_sqrt(double x, void * p) {
    struct FuncParams_struct * p_params = (struct FuncParams_struct *) p;
    double a = p_params->a;
    double b = p_params->b;
    double c = p_params->c;

    return a/sqrt(x+b)+c;
}

Function My_Sqrt;
My_Sqrt.p_func = &my_sqrt;
struct FuncParams_struct my_params = { 1.0, 1.0, 0.0 };
My_Sqrt.p_params = &my_params;

// Call the function at a certain x
double result_at_3 = FN_EVAL(&My_Sqrt, 3);

// Pass My_Sqrt to an integration routine 
// (which does not care about the parameters a,b,c 
// and which can take any other Function to integrate)
// It uses FN_EVAL to evaluate MySqrt at a certain x.
double integral = integrate(&My_Sqrt);

// Easily change some of the parameters
My_Sqrt.p_params->a=3.0;

As you can see, this allows me to create an instance of the Function structure, which contains a pointer to some function parameters (which are typically contained within another structure) and a pointer to a 'normal' C function. The great thing about this is that the routines that use Function only need to know that it is a function that takes a double and returns a double (they use the FN_EVAL macro). They do not have to care about the type and number of parameters. On the other hand, I can easily change the values stored in the parameters from outside of the routines.

I would now like to have the features highlighted above in a C++ Function. I searched a lot for what would be the best way to get this, but I could not find it (partly because I am a bit overwhelmed by the possibilities of C++ as compared to C). Thus far, I was thinking to make a class Function. This class could than store the actual function definition and it could be made callable by defining the operator(), such that again routines do not have to care about the parameters. The operator() could thus be used instead of the FN_EVAL macro.

The things that I could not yet decide/find are:

  • how I would store the parameters. I was thinking about using a template typename. However, as far as I understand, then also the class itself needs to be a template, in which case also the routines should accept a templated class. I do not want to use a void *.
  • how I would change the parameters that are stored in my class Function. Should I make them public such that I can easily change them, or should I keep them private and write some interface to access them? In the latter case, how should I go about this? Since I will be considering a large variety of parameters (both in number and in type).

Things to consider:

  • I found a lot of questions and answers about wrappers to use gsl-routines within C++. That is not what I am looking for.
  • I also looked at the STL <functional>. As far as I could figure out, it does not fulfill my requirements for the parameters that I can store within the Function. However, I can be wrong about this.
  • My functions can be rather complex (i.e., not just one-line things like the example above) and the parameters can themselves contain a mixture of doubles, ints, structures...
  • I would like to have the possibility to extend the Function class to higher dimensions, i.e. f(x,y,z). In C, I had for example

    struct FunctionThree_struct
    {
      double (* p_func) (double x, double y, double z, void * p_params);
      void * p_params;
    };
    typedef struct FunctionThree_struct FunctionThree;
    #define FN_THREE_EVAL(p_F,x,y,z) (*((p_F)->p_func))(x,y,z,(p_F)->p_params)
    
    
  • I do care about efficient function calls. Especially for higher dimensional integrals, the functions will be called millions of times.

How can I check that function really get a variable that defined as const?

Given the following code:

template <class Func>
void f(Func f , int* param){
   f(/* how can I send "param" as const "int*" */);
}

How can I do it so that if f don't get the variable as const - so we will get error ?

Using SFINAE to resolve allocator member conditionally

I am writing a constructor for a list data structure.

template <class T, class Allocator = std::allocator<T>>
class list {

...
}

The class takes an Allocator template parameter and defaults to std::allocator if none is provided. Since C++11 allocators may have state the default constructor also takes an allocator object.

//    *** CONSTRUCTORS ***
explicit list(const Allocator& alloc = Allocator()): alloc_(alloc), head_(nullptr), tail_(nullptr), size_(0) {
    if(std::is_same<Allocator, customAllocator<T>>::value) {
        std::cout << "****" << std::endl;
        std::cout << alloc.member_ << std::endl;
        std::cout << alloc_.member_ << std::endl;
        std::cout << "****" << std::endl;
    }
}

When a custom allocator that contains 'member_' is provided the following lines execute without failure.

However when a std::allocator is passed the compiler understandably complains that there is no member 'member_' in the allocator.

However is there a way so that the std::cout lines are printed when a custom allocator is provided and not printed when the std::allocator (or any allocator without 'member_') is provided?

Thank you

jeudi 28 juin 2018

Manually place a toolbar Qt c++

My QMainWindow contains three different windows. I would like to display three different toolbars. One for each window. For now I display a toolbar but I can not place it just above my windows. I wanted to know if it was possible?

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent) {
    //here I declared a widget and my three windows.
    QToolBar *toolBar= addToolBar("window");
    addLine=new QAction("Add Line",this);
    removeLine=new QAction("Remove line",this);
    removeAll=new QAction("Remove all",this);
    toolBar->addAction(addLine);
    toolBar->addAction(removeLine);
    toolBar->addAction(removeAll);
}

Why does std::conditional_variable as a class member cause compile errors with std::thread?

I tried including std::conditional_variable as a class member, and got a lot of compilation errors when passing an object of this class to a std::thread. I cut down all the other code from my actual program, and ended up with the below minimal code. Removing the std::conditional_variable causes no problems. I tried "initializing" the variable in the constructor, as well as making it inline, but neither helped.

#include <thread>
#include <condition_variable>

struct ThreadHandler {
    void operator()() { }

    std::condition_variable cond; 
};

int main() {
    ThreadHandler th1;
    std::thread t1(th1);
    t1.join(); 
}

What am I doing wrong here?

Below is the compilation error I get:

In file included from main.cpp:1:
/usr/local/include/c++/8.1.0/thread: In instantiation of ‘static std::thread::_Invoker<std::tuple<typename std::decay<_Tp>::type, typename std::decay<_Args>::type ...> > std::thread::__make_invoker(_Callable&&, _Args&& ...) [with _Callable = ThreadHandler&; _Args = {}; typename std::decay<_Tp>::type = ThreadHandler]’:
/usr/local/include/c++/8.1.0/thread:127:22:   required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = ThreadHandler&; _Args = {}]’
main.cpp:14:23:   required from here
/usr/local/include/c++/8.1.0/thread:258:4: error: no matching function for call to ‘std::tuple<ThreadHandler>::tuple(<brace-enclosed initializer list>)’
  } };
    ^
In file included from /usr/local/include/c++/8.1.0/bits/unique_ptr.h:37,
                 from /usr/local/include/c++/8.1.0/memory:80,
                 from /usr/local/include/c++/8.1.0/thread:39,
                 from main.cpp:1:
/usr/local/include/c++/8.1.0/tuple:828:11: note: candidate: ‘template<class _Alloc, class _Dummy, class ... _UElements, typename std::enable_if<((std::_TC<((1 == sizeof... (_UElements)) && (! std::is_same<std::tuple<ThreadHandler>, std::tuple<_Tail ...> >::value)), ThreadHandler>::_MoveConstructibleTuple<_UElements ...>() && (! std::_TC<((1 == sizeof... (_UElements)) && (! std::is_same<std::tuple<ThreadHandler>, std::tuple<_Tail ...> >::value)), ThreadHandler>::_ImplicitlyMoveConvertibleTuple<_UElements ...>())) && std::_TC<(std::is_same<_Dummy, void>::value && (1 == 1)), ThreadHandler>::_NonNestedTuple<tuple<_Tail ...>&&>()), bool>::type <anonymous> > std::tuple<_Elements>::tuple(std::allocator_arg_t, const _Alloc&, std::tuple<_Args2 ...>&&)’
  explicit tuple(allocator_arg_t __tag, const _Alloc& __a,
           ^~~~~
/usr/local/include/c++/8.1.0/tuple:828:11: note:   template argument deduction/substitution failed:
In file included from main.cpp:1:
/usr/local/include/c++/8.1.0/thread:258:4: note:   candidate expects 3 arguments, 1 provided
  } };
    ^
In file included from /usr/local/include/c++/8.1.0/bits/unique_ptr.h:37,
                 from /usr/local/include/c++/8.1.0/memory:80,
                 from /usr/local/include/c++/8.1.0/thread:39,
                 from main.cpp:1:
/usr/local/include/c++/8.1.0/tuple:813:2: note: candidate: ‘template<class _Alloc, class _Dummy, class ... _UElements, typename std::enable_if<((std::_TC<((1 == sizeof... (_UElements)) && (! std::is_same<std::tuple<ThreadHandler>, std::tuple<_Tail ...> >::value)), ThreadHandler>::_MoveConstructibleTuple<_UElements ...>() && std::_TC<((1 == sizeof... (_UElements)) && (! std::is_same<std::tuple<ThreadHandler>, std::tuple<_Tail ...> >::value)), ThreadHandler>::_ImplicitlyMoveConvertibleTuple<_UElements ...>()) && std::_TC<(std::is_same<_Dummy, void>::value && (1 == 1)), ThreadHandler>::_NonNestedTuple<tuple<_Tail ...>&&>()), bool>::type <anonymous> > std::tuple<_Elements>::tuple(std::allocator_arg_t, const _Alloc&, std::tuple<_Args2 ...>&&)’
  tuple(allocator_arg_t __tag, const _Alloc& __a,
  ^~~~~
/usr/local/include/c++/8.1.0/tuple:813:2: note:   template argument deduction/substitution failed:
In file included from main.cpp:1:
/usr/local/include/c++/8.1.0/thread:258:4: note:   candidate expects 3 arguments, 1 provided
  } };
    ^
In file included from /usr/local/include/c++/8.1.0/bits/unique_ptr.h:37,
                 from /usr/local/include/c++/8.1.0/memory:80,
                 from /usr/local/include/c++/8.1.0/thread:39,
                 from main.cpp:1:
/usr/local/include/c++/8.1.0/tuple:798:11: note: candidate: ‘template<class _Alloc, class _Dummy, class ... _UElements, typename std::enable_if<((std::_TC<((1 == sizeof... (_UElements)) && (! std::is_same<std::tuple<ThreadHandler>, std::tuple<_Tail ...> >::value)), ThreadHandler>::_ConstructibleTuple<_UElements ...>() && (! std::_TC<((1 == sizeof... (_UElements)) && (! std::is_same<std::tuple<ThreadHandler>, std::tuple<_Tail ...> >::value)), ThreadHandler>::_ImplicitlyConvertibleTuple<_UElements ...>())) && std::_TC<(std::is_same<_Dummy, void>::value && (1 == 1)), ThreadHandler>::_NonNestedTuple<tuple<_Tail ...>&&>()), bool>::type <anonymous> > std::tuple<_Elements>::tuple(std::allocator_arg_t, const _Alloc&, const std::tuple<_Args2 ...>&)’
  explicit tuple(allocator_arg_t __tag, const _Alloc& __a,
           ^~~~~
/usr/local/include/c++/8.1.0/tuple:798:11: note:   template argument deduction/substitution failed:
In file included from main.cpp:1:
/usr/local/include/c++/8.1.0/thread:258:4: note:   candidate expects 3 arguments, 1 provided
  } };
    ^
In file included from /usr/local/include/c++/8.1.0/bits/unique_ptr.h:37,
                 from /usr/local/include/c++/8.1.0/memory:80,
                 from /usr/local/include/c++/8.1.0/thread:39,
                 from main.cpp:1:
/usr/local/include/c++/8.1.0/tuple:783:2: note: candidate: ‘template<class _Alloc, class _Dummy, class ... _UElements, typename std::enable_if<((std::_TC<((1 == sizeof... (_UElements)) && (! std::is_same<std::tuple<ThreadHandler>, std::tuple<_Tail ...> >::value)), ThreadHandler>::_ConstructibleTuple<_UElements ...>() && std::_TC<((1 == sizeof... (_UElements)) && (! std::is_same<std::tuple<ThreadHandler>, std::tuple<_Tail ...> >::value)), ThreadHandler>::_ImplicitlyConvertibleTuple<_UElements ...>()) && std::_TC<(std::is_same<_Dummy, void>::value && (1 == 1)), ThreadHandler>::_NonNestedTuple<tuple<_Tail ...>&&>()), bool>::type <anonymous> > std::tuple<_Elements>::tuple(std::allocator_arg_t, const _Alloc&, const std::tuple<_Args2 ...>&)’
  tuple(allocator_arg_t __tag, const _Alloc& __a,
  ^~~~~
/usr/local/include/c++/8.1.0/tuple:783:2: note:   template argument deduction/substitution failed:
In file included from main.cpp:1:
/usr/local/include/c++/8.1.0/thread:258:4: note:   candidate expects 3 arguments, 1 provided
  } };
    ^
In file included from /usr/local/include/c++/8.1.0/bits/unique_ptr.h:37,
                 from /usr/local/include/c++/8.1.0/memory:80,
                 from /usr/local/include/c++/8.1.0/thread:39,
                 from main.cpp:1:
/usr/local/include/c++/8.1.0/tuple:771:2: note: candidate: ‘template<class _Alloc> std::tuple<_Elements>::tuple(std::allocator_arg_t, const _Alloc&, std::tuple<_Elements>&&)’
  tuple(allocator_arg_t __tag, const _Alloc& __a, tuple&& __in)
  ^~~~~
/usr/local/include/c++/8.1.0/tuple:771:2: note:   template argument deduction/substitution failed:
In file included from main.cpp:1:
/usr/local/include/c++/8.1.0/thread:258:4: note:   candidate expects 3 arguments, 1 provided
  } };
    ^
In file included from /usr/local/include/c++/8.1.0/bits/unique_ptr.h:37,
                 from /usr/local/include/c++/8.1.0/memory:80,
                 from /usr/local/include/c++/8.1.0/thread:39,
                 from main.cpp:1:
/usr/local/include/c++/8.1.0/tuple:767:2: note: candidate: ‘template<class _Alloc> std::tuple<_Elements>::tuple(std::allocator_arg_t, const _Alloc&, const std::tuple<_Elements>&)’
  tuple(allocator_arg_t __tag, const _Alloc& __a, const tuple& __in)
  ^~~~~
/usr/local/include/c++/8.1.0/tuple:767:2: note:   template argument deduction/substitution failed:
In file included from main.cpp:1:
/usr/local/include/c++/8.1.0/thread:258:4: note:   candidate expects 3 arguments, 1 provided
  } };
    ^
In file included from /usr/local/include/c++/8.1.0/bits/unique_ptr.h:37,
                 from /usr/local/include/c++/8.1.0/memory:80,
                 from /usr/local/include/c++/8.1.0/thread:39,
                 from main.cpp:1:
/usr/local/include/c++/8.1.0/tuple:761:11: note: candidate: ‘template<class _Alloc, class ... _UElements, typename std::enable_if<(std::_TC<((1 == sizeof... (_UElements)) && std::_TC<(sizeof... (_UElements) == 1), ThreadHandler>::_NotSameTuple<_UElements ...>()), ThreadHandler>::_MoveConstructibleTuple<_UElements ...>() && (! std::_TC<((1 == sizeof... (_UElements)) && std::_TC<(sizeof... (_UElements) == 1), ThreadHandler>::_NotSameTuple<_UElements ...>()), ThreadHandler>::_ImplicitlyMoveConvertibleTuple<_UElements ...>())), bool>::type <anonymous> > std::tuple<_Elements>::tuple(std::allocator_arg_t, const _Alloc&, _UElements&& ...)’
  explicit tuple(allocator_arg_t __tag, const _Alloc& __a,
           ^~~~~
/usr/local/include/c++/8.1.0/tuple:761:11: note:   template argument deduction/substitution failed:
In file included from main.cpp:1:
/usr/local/include/c++/8.1.0/thread:258:4: note:   candidate expects at least 2 arguments, 1 provided
  } };
    ^
In file included from /usr/local/include/c++/8.1.0/bits/unique_ptr.h:37,
                 from /usr/local/include/c++/8.1.0/memory:80,
                 from /usr/local/include/c++/8.1.0/thread:39,
                 from main.cpp:1:
/usr/local/include/c++/8.1.0/tuple:750:2: note: candidate: ‘template<class _Alloc, class ... _UElements, typename std::enable_if<(std::_TC<((1 == sizeof... (_UElements)) && std::_TC<(sizeof... (_UElements) == 1), ThreadHandler>::_NotSameTuple<_UElements ...>()), ThreadHandler>::_MoveConstructibleTuple<_UElements ...>() && std::_TC<((1 == sizeof... (_UElements)) && std::_TC<(sizeof... (_UElements) == 1), ThreadHandler>::_NotSameTuple<_UElements ...>()), ThreadHandler>::_ImplicitlyMoveConvertibleTuple<_UElements ...>()), bool>::type <anonymous> > std::tuple<_Elements>::tuple(std::allocator_arg_t, const _Alloc&, _UElements&& ...)’
  tuple(allocator_arg_t __tag, const _Alloc& __a,
  ^~~~~
/usr/local/include/c++/8.1.0/tuple:750:2: note:   template argument deduction/substitution failed:
In file included from main.cpp:1:
/usr/local/include/c++/8.1.0/thread:258:4: note:   candidate expects at least 2 arguments, 1 provided
  } };
    ^
In file included from /usr/local/include/c++/8.1.0/bits/unique_ptr.h:37,
                 from /usr/local/include/c++/8.1.0/memory:80,
                 from /usr/local/include/c++/8.1.0/thread:39,
                 from main.cpp:1:
/usr/local/include/c++/8.1.0/tuple:740:11: note: candidate: ‘template<class _Alloc, class _Dummy, typename std::enable_if<(std::_TC<std::is_same<_Dummy, void>::value, ThreadHandler>::_ConstructibleTuple<ThreadHandler>() && (! std::_TC<std::is_same<_Dummy, void>::value, ThreadHandler>::_ImplicitlyConvertibleTuple<ThreadHandler>())), bool>::type <anonymous> > std::tuple<_Elements>::tuple(std::allocator_arg_t, const _Alloc&, const _Elements& ...)’
  explicit tuple(allocator_arg_t __tag, const _Alloc& __a,
           ^~~~~
/usr/local/include/c++/8.1.0/tuple:740:11: note:   template argument deduction/substitution failed:
In file included from main.cpp:1:
/usr/local/include/c++/8.1.0/thread:258:4: note:   candidate expects 3 arguments, 1 provided
  } };
    ^
In file included from /usr/local/include/c++/8.1.0/bits/unique_ptr.h:37,
                 from /usr/local/include/c++/8.1.0/memory:80,
                 from /usr/local/include/c++/8.1.0/thread:39,
                 from main.cpp:1:
/usr/local/include/c++/8.1.0/tuple:729:2: note: candidate: ‘template<class _Alloc, class _Dummy, typename std::enable_if<(std::_TC<std::is_same<_Dummy, void>::value, ThreadHandler>::_ConstructibleTuple<ThreadHandler>() && std::_TC<std::is_same<_Dummy, void>::value, ThreadHandler>::_ImplicitlyConvertibleTuple<ThreadHandler>()), bool>::type <anonymous> > std::tuple<_Elements>::tuple(std::allocator_arg_t, const _Alloc&, const _Elements& ...)’
  tuple(allocator_arg_t __tag, const _Alloc& __a,
  ^~~~~
/usr/local/include/c++/8.1.0/tuple:729:2: note:   template argument deduction/substitution failed:
In file included from main.cpp:1:
/usr/local/include/c++/8.1.0/thread:258:4: note:   candidate expects 3 arguments, 1 provided
  } };
    ^
In file included from /usr/local/include/c++/8.1.0/bits/unique_ptr.h:37,
                 from /usr/local/include/c++/8.1.0/memory:80,
                 from /usr/local/include/c++/8.1.0/thread:39,
                 from main.cpp:1:
/usr/local/include/c++/8.1.0/tuple:719:2: note: candidate: ‘template<class _Alloc> std::tuple<_Elements>::tuple(std::allocator_arg_t, const _Alloc&)’
  tuple(allocator_arg_t __tag, const _Alloc& __a)
  ^~~~~
/usr/local/include/c++/8.1.0/tuple:719:2: note:   template argument deduction/substitution failed:
In file included from main.cpp:1:
/usr/local/include/c++/8.1.0/thread:258:4: note:   candidate expects 2 arguments, 1 provided
  } };
    ^
In file included from /usr/local/include/c++/8.1.0/bits/unique_ptr.h:37,
                 from /usr/local/include/c++/8.1.0/memory:80,
                 from /usr/local/include/c++/8.1.0/thread:39,
                 from main.cpp:1:
/usr/local/include/c++/8.1.0/tuple:713:28: note: candidate: ‘template<class ... _UElements, class _Dummy, typename std::enable_if<((std::_TC<((1 == sizeof... (_UElements)) && (! std::is_same<std::tuple<ThreadHandler>, std::tuple<_Tps ...> >::value)), ThreadHandler>::_MoveConstructibleTuple<_UElements ...>() && (! std::_TC<((1 == sizeof... (_UElements)) && (! std::is_same<std::tuple<ThreadHandler>, std::tuple<_Tps ...> >::value)), ThreadHandler>::_ImplicitlyMoveConvertibleTuple<_UElements ...>())) && std::_TC<(std::is_same<_Dummy, void>::value && (1 == 1)), ThreadHandler>::_NonNestedTuple<tuple<_Tps ...>&&>()), bool>::type <anonymous> > constexpr std::tuple<_Elements>::tuple(std::tuple<_Args1 ...>&&)’
         explicit constexpr tuple(tuple<_UElements...>&& __in)
                            ^~~~~
/usr/local/include/c++/8.1.0/tuple:713:28: note:   template argument deduction/substitution failed:
In file included from main.cpp:1:
/usr/local/include/c++/8.1.0/thread:258:4: note:   ‘ThreadHandler’ is not derived from ‘std::tuple<_Tps ...>’
  } };
    ^
In file included from /usr/local/include/c++/8.1.0/bits/unique_ptr.h:37,
                 from /usr/local/include/c++/8.1.0/memory:80,
                 from /usr/local/include/c++/8.1.0/thread:39,
                 from main.cpp:1:
/usr/local/include/c++/8.1.0/tuple:702:19: note: candidate: ‘template<class ... _UElements, class _Dummy, typename std::enable_if<((std::_TC<((1 == sizeof... (_UElements)) && (! std::is_same<std::tuple<ThreadHandler>, std::tuple<_Tps ...> >::value)), ThreadHandler>::_MoveConstructibleTuple<_UElements ...>() && std::_TC<((1 == sizeof... (_UElements)) && (! std::is_same<std::tuple<ThreadHandler>, std::tuple<_Tps ...> >::value)), ThreadHandler>::_ImplicitlyMoveConvertibleTuple<_UElements ...>()) && std::_TC<(std::is_same<_Dummy, void>::value && (1 == 1)), ThreadHandler>::_NonNestedTuple<tuple<_Tps ...>&&>()), bool>::type <anonymous> > constexpr std::tuple<_Elements>::tuple(std::tuple<_Args1 ...>&&)’
         constexpr tuple(tuple<_UElements...>&& __in)
                   ^~~~~
/usr/local/include/c++/8.1.0/tuple:702:19: note:   template argument deduction/substitution failed:
In file included from main.cpp:1:
/usr/local/include/c++/8.1.0/thread:258:4: note:   ‘ThreadHandler’ is not derived from ‘std::tuple<_Tps ...>’
  } };
    ^
In file included from /usr/local/include/c++/8.1.0/bits/unique_ptr.h:37,
                 from /usr/local/include/c++/8.1.0/memory:80,
                 from /usr/local/include/c++/8.1.0/thread:39,
                 from main.cpp:1:
/usr/local/include/c++/8.1.0/tuple:690:28: note: candidate: ‘template<class ... _UElements, class _Dummy, typename std::enable_if<((std::_TC<((1 == sizeof... (_UElements)) && (! std::is_same<std::tuple<ThreadHandler>, std::tuple<_Tps ...> >::value)), ThreadHandler>::_ConstructibleTuple<_UElements ...>() && (! std::_TC<((1 == sizeof... (_UElements)) && (! std::is_same<std::tuple<ThreadHandler>, std::tuple<_Tps ...> >::value)), ThreadHandler>::_ImplicitlyConvertibleTuple<_UElements ...>())) && std::_TC<(std::is_same<_Dummy, void>::value && (1 == 1)), ThreadHandler>::_NonNestedTuple<const tuple<_Tps ...>&>()), bool>::type <anonymous> > constexpr std::tuple<_Elements>::tuple(const std::tuple<_Args1 ...>&)’
         explicit constexpr tuple(const tuple<_UElements...>& __in)
                            ^~~~~
/usr/local/include/c++/8.1.0/tuple:690:28: note:   template argument deduction/substitution failed:
In file included from main.cpp:1:
/usr/local/include/c++/8.1.0/thread:258:4: note:   ‘ThreadHandler’ is not derived from ‘const std::tuple<_Tps ...>’
  } };
    ^
In file included from /usr/local/include/c++/8.1.0/bits/unique_ptr.h:37,
                 from /usr/local/include/c++/8.1.0/memory:80,
                 from /usr/local/include/c++/8.1.0/thread:39,
                 from main.cpp:1:
/usr/local/include/c++/8.1.0/tuple:678:19: note: candidate: ‘template<class ... _UElements, class _Dummy, typename std::enable_if<((std::_TC<((1 == sizeof... (_UElements)) && (! std::is_same<std::tuple<ThreadHandler>, std::tuple<_Tps ...> >::value)), ThreadHandler>::_ConstructibleTuple<_UElements ...>() && std::_TC<((1 == sizeof... (_UElements)) && (! std::is_same<std::tuple<ThreadHandler>, std::tuple<_Tps ...> >::value)), ThreadHandler>::_ImplicitlyConvertibleTuple<_UElements ...>()) && std::_TC<(std::is_same<_Dummy, void>::value && (1 == 1)), ThreadHandler>::_NonNestedTuple<const tuple<_Tps ...>&>()), bool>::type <anonymous> > constexpr std::tuple<_Elements>::tuple(const std::tuple<_Args1 ...>&)’
         constexpr tuple(const tuple<_UElements...>& __in)
                   ^~~~~
/usr/local/include/c++/8.1.0/tuple:678:19: note:   template argument deduction/substitution failed:
In file included from main.cpp:1:
/usr/local/include/c++/8.1.0/thread:258:4: note:   ‘ThreadHandler’ is not derived from ‘const std::tuple<_Tps ...>’
  } };
    ^
In file included from /usr/local/include/c++/8.1.0/bits/unique_ptr.h:37,
                 from /usr/local/include/c++/8.1.0/memory:80,
                 from /usr/local/include/c++/8.1.0/thread:39,
                 from main.cpp:1:
/usr/local/include/c++/8.1.0/tuple:662:17: note: candidate: ‘constexpr std::tuple<_Elements>::tuple(std::tuple<_Elements>&&) [with _Elements = {ThreadHandler}]’
       constexpr tuple(tuple&&) = default;
                 ^~~~~
/usr/local/include/c++/8.1.0/tuple:662:17: note:   no known conversion for argument 1 from ‘ThreadHandler’ to ‘std::tuple<ThreadHandler>&&’
/usr/local/include/c++/8.1.0/tuple:657:28: note: candidate: ‘template<class ... _UElements, typename std::enable_if<((std::_TC<((1 == sizeof... (_UElements)) && std::_TC<(sizeof... (_UElements) == 1), ThreadHandler>::_NotSameTuple<_UElements ...>()), ThreadHandler>::_MoveConstructibleTuple<_UElements ...>() && (! std::_TC<((1 == sizeof... (_UElements)) && std::_TC<(sizeof... (_UElements) == 1), ThreadHandler>::_NotSameTuple<_UElements ...>()), ThreadHandler>::_ImplicitlyMoveConvertibleTuple<_UElements ...>())) && (1 >= 1)), bool>::type <anonymous> > constexpr std::tuple<_Elements>::tuple(_UElements&& ...)’
         explicit constexpr tuple(_UElements&&... __elements)
                            ^~~~~
/usr/local/include/c++/8.1.0/tuple:657:28: note:   template argument deduction/substitution failed:
/usr/local/include/c++/8.1.0/tuple:656:21: error: no type named ‘type’ in ‘struct std::enable_if<false, bool>’
         bool>::type=false>
                     ^~~~~
/usr/local/include/c++/8.1.0/tuple:646:19: note: candidate: ‘template<class ... _UElements, typename std::enable_if<((std::_TC<((1 == sizeof... (_UElements)) && std::_TC<(sizeof... (_UElements) == 1), ThreadHandler>::_NotSameTuple<_UElements ...>()), ThreadHandler>::_MoveConstructibleTuple<_UElements ...>() && std::_TC<((1 == sizeof... (_UElements)) && std::_TC<(sizeof... (_UElements) == 1), ThreadHandler>::_NotSameTuple<_UElements ...>()), ThreadHandler>::_ImplicitlyMoveConvertibleTuple<_UElements ...>()) && (1 >= 1)), bool>::type <anonymous> > constexpr std::tuple<_Elements>::tuple(_UElements&& ...)’
         constexpr tuple(_UElements&&... __elements)
                   ^~~~~
/usr/local/include/c++/8.1.0/tuple:646:19: note:   template argument deduction/substitution failed:
/usr/local/include/c++/8.1.0/tuple:645:21: error: no type named ‘type’ in ‘struct std::enable_if<false, bool>’
         bool>::type=true>
                     ^~~~
/usr/local/include/c++/8.1.0/tuple:619:26: note: candidate: ‘template<class _Dummy, typename std::enable_if<((std::_TC<std::is_same<_Dummy, void>::value, ThreadHandler>::_ConstructibleTuple<ThreadHandler>() && (! std::_TC<std::is_same<_Dummy, void>::value, ThreadHandler>::_ImplicitlyConvertibleTuple<ThreadHandler>())) && (1 >= 1)), bool>::type <anonymous> > constexpr std::tuple<_Elements>::tuple(const _Elements& ...)’
       explicit constexpr tuple(const _Elements&... __elements)
                          ^~~~~
/usr/local/include/c++/8.1.0/tuple:619:26: note:   template argument deduction/substitution failed:
/usr/local/include/c++/8.1.0/tuple:618:28: error: no type named ‘type’ in ‘struct std::enable_if<false, bool>’
                bool>::type=false>
                            ^~~~~
/usr/local/include/c++/8.1.0/tuple:608:19: note: candidate: ‘template<class _Dummy, typename std::enable_if<((std::_TC<std::is_same<_Dummy, void>::value, ThreadHandler>::_ConstructibleTuple<ThreadHandler>() && std::_TC<std::is_same<_Dummy, void>::value, ThreadHandler>::_ImplicitlyConvertibleTuple<ThreadHandler>()) && (1 >= 1)), bool>::type <anonymous> > constexpr std::tuple<_Elements>::tuple(const _Elements& ...)’
         constexpr tuple(const _Elements&... __elements)
                   ^~~~~
/usr/local/include/c++/8.1.0/tuple:608:19: note:   template argument deduction/substitution failed:
/usr/local/include/c++/8.1.0/tuple:607:28: error: no type named ‘type’ in ‘struct std::enable_if<false, bool>’
                bool>::type=true>
                            ^~~~
/usr/local/include/c++/8.1.0/tuple:591:26: note: candidate: ‘template<class _Dummy, typename std::enable_if<(std::tuple<ThreadHandler>::_TC2<_Dummy>::_DefaultConstructibleTuple() && (! std::tuple<ThreadHandler>::_TC2<_Dummy>::_ImplicitlyDefaultConstructibleTuple())), bool>::type <anonymous> > constexpr std::tuple<_Elements>::tuple()’
       explicit constexpr tuple()
                          ^~~~~
/usr/local/include/c++/8.1.0/tuple:591:26: note:   template argument deduction/substitution failed:
In file included from main.cpp:1:
/usr/local/include/c++/8.1.0/thread:258:4: note:   candidate expects 0 arguments, 1 provided
  } };
    ^
In file included from /usr/local/include/c++/8.1.0/bits/unique_ptr.h:37,
                 from /usr/local/include/c++/8.1.0/memory:80,
                 from /usr/local/include/c++/8.1.0/thread:39,
                 from main.cpp:1:
/usr/local/include/c++/8.1.0/tuple:581:17: note: candidate: ‘template<class _Dummy, typename std::enable_if<std::tuple<ThreadHandler>::_TC2<_Dummy>::_ImplicitlyDefaultConstructibleTuple(), bool>::type <anonymous> > constexpr std::tuple<_Elements>::tuple()’
       constexpr tuple()
                 ^~~~~
/usr/local/include/c++/8.1.0/tuple:581:17: note:   template argument deduction/substitution failed:
In file included from main.cpp:1:
/usr/local/include/c++/8.1.0/thread:258:4: note:   candidate expects 0 arguments, 1 provided
  } };
    ^
/usr/local/include/c++/8.1.0/thread:258:4: error: could not convert ‘{<expression error>}’ from ‘<brace-enclosed initializer list>’ to ‘std::thread::_Invoker<std::tuple<ThreadHandler> >’
In file included from /usr/local/include/c++/8.1.0/bits/unique_ptr.h:37,
                 from /usr/local/include/c++/8.1.0/memory:80,
                 from /usr/local/include/c++/8.1.0/thread:39,
                 from main.cpp:1:
/usr/local/include/c++/8.1.0/tuple: In instantiation of ‘constexpr std::_Head_base<_Idx, _Head, false>::_Head_base(_UHead&&) [with _UHead = ThreadHandler; long unsigned int _Idx = 0; _Head = ThreadHandler]’:
/usr/local/include/c++/8.1.0/tuple:373:49:   required from ‘constexpr std::_Tuple_impl<_Idx, _Head>::_Tuple_impl(std::_Tuple_impl<_Idx, _Head>&&) [with long unsigned int _Idx = 0; _Head = ThreadHandler]’
/usr/local/include/c++/8.1.0/tuple:662:17:   required from ‘std::thread::_State_impl<_Callable>::_State_impl(_Callable&&) [with _Callable = std::thread::_Invoker<std::tuple<ThreadHandler> >]’
/usr/local/include/c++/8.1.0/thread:197:20:   required from ‘static std::thread::_State_ptr std::thread::_S_make_state(_Callable&&) [with _Callable = std::thread::_Invoker<std::tuple<ThreadHandler> >; std::thread::_State_ptr = std::unique_ptr<std::thread::_State>]’
/usr/local/include/c++/8.1.0/thread:126:38:   required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = ThreadHandler&; _Args = {}]’
main.cpp:14:23:   required from here
/usr/local/include/c++/8.1.0/tuple:133:42: error: use of deleted function ‘ThreadHandler::ThreadHandler(ThreadHandler&&)’
  : _M_head_impl(std::forward<_UHead>(__h)) { }
                                          ^
main.cpp:4:8: note: ‘ThreadHandler::ThreadHandler(ThreadHandler&&)’ is implicitly deleted because the default definition would be ill-formed:
 struct ThreadHandler
        ^~~~~~~~~~~~~
main.cpp:4:8: error: use of deleted function ‘std::condition_variable::condition_variable(const std::condition_variable&)’
In file included from main.cpp:2:
/usr/local/include/c++/8.1.0/condition_variable:82:5: note: declared here
     condition_variable(const condition_variable&) = delete;
     ^~~~~~~~~~~~~~~~~~
In file included from main.cpp:1:
/usr/local/include/c++/8.1.0/thread: In instantiation of ‘std::thread::_State_impl<_Callable>::_State_impl(_Callable&&) [with _Callable = std::thread::_Invoker<std::tuple<ThreadHandler> >]’:
/usr/local/include/c++/8.1.0/thread:197:20:   required from ‘static std::thread::_State_ptr std::thread::_S_make_state(_Callable&&) [with _Callable = std::thread::_Invoker<std::tuple<ThreadHandler> >; std::thread::_State_ptr = std::unique_ptr<std::thread::_State>]’
/usr/local/include/c++/8.1.0/thread:126:38:   required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = ThreadHandler&; _Args = {}]’
main.cpp:14:23:   required from here
/usr/local/include/c++/8.1.0/thread:221:14: note: synthesized method ‘constexpr std::tuple<_Elements>::tuple(std::tuple<_Elements>&&) [with _Elements = {ThreadHandler}]’ first required here
       struct _Invoker
              ^~~~~~~~
/usr/local/include/c++/8.1.0/thread:182:69: note: synthesized method ‘constexpr std::thread::_Invoker<std::tuple<ThreadHandler> >::_Invoker(std::thread::_Invoker<std::tuple<ThreadHandler> >&&)’ first required here
  _State_impl(_Callable&& __f) : _M_func(std::forward<_Callable>(__f))

Passing a pointer-to-member function into template

I wonder how can I pass a pointer to the non-static member function into the template? Here's the simplified code:

template<typename, typename>
struct contains;

template<typename T, typename R, typename... Ts>
struct contains<T, R(Ts...)>
{
    static constexpr bool result = std::disjunction_v<std::is_same<T, Ts>...>;
};

class A
{
public:
    static void staticFoo(int a, double* b) {}
    void foo(int a, double* b) {}
};
void foo(int a, double* b) {}

int main ()
{
    //ok, this works
    std::cout << std::boolalpha << contains<double*, decltype(foo)>::result;
    //this too
    std::cout << std::boolalpha << contains<double*, std::remove_pointer_t<decltype(&A::staticFoo)>>::result;
    //boom, error
    std::cout << std::boolalpha << contains<double*, decltype(&A::foo)>::result;

    return 0;
}

Executing this code, I got an error:

 incomplete type 'contains<double*, void (A::*)(int, double*)>' used in nested name specifier

As I understood, types are:

void(int, double*)
void(*)(int, double*)
void(A::*)(int, double*)

In the second case I can use std::remove_pointer_t, but how can I remove (A::*) from function signature in the third case?

How to check if union contains type (using type_traits)?

I have a function template like the following:

template<class U, class T>
T* unsafeCast(U* theUnion) {
    reinterpret_cast<T*>(theUnion);
}

How can I make sure this only compiles if T is a type contained within the union U, so that the following holds?

union FooUnion {
    int a;
    double b;
} foo;

unsafeCast<FooUnion, int>(&foo); // compiles
unsafeCast<FooUnion, double>(&foo); // compiles
unsafeCast<FooUnion, char>(&foo); // does not compile

I understand that is_union from <type_traits> allows to check for a union, but how can I check for types within a union?

check return type from templated method

I am working on c++11 application:

There I have some templated methods:

template <class P, class T>
void copyMemberToDocument(const P &childClass
                          std::string (T::*getter) (void) const) {
   auto member = (childClass.*getter)();
   // ...
}

Child class has multiple inheritance so I can have something like:

class A {
public:
  int getA() {return 1;}

class B {
public:
  const char* getB() {return "hello";}

class C : public A, public B {};

So I can do something like:

C c;
copyMemberToDocument(c, &B::getB);
copyMemberToDocument(c, &B::getA);

Is is possible to know if return value in templated method will be "const char*" or "int" in order to do different things depending on that?

Thanks and regards

Private delete operator complie-time error with gcc but not clang

this is a follow up to this question

when using nothrow allocators the code compile with clang but not with gcc

#include <new>

class X {
   public:
      X() noexcept { }    
   private:
      static void operator delete(void*) { }
};

int main() { 
    X* x = new(std::nothrow) X{}; 
}

demo

which compiler is right ?

Regex for GPS data

I am trying to check whether a GPS lock is active by parsing NMEA messages from a GPS chip.

The following line with the highlighted 'A' confirms the data is valid and hence a GPS lock is active.

$GPRMC,132417.000,A,5112.2257,N,00009.5337,W,0.00,288.79,140618,,,A*76

It is possible that the number between 'GPRMC' and 'A' is missing if there no GPS lock, in which case we 'V' (for invalid data) instead of 'A'.

I know I could do this by string manipulation, searching for the second comma after the GPRMC keyword and then checking we have a letter A after that.

Is there a more elegant way using regex? I'm not as familiar with regex expressions as I would like to be.

I am trying to do this in C++14.

cmake enable g++ -std=c++11

I have a c++ project and I use cmake to build it. in the c++ code I use std::to_string and apparently I have to path the command g++ -std=c++11to compile it.

I tried :

ccmake .. CMAKE_CXX_COMPILER=g++ -std=c++11

but I have an error that it's looking for a folder std=c++11 in the build directory.

How can I enable c++11 using cmake ?

send error : bad address

I am trying to send some data (cryptographic material) throught a TCP socket in my localhost. So i send first the size of the datas, and it works well. Then i send the real data. It starts well, my server getting some of it but after some time, it crash giving me

Send error: Bad address

*** Error in `/home/stagiaire031/Bureau/HElib-master/src/serveur': free():

invalid next size (normal): 0x0000000000882cc0 ***

i've tried to valgrind it to get some information, but i only got this :

--7732-- VALGRIND INTERNAL ERROR: Valgrind received a signal 11 (SIGSEGV) - exiting --7732-- si_code=128; Faulting address: 0x0; sp: 0x803426e30

valgrind: the 'impossible' happened: Killed by fatal signal

host stacktrace: ==7732== at 0x38091C12: ??? (in /usr/lib/valgrind/memcheck-amd64-linux)

==7732== by 0x38050E84: ??? (in /usr/lib/valgrind/memcheck-amd64-linux)

==7732== by 0x380510A9: ??? (in /usr/lib/valgrind/memcheck-amd64-linux)

==7732== by 0x380D4F7B: ??? (in /usr/lib/valgrind/memcheck-amd64-linux)

==7732== by 0x380E3946: ??? (in /usr/lib/valgrind/memcheck-amd64-linux)

sched status: running_tid=1

I'm not really used to valgrind, and the only things i found about this error is this, but i don't find somwhere in my code where i could have write before or after my buffer.

The other weird things is that sometimes my server get more data than other times before crashing.

here is the relevant code for the server :

char *buffer = 0;
buffer = new char[4096];
stringstream s2;
s2.str();
long n = recv(newsockfd, buffer, 50, 0);
cout << buffer << endl;
double size = stod(buffer, nullptr);
cout << "i receive this size of message : " << n << endl;
n = 0;
int i = 0;
cout << "we wait the message" << endl;
while (i < size)
{
    n = read(newsockfd, buffer, size);
    if (n < 0)
    {
        cout << "we got a receive error" << n << endl;
        perror("Send error");
    }
    else
    {
        cout << "concatenate strings" << endl;
        s2 << *buffer;
        cout << "we receive " << n << " and all : " << i << endl;
        i += n;
    }
    bzero(buffer, 4096);
}

and here is the one for the client :

n = send(sockfd, s2.str().c_str(), 10, 0);
cout << "context size " << s1.str().length() << endl;
n = 0;
int i = 0;
while (i < s1.str().length())
{
    n = send(sockfd, s1.str().c_str(), s1.str().length() - i, 0);
    if (n < 0)
    {
        perror("Send error");
    }
    else
    {
        cout << "end of a turn... we send " << n << endl;
        i += n;
        s1.str() += n;
    }
}

i've check out some post about error with socket, like this this ,this or this. They helped me before but seems like not enought for my current problem.

Thanks everyone for any help!

regex_replace, why does it lost the $1?

string s = " 'I'd go.' ";
s = std::regex_replace(s, std::regex("((^| )')|('($| ))"), "$1(Quotation, )");
cout << s; // '(Quotation, )I'd go.(Quotation, )

I want to replace the ' with (Quotation, ), and I don't want to lose the original '. So, I use $1 to mean the original '. And I don't want to replace the ' of I'd.

^ means if the ' is the start of the string it would be replaced. $ means the end of the string.

The result is supposed to be

'(Quotation, )I'd go.' (Quotation, )

But actually the result is

'(Quotation, )I'd go.(Quotation, )

The left quotation replacement works fine, but the right loses the ' . Why?

mercredi 27 juin 2018

Lock less consumer producer using C++11

I am looking for "complete" producer-consumer sample using C++11 memory barrier.

(I have derived following example from Jeff's article and added a line to make it complete.)

void SendTestMessage(void* param)
{
    // Copy to shared memory using non-atomic stores.
    g_payload.tick  = clock();
    g_payload.str   = "TestMessage";
    g_payload.param = param;

    // Release fence.
    std::atomic_thread_fence(std::memory_order_release);

    // Perform an atomic write to indicate that the message is ready.
    g_guard.store(1, std::memory_order_relaxed);
}

bool TryReceiveMessage(Message& result)
{
    // Perform an atomic read to check whether the message is ready.
    int ready = g_guard.load(std::memory_order_relaxed);

    if (ready != 0)
    {   
        g_guard.store(0, std::memory_order_relaxed);

        // Acquire fence.
        std::atomic_thread_fence(std::memory_order_acquire);

        // Yes. Copy from shared memory using non-atomic loads.
        result.tick  = g_payload.tick;
        result.str   = g_payload.str;
        result.param = g_payload.param;

        return true;
    }

    // No.
    return false;
}

if you notice, i added "g_guard.store(0, std::memory_order_relaxed);" just before acquire. This will help following ways

  1. It would avoid "TryReciveMessage" to cosnume same message if called multiple times before new message is written
  2. It would not add explicit memory fence and hence won't affect performance
  3. since "std::memory_order_relaxed" guarantees the ordering, it would be get overwritten by "SendTestMessage" value if new load added after the "std::memory_order_acquire" is called. So, we will not miss any load.

Please provide your comments and/or suggestions.

What are the disadvantages of define a field (in class) as a reference?

What are the disadvantages of define a field (in class) as a reference?
For example:

template <typename T>
Class A {  
    T& x; 
public:  
    //....
}

In addition, exists special things that I need to do while I define a field as reference?

Why I get this error "invalid initialization of non-const reference of type 'A&' from an rvalue of type 'A'"

Given the following code:

#include <iostream>
using std::ostream;

class A {
    int x;
public:
    A(int x) :
            x(x) {
    }
    A& operator+=(const A& a) {
        this->x = this->x + a.x;
        return *this;
    }
    friend ostream& operator<<(ostream& os, const A& a);

};

A operator+(const A& a1, const A& a2) {
    return A(a1) + a2;
}

ostream& operator<<(ostream& os, const A& a) {
    return os << a.x;
}

int main() {
    const A a1(2);
    A& sum = a1 + a1; // error**************
    std::cout << sum;
}

I get the following error:

invalid initialization of non-const reference of type 'A&' from an rvalue of type 'A'

But I don't understand what is the reason of this error. At all, I get new object from operator+ and I define a reference (sum) to this object , so what is the problem in this way? And how can I fix it?

How Can I Build A Sequence Of Structs With Integer Members of Increasing Value at Compile Time in C++11

Working in an embedded environment, I'm repeatedly writing code that takes an array of bytes from a protocol layer and turns those bytes into a C++ class representation.

An example array of bytes that represents a uint32_t, followed by a uint8_t, followed by a uint16_t might look like this.

std::array<uint8_t, 7> bytes(0x01, 0x02, 0x03, 0x04, 0x10, 0x20, 0x30);

Where 0x01020304 is my uin32_t, 0x04 is my uint8_t and 0x2030 is my uint16_t.

I also have a variadic function func that I want to call with the values parsed out of the payload.

To achieve this, I manually define an intermediate object:

// Declaring the Object
struct MY_TYPE
{
   uint32_t val1;
   uint8_t val2;
   uint16_t val3;
} __attribute__((__packed__));

// Processing the Bytes 
auto & object(reinterpret_cast<MY_TYPE *>(&bytes));

func(object.val1, object.val2, object.val3) 

What I want to do is implement a variadic class such that I don't need to re-implement MY_TYPE for every combination of types.

Here's what I initially tried:

template <typename... Types>
struct GENERIC_CLASS
{
   template <typename ReturnType, std::size_t ArraySize>
   ReturnType getValueFromArray(std::array<uint8_t, ArraySize> const & array, 
                                uint32_t & index); 

   // Note, not valid c++ since the size of the array (N) isn't 
   // specified. This has been omitted for simplicity. 
   void process(std::array<uin8_t, N> const & array)
   {
      auto currentIndex(u0);

      // Assumes this class has a specialization 
      // for getValueFromArray for all of the types in Types. 

      // This code doesn't work because there is no sequence point 
      // between each call to getValueFromArray, so the 
      // currentIndex can be incremented in a non-deterministic way. 
      func(this->getValueFromArray<Types>(array, currentIndex)...);
   }
};

I was able to work around this problem by introducing a new class:

template <typename T, std::size_t position>
struct Param
{
   using type = T;
   static constexpr std::size_t offset = position;
};

This way, instead of maintaining currentIndex at runtime, I can specify the offset of each argument in code, like this:

GENERIC_CLASS<Param<uint32_t, 0>, Param<uint8_t, 4>, Param<uint16_t, 5>>

The above is potentially error prone, as the offsets could be wrong. Is there some way to generate my sequence of Params from a parameter pack of types by accumulating sizes?

Alternatively, is there some workaround for the sequence point problem that I've mentioned above?

move or copy when passing arguments to the constructor and member functions

The following is an example of my typical code. A have a lot of objects that look like this:

struct Config
{
    Config();
    Config(const std::string& cType, const std::string& nType); //additional variables omitted
    Config(Config&&) = default;
    Config& operator=(Config&&) = default;

    bool operator==(const Config& c) const;
    bool operator!=(const Config& c) const;

    void doSomething(const std::string& str);
    bool doAnotherThing(const MyOtherObject& obj);
    void doYetAnotherThing(int value1, unsigned long value2, const std::string& value3, MyEnums::Seasons value4, const std::vector<MySecondObject>& value5);

    std::string m_controllerType;
    std::string m_networkType;
    //...
};

//...

Config::Config(const std::string& cType, const std::string& nType) :
    m_controllerType(cType),
    m_networkType(nType)
{
}

My motivations and general understand of the subject:

  • use const references in constructors and methods to avoid double-copying when passing objects.
  • simple types - pass by value; classes and structs - pass by const reference (or simple reference when I need to modify them)
  • force compiler to create default move constructor and move assignment so that It would be able to do it's fancy magic and simultaneously it allows to avoid writing boring ctor() : m_v1(std::move(v1)), m_v2(std::move(v2)), m_v3(std::move(v3)) {}.
  • if it performs badly, use libc and raw pointers, then wrap it at class and write a comment.

I have a strong feeling that by rules of thumb are flawed and simply incorrect.

After reading cppreference, Scott Mayers, C++ standard, Stroustrup and so on, I feel like: "Yea, I understand every word here, but it still doesn't make any sense'. The only thing I king of understood is that move semantics makes sense when my class contains non-copiable types, like std::mutex and std::unique_ptr.

I've seen a lot of code where people pass complex object by value, like large strings, vectors and custom classes - I believe this is where move semantics happen, but, again, how can you pass an object to a function by move? If I am correct, it would leave an object in a "kind-of-null-state", making it unusable.

So, the questionы are: - How do I correctly decide between pass-by-value and pass-by-reference? - Do I need to provide both copy and move constructors? - Do I need to explicitly write move and copy constructors? May I use = default? My classes are mostly POD object so there is no complex login involved. - When debugging, I can always write std::cout << "move\n"; or std::cout << "copy\n"; in constructors of my own classes, but how do I know what happens with classes from stdlib?

P.S. It may look like it is a cry out of desperation (it is), not a valid SO question. I simply don't know to formulate my problems better than this.

Is there any way to print its information when met an uncaught exception that is not from STL?

When compiler meets an exception that is from STL like std::out_of_range :

int main(int argc, char *argv[]) {
    throw std::out_of_range("There is an exception!");
}

the console will show the message :

libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: There is an exception!

So I wrote an exception class :

class Exception {
    protected:
        const char *msg;
    public:
        Exception(const char *msg) noexcept : msg(msg) {}
        Exception(const string &msg) noexcept : msg(msg.c_str()) {}
        const char *what() const noexcept {
            return this->msg;
        }
};

However, throwing Exception will not get any information :

int main(int argc, char *argv[]) {
    throw Exception("There is an exception!");
}

Console message :

libc++abi.dylib: terminating with uncaught exception of type Exception

Is there any way making console show :

libc++abi.dylib: terminating with uncaught exception of type Exception: There is an exception!

Compiler : Apple LLVM version 9.1.0 (clang-902.0.39.2)

Why is the move constructor involved here

I have this piece of C++ code:

class Args {};

class MyClass {
  public:
  MyClass(Args& a) {}
  MyClass(MyClass &&) = delete;
};

int main() {

  Args a;
  MyClass c1 = MyClass(a);
  MyClass c2 = a;
  MyClass c3(a);

  return 0;
}

This does not compile because the construction of objects c1 and c2 seem to involve the class's move constructor:

error: use of deleted function ‘MyClass::MyClass(MyClass&&)’

It seems as if the compiler wants to create temporary object and then move them to c1 and c2. Why is this happening? Shouldn't all three statements just call the MyClass(Args& a) constructor?

On the other hand, if I do create the move constructor the program compiles fine and the move constructor is never called!!!

The c++11 constexper feature

So, my question. There is a feature in c++11 called constexper. May I know how this works? And, moreover is there any feature in the new versions (c++14 and c++17) that can be used in place of this.

How to generate CMakeLists.txt.user with bash script

Wi have a rather large projet that takes time to configure manually, so we decided to make a bash scrip to do everything for us.

we're on Ubuntu 16.04 We're using c++ and CMake in our project We're using QtCreator to work on the project

The bash script is allmost done, but I am having trouble configuring QtCreator settings: I did manage to modify the kits directly in .config/QtProject/qtcreator/profiles.xml

But i can't find how to create the QtCreator's CMakeLists.txt.user file with a bash script

does anyone know how to create a CMakeLists.txt.user file with a bash script if it's possible?

mardi 26 juin 2018

Derived classes from abstract base class

I am trying to use a derived class from an abstract base class in c++ (c++11). I can not post exact code but here is an example of my implementation:

class A{
    protected:
        union x {
          struct type_a{
              uint8_t data : 8;
          };
          struct type_b{
              uint8_t data : 12;
          }; 
        };
    public:
        virtual int get_word() = 0; //pure virtual, makes class abstract
};

class B : public A{
    private:
        struct type_var{}type; //used to store struct type from base class
    public:
        B(int select) {
            switch(select) {
                case CNTR_GRP:
                   type = x.type_a; //error here
                break;
                /*... more similar case statements */
        }
        //implement get_word().. etc
};

Now like I said, I can only show example code. I need the derived class to select the correct struct type from the base (abstract) class. The type of the struct is not known until runtime so this is why it is structured like so. My current error is error: expected primary-expression before ‘.’ token which occurs where I commented. I have tried many different ways of accessing and setting the proper struct from base class such as type = A::x.type_a; but have failed to get it to work.

I have researched and read lots of posts on SO and tried following implementations and examples but can't get it to work. Am I missing something here? Thanks for the help, hopefully I'm not missing something completely obvious.

Resources I have used:

Interfaces in C++ (Abstract Classes)

How to access protected members in derived class?

Why does a purely virtual/abstract class require a constructor, in particular for protected const member variables?

  • several more that I closed and can't seem to find.

Why I get the following error: "returning reference to temporary [-Werror=return-local-addr]"

given the following code:

#include <set>

using std::set;

class Pool {
    set<int> s;
public:
    Pool();
    ~Pool();

    typedef typename set<int>::iterator Iterator;
    const Iterator& begin() const;
    // Iterator& begin();
    // const Iterator& end() const;
    // Iterator& end();
};

Pool::Pool() = default;
Pool::~Pool() = default;

const typename Pool::Iterator& Pool::begin() const {
    return s.begin(); //** error
}

Why I get the following error (I understand the meaning of the error, but, I don't understand why I get it in this case)?

returning reference to temporary [-Werror=return-local-addr]

How can I fix it?

How to make the default destructor non-inline?

How can one force the compiler to make the default destructor of a class non-inline?

One way of doing this is to write an empty destructor definition, but it feels messy and also you get a warning from the static analyzer (clang-tidy in my case), that = default should be used for a trivial destructor.

To elaborate more on the actual use case - the goal is to have something similar to:

MyClass.h

class MyClassImpl;

class MyClass {
    std::unique_ptr<MyClassImpl> m_impl;
public:
    MyClass();
    // and some other methods
};

A std::unique_pointer to an incomplete type, which is forward declared in the header and the definition is known only in the source file.

The code above will give a compiler error:

error: use of undefined type 'MyClassImpl'

The actual problem is, that the default destructor of MyClass generated by the compiler is inline and so it needs the complete type info of MyClassImpl.

This can be fixed by adding an empty destructor for MyClass (by declaring in the header and defining in the source file, since defining in the header will implicitly make it inline which will cause the same error).

But is this the only way in modern C++?

time complexity of find fun in vector stl c++

Can you explain how find function works in STL C++ vector and what is its time complexity?

vector<int> v; if(find(v.begin(),v.end(),element)==v.end()) do this; else do this

Inserting multiple not-a-numbers into a std::unordered_set

One of consequences of the IEEE 754 standard is the non-intuitive behavior of std::unordered_set<double>, when not-a-number elements (NANs) are inserted.

Due to the fact that NAN!=NAN, after the following sequence:

#include <iostream>
#include <cmath>
#include <unordered_set>

int main(){
    std::unordered_set<double> set;
    set.insert(NAN);
    set.insert(NAN);
    std::cout<<"Number of elements "<<set.size()<<"\n";  //there are 2 elements!
}

there are two elements in the set(see it live): NAN and NAN!

Mine main issue with this is, that when N NANs are inserted into the hash-set, they all hit the same hash-bucket and the performance of N inserts into the hash-set degenerates to the worst-case running time - O(N^2).

For an example, see the listing at the end of the question or here live - inserting NAN takes some order of magnitude more time than a "normal" floating number.

My question: is it possible (and if yes - how) to tweak std::unordered_set<double> in such a way, that there is at most one NAN-element in the set, no matter the flavor of inserted NANs (NAN, -NAN and so on)?


Listing:

#include <iostream>
#include <cmath>
#include <unordered_set>
#include <chrono>

constexpr int N=5000;
void test_insert(double value)
{
    std::unordered_set<double> s;
    auto begin = std::chrono::high_resolution_clock::now();
    for (int i = 0; i < N; i++) {
        s.insert(value);
    }
    auto end = std::chrono::high_resolution_clock::now();
    std::cout << "Duration: " << (std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin).count() / 1e9) << "\n";
    std::cout << "Number of elements: "<<s.size()<<"\n";
}

int main(){
    std::cout << "Not NAN\n";
    test_insert(1.0);           //takes 0.0001 s
    std::cout << "NAN\n";
    test_insert(NAN);           //takes 0.2 s
}

How can I fix it "Member declaration not found"?

given the following code:

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

    Point(const Point& p);
    ~Point();
    Point& operator=(const Point& p);

    Point& operator+=(const Point& Prhs);
};

template<class T>
Point<T>& Point<T>::operator+=(const Point<T>& Prhs) {//**error1**
    this->x += Prhs.x; //**error2**
    this->y += Prhs.y; //**error3**
    return *this;
}

template<class T>
Point<T> operator+(const Point<T>& Plhs, const Point<T>& Prhs) { 
    return Plhs += Prhs;
}  

I get the following errors:

error1: Member declaration not found

error2: Field 'x' could not be resolved

error3: Field 'y' could not be resolved

I don't understand what is the reason of these errors. How can I fix it?

Is it possible to show an application without its dock icon on Mac dinamically?

I am working on an application using Qt and C++. I have 2 windows: one main window and one floating window. I must have an option in the app to toggle the dock icon on or off, but when the floating window is visible I must leave the dock icon there.