vendredi 30 septembre 2016

Specify a range of ASCII lowercase chars in C++

I am writing a program that takes a char and compares it to see if it's in a range of certain chars. For instance, if the char I get is an n I go to state 3, if its a - m or o - z I go to state 4. I'm new to C++ so I'm still learning.

Can I say something like:

char c = file.next_char();
...
if (c in 'a'...'m', 'o'...'z')
{
   state = 3;
} else {
   state = 4;
}

Template only for smart pointer

Hi I am not sure that this is possible since but I thought of asking since there might be better ways of achieving something similar that I am not aware of. For simplicity lets just consider that VectorT is

template<class T>
class VectorT: private std::vector<T>`

An attempt to what I wanted to have is something along the lines of.

namespace detail
{
template<class SmartPtr>
class MyClassVectorBase : public VectorT<SmartPtr>
{
public:
    MyClassVectorBase() = default;

    // all common functions of MyVectorView and MyVector
};
}

using MyClassVectorView = detail::MyClassVectorBase<nonstd::observer_ptr<SomeClass>>;

class MyVector : public detail::MyClassVectorBase<std::unique_ptr<SomeClass>>
{
    // only functions related to the actual owner vector
};

What I am hoping is that MyClassVectorBase can be templated only on the smart pointer type and only accept SomeClass. I thought that it might be possible with a specialization but I got no idea what the syntax for something like that would be

template<class T, class SmartPtr>
class MyClassVectorBase : public VectorT<SmartPtr<T>>
{
};

template<SomeClass T, typename SmartPtr>
class MyClassVectorBase : public VectorT<SmartPtr<T>>
{   
};

Is something like that even possible ?

C++ vector allocator error

I'm trying compile with gcc

#include <string>
#include <vector>

std::vector < std::string, std::vector < std::vector < int > > > plain;

int main(){
return 0;
}

But getting a error: error: ‘class std::vector, std::allocator > >’ has no member named ‘deallocate’

Returning member unique_ptr from class method

I am trying to return a std::unique_ptr class member (trying to move the ownership) to the caller. The following is a sample code snippet:

class A {
 public:
  A() : p {new int{10}} {}

  static std::unique_ptr<int> Foo(A &a) {
    return a.p; // ERROR: Copy constructor getting invoked
    // return std::move(a.p); WORKS FINE

  }
  std::unique_ptr<int> p;
};

I thought the compiler (gcc-5.2.1) would be able to do return value optimization (copy elision) in this case without requiring the explicit intent via std::move() to be coded. Please explain.

Also, the following code seems to be working fine:

std::unique_ptr<int> foo() {
  std::unique_ptr<int> p {new int{10}};
  return p;
}

Thanks in advance!

Literal operator template: why not string?

Once again, while replying to another question, I forgot (my fault) that literal operator templates are picked up from the set of declarations only when integer or floating literals are found.

Apart for the obvious reason that is because the standard says that, what's the technical reason (if any) for which they are not considered when dealing with string literals?

I found also a proposal for that, but still that is not an option.
What prevents them to be used for strings?

Why can't C++ automatically figure out when to use constexpr without making us write the tag? [duplicate]

This question already has an answer here:

Item 15 of Scott Meyer's Modern C++ book: "use constexpr whenever possible". He says you can mark a function constexpr and still call it with values that aren't known at compile-time -- in that case it'll behave like any other runtime function, so you get the benefits of compile-time computation if possible but can still use it with non-compile time values too. The compiler will figure it out. But if that's true, then why can't we tag every function with constexpr (or better yet, don't tag any of them and let the compiler figure it out all the time)? If the compiler is able to detect whether the values are known at compile-time and automatically do the right thing when I tag the method as constexpr, then why can't it automatically do that same check even when I don't write constexpr?

Please advice practice exercises for c++11 programming

I am an advanced level developer, mostly C/C++ languages. I tried to find some exercises to practice a bit the newer C++ standards (C++11/C++14) with no much success.

I would like to implement some exercises to practice such new things as auto types, shared pointers, new STL containers and other stuff that was introduced in C++11.

If somebody may advice me any good resource for this purpose, I will be very thankful.

Why isn't std::move a keyword in C++?

Obviously, move semantics/r-value references were a much needed addition in C++11. One thing that has always bugged me though, is std::move. The purpose of std::move is to transform an l-value into an r-value. And yet, the compiler is perfectly happy to let you continue using that value as an l-value and you get to find out at runtime that you screwed up.

It seems like there is a missed opportunity to define move (or some other name) as a keyword (similar to *_cast) and actually have the compiler understand that the referenced value can no longer be used as an l-value here. I'm sure there is some implementation work to do this, but is there some fundamental reason why this wasn't done?

`[ ]` operator leads to compile error on map

I am trying to get an element from a map in a for loop. Following the example on cppreference I try this:

#include <iostream>
#include <map>

using namespace std;

int main()
{
    map<int, int> mapping;

    mapping.insert(pair<int, int>(11,1));
    mapping.insert(pair<int, int>(12,2));
    mapping.insert(pair<int, int>(13,3));

    for (const auto &it : mapping)
        mapping[it]++;


    cout << "array: ";
    for (const auto &it : mapping)
        cout << it.second << " ";

    return 0;
}

Which gives the following compilation error with gcc:

main.cpp: In function 'int main()':
main.cpp:15:16: error: no match for 'operator[]' (operand types are 'std::map<int, int>' and 'const std::pair<const int, int>')
         mapping[it]++;

If I understand it correctly the problem is that the auto is resolved to a std::pair<const int, int> for which no [] operator is defined. I was wondering whether there is a way to get this to work.

See for the full compilation error here

When and how to use a template literal operator?

On cppreference there is a mentioning that one can have templated user-literal operators, with some restrictions:

If the literal operator is a template, it must have an empty parameter list and can have only one template parameter, which must be a non-type template parameter pack with element type char, such as

template <char...> double operator "" _x();

So I wrote one like in the code below:

template <char...> 
double operator "" _x()
{
    return .42;
}

int main()
{
    10_x; // empty template list, how to specify non-empty template parameters?
}

Question:

  1. The code works, but how can I use the operator with some non-empty template parameters? 10_x<'a'>; or 10_<'a'>x; does not compile.
  2. Do you have any example of real-world usage of such templated operators?

error: invalid conversion from 'unsigned char*' to 'const signed char*'

uint8_t* buf1;
...
const signed char* buf2 = static_cast<const signed char*>(buf1);

invalid static_cast from type 'uint8_t* {aka unsigned char*}' to type 'const signed char*'

c-style-cast: (const signed char*) works fine

Is there any danger using c-style-cast vs static_cast in this case?

How do I access an alias declared inside struct/class scope?

Header.h

namespace some_name {
    struct foo {
        // using alias
        using MyMap = std::map<double, some_class* const>;
        MyMap* GetMap();
        MyMap* map_;
    }
}

Source.cpp

#include "Header.h"

// using declaration
using some_name::foo;

MyMap* foo::GetMap(){
    ...
    return map_;
}

But I get compiler error:

error: ‘MyMap’ does not name a type

MyMap* foo::GetMap() {

^

If I define the GetMap() in place in the header file everything works fine but if I move it to source file I get that error. What am I missing here?

What direction should I take now that I know standard C++11 front-to-back?

I have a strong C and Java background, but C++ has caught my eye for the past several months and I think I am capable of doing advanced things pertaining to the language. As of now, I feel overwhelmed by my options as to which direction I should take. Looking on other forums, people say to learn an API (such as Linux). Is this the right path to go down? I like both A.I. and low-level programming projects and perhaps would like to contribute to them. Any advice is much appreciated!

How many types can std::variant define?

I've learned there is a std::variant type in c++11. Looks like there are no predefined data types supported by the variant container but for each variant type the user may define her own data-type set.

std::variant<int, float> v;

I wonder, how long may the list of types be? Does the library has a predefined templates for a maximal number of parameter in Aleksandrescu manner, or is the variant supported by the compiler and the number of types is not limited?

Is it specified in the C+11 standard that std::begin(Container&&) returns const_iterator?

Here's a link to relevant code:

#include <iostream>
#include <string>
#include <vector>
#include <type_traits>

int main()
{
  std::vector<int> v{1, 2, 3, 4, 5};
  auto iter = begin(std::move(v));
  if(std::is_const<typename std::remove_reference<decltype(*iter)>::type>::value)
    std::cout<<"is const\n";
  return 0;
}

http://ift.tt/2cQ9tYe

I ran into this behavior because of a declval<Container>() in a decltype expression with std::begin. Both gcc and clang return iterators which yield const references when dereferenced. It probably makes sense since r-value references usually bind to expiring objects that you don't want to mutate. However, I could not find any documentation on this to determine whether it's mandated by the standard. I couldn't find any relevant overloads of begin() or ref-qualified overloads of Container::begin().

How to properly pass C strings to a lambda inside a variadic template function

Here is my complex situation:

I have a function using variadic template and lambda:

template<typename...Args>
void foo(Args...args) {
    // the arguments are passed to the lambda
    _func = [args...](){ do_sth(args...); };
}

On observing specific events, the lambda _func would be fired. My problem is, some of the arguments I passed are C strings, they could be pointing to temporary std string like this:

const char *pStr = __temp_std__string__.c_str();

Given I call foo(pStr);, and when _func is called, the temporary string that pStr is pointing to, has been released. I would like to know whether there exists a generic way to handle this. I am using C++11.

How to avoid this kind of repetition

I have code similar to this:

#include <string>

class A{
public:
    std::string &get(){
        return s;
    }

    const std::string &get() const{
        return s;
    }

    std::string &get_def(std::string &def){
        return ! s.empty() ? s : def;
    }

    // I know this might return temporary
    const std::string &get_def(const std::string &def) const{
        return ! s.empty() ? s : def;
    }

private:
    std::string s = "Hello";
};

I am wondering is there easy way to avoid code repetition in get() functions?

Divide Vector into chunks with constant memory

suppose you need to work with great amount of elements (1 bilion+) that are stored in vector and at one moment, you would like to take all of these elements and divide them into groups. To be specific, we would like to do following:

std::vector<std::vector<int>> groups(100, std::vector<int>);
for (size_t i = 0; i < 1000000000; ++i) {
    groups[i % 100].push_back(big_vector.push_back(i));
}
big_vector.resize(0);
big_vector.shrink_to_fit();

However, since big_vector is really massive, it is quite inconvenient to have our data in memory duplicated. This however probably can not be avoided due to vectors continuous memory allocation and inability to resize itself without copying the whole data (Correct me if I am wrong).

The question is then, what other structure to use to store our big data? I thought of writing custom container, that would internally store data in std::vector<std::array<SIZE>>, where SIZE is sufficiently large not to have too many chunks, but not that big to cause problems with duplicate memory overhead. Is there more standard-ish (boost-ish) way of doing this, or is writing custom container my best bet?

To further specify my expectations of the container - it would be nice if it had interface similar to vector (fast random access etc.). However if necessary I would probably could get by without random access and only the ability to push and read things. This though has to be very fast anyway.

jeudi 29 septembre 2016

Add operator[] for vector when Type is unique_ptr

Suppose that we have the vector class below which has been shortened to minimum to showcase the question.

template <typename T>
class VectorT : private std::vector<T>
{
  using vec = std::vector<T>;
public:
  using vec::operator[];
  using vec::push_back;
  using vec::at;
  using vec::emplace_back;

  template<typename Q = T>
  typename Q::element_type* operator[](const size_t _Pos) const { return at(_Pos).get(); }
};

Is there any way to check if T is a unique_ptr and if yes to add an operator[] to return the unique_ptr::element_type*. At the same time though the normal operator[] should also work.

VectorT<std::unique_ptr<int>> uptr_v; 
uptr_v.emplace_back(make_unique<int>(1));
//int* p1 = uptr_v[0]; // works fine if using vec::operator[]; is commented out
                          then of course it wont work for the normal case
//std::cout << *p1;

VectorT<int*> v;
v.emplace_back(uptr_v[0].get());
int *p2 = v[0];
std::cout << *p2;

Any way to achieve something like that ?

Possible c++11 instance template error on Visual studio 2015

run following code, seems the compiler defined an empty printf();

template<typename T>
void printf(T value) {
    std::cout << value << std::endl;
    cout << "case 1" << endl;
}

template<typename T, typename... Args>
void printf(T value, Args... args) {
    printf(value);
    cout << "...";
    printf(args...);
    cout << "case 2" << endl;
}
int main() {
    printf(1, 2, "123", 1.1);
    return 0;
}

I'm using vs 2015 with newest patch. The output is:

1
case 1
...2
case 1
...123...1.1
case 1
case 2
case 2
case 2

C++ Variadic template - Unable to figure out the compilation error

Given below is the code(CPP part of it) that I am trying to compile

template<typename... T>
void SelectOperation::fetchNextRow(tuple<T...>& row) const
{
    fetchColumn<0, decltype(row), T...>(row, nullptr);
}

template<int index, typename T, typename U>
void SelectOperation::fetchColumn(T& row) const
{
    cout << typeid(row).name();
    std::get<index>(row) = this->get<U>(index + 1);
}

template<int index, typename T, typename U, typename... V>
void SelectOperation::fetchColumn(T& row, void*) const
{
    fetchColumn<index, T, U>(row);
    fetchColumn<index + 1, T, V...>(row, nullptr);
}

The errors I am getting are as follows:

D:\workspaces\Calzone_Mayank\modules\Figgy\include\common/db/core/SelectOperation.h(149): 
error C2783: 'void figgy::SelectOperation::fetchColumn(T &,void *) const': could not deduce
template argument for 'U'
D:\workspaces\Calzone_Mayank\modules\Figgy\include\common/db/core/SelectOperation.h(58):
note: see declaration of 'figgy::SelectOperation::fetchColumn'
D:\workspaces\Calzone_Mayank\modules\Figgy\include\common/db/core/SelectOperation.h(149):
error C2780: 'void figgy::SelectOperation::fetchColumn(T &) const': expects 1 arguments
- 2 provided

I am unable to understand why argument for 'U' couldn't be deduced. Why is the compiler unable to determine which overloaded function it should look for?

Undefined refernece when compiling a single file with g++

Whenever I compile my code, g++ returns this error message (this is just a segement. The rest is more of the same):

text.cpp:(.text+0x2b82): undefined reference to `parser(int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
/tmp/ccSFOyBc.o:text.cpp:(.text+0x2c3c): more undefined references to `parser(int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)' follow
/tmp/ccSFOyBc.o: In function `main':
text.cpp:(.text+0x2f02): undefined reference to `contains(std::vector<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > >*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
text.cpp:(.text+0x30d2): undefined reference to `contains(std::vector<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > >*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'

Parser and contains are both functions I created that exist in the program. I heard this issue occurs when you do not link libraries or forgetting to link multiple files together, but I am only using one file (text.cpp) and have one library (-lncurses), and these errors occur with functions I have defined in the program.

I compile with g++ text.cpp -lncurses. I am using Fedora Linux 24 with the latest g++.

Any idea what this means?

Is it possible to write a C++ function which returns whether the number of arguments is divisible by N?

I've been learning about variadic templates, and with the help of this excellent blog post, I've managed to write a function even_number_of_args which returns whether the number of arguments it receives is divisible by 2.

#include <iostream>

bool even_number_of_args() {
    return true;
}

template <typename T>
bool even_number_of_args(T _) {
    return false;
}

template<typename T, typename U, typename... Vs>
bool even_number_of_args(T _, U __, Vs... vs) {
  return even_number_of_args(vs...);
}

int main() {
    std::cout << even_number_of_args()                   << std::endl; // true
    std::cout << even_number_of_args(1)                  << std::endl; // false
    std::cout << even_number_of_args(1, "two")           << std::endl; // true
    std::cout << even_number_of_args(1, "two", 3.0)      << std::endl; // false
    std::cout << even_number_of_args(1, "two", 3.0, '4') << std::endl; // true
}

I was wondering if it was possible to write a function that takes, as a template argument, a number N and returns whether the number of arguments it receives is a multiple of N. For example, the function may look something like this:

std::cout << number_of_args_divisible_by_N<1>(1, "two", 3.0, '4') // true
std::cout << number_of_args_divisible_by_N<2>(1, "two", 3.0, '4') // true
std::cout << number_of_args_divisible_by_N<3>(1, "two", 3.0, '4') // false
std::cout << number_of_args_divisible_by_N<4>(1, "two", 3.0, '4') // true

error: expected class-name before '{' token - can't seem to find any circular includes

I understand that this question has been asked a few times and the usual case is because of circular includes, but I have had trouble for the past few hours trying to find out where I may have a case of circular includes. I don't think I have a point where I can forward declare anything either. I'm probably wrong, so I need some help

The assignment I am trying to complete uses two ADTs one being a Stack and the other being a Queue. These files are templated to accept any data type, but in this lab we will be using strings. Our Queue.h/.hpp is supposed to implement a QueueInterface.h, and the Stack.h/.hpp a StackInterface.h

Finally, we have to define our own error called PreconditionViolationException.h is a sub-class of std::runtime_error.

Maybe this link will help if that's not a good explanation

To possibly save some time, I'll start with a list of the files I'm using and then my Makefile.

Executive.h/.cpp, main.cpp, Node.h/.hpp PreconditionViolationException.h/.cpp Queue.h/.hpp QueueInterface.h Stack.h/.hpp StackInterface.h

BuildingExecutive: main.o Executive.o PreconditionViolationException.o
    g++ -std=c++11 -g -Wall main.o PreconditionViolationException.o Executive.o -o BuildingExecutive

main.o: main.cpp
    g++ -std=c++11 -g -Wall -c main.cpp

PreconditionViolationException.o: PreconditionViolationException.cpp PreconditionViolationException.h
    g++ -std=c++11 -g -Wall -c PreconditionViolationException.cpp

Executive.o: Executive.cpp Executive.h Queue.hpp Queue.h Stack.hpp Stack.h Node.hpp Node.h StackInterface.h QueueInterface.h
    g++ -std=c++11 -g -Wall -c Executive.cpp

This is where I have a maybe off-topic question in regards to my Makefile. My question was if I should be compiling PreconditionViolationException.o as it's own object file? I can see why I don't explicitly compile my Stack and Queue files because they are templated, but since the only files that depend on PreconditionViolationException are the templated files, does that make a difference? My Executive(which is the file that just outputs and runs the program) doesn't depend on PreconditionViolationException, it just catches any std::exception, which should catch PreconditionViolationException since std::runtime_error is a subclass of std::exception

Well if there isn't a glaring problem with my Makefile, here is basically how I tried to trace if this had any circular includes or not.

I started with my main.cpp which looks like this.

#include "Executive.h"

int main(int argc, char** argv) {
  Executive exec(argv[1]);
  exec.Run();
  return 0;
}

This only includes Executive.h, so here is that

#ifndef EXECUTIVE_H
#define EXECUTIVE_H

#include "Queue.h"
#include "Stack.h"

class Executive {
.
. will cutout whatever isn't necessary
.
private:
    Queue<std::string> Line;
    Stack<std::string> Elevator;
};
#endif

This file depends on Queue.h and Stack.h so here are those

#ifndef QUEUE_H
#define QUEUE_H

#include "Node.h"
#include "QueueInterface.h"

template <typename T>
class Queue : public QueueInterface {
.
.
.
};
#endif

then

#ifndef STACK_H
#define STACK_H

#include "Node.h"
#include "StackInterface.h"

template <typename T>
class Stack : public StackInterface {
.
.
.
};

I don't think Node could be causing a problem here so here are the Interfaces

#ifndef STACKINTERFACE_H
#define STACKINTERFACE_H

#include "PreconditionViolationException.h"

template <typename T>
class StackInterface {
.
.
.
};
#endif

and

#ifndef QUEUEINTERFACE_H
#define QUEUEINTERFACE_H

#include "PreconditionViolationException.h"

template <typename T>
class QueueInterface {
.
.
.
}
#endif

Each of these include the PreconditionViolationException, because their methods can throw that exception.

#ifndef PVE_H
#define PVE_H

#include <stdexcept>
#include <string>

class PreconditionViolationException : public std::runtime_error {
.
.
.
}
#endif

Correct me if I'm wrong please, but after reading this I don't think there is anywhere other than possibly when I declare my Nodes that I could forward declare anything. Since my understanding of how a everything is compiled together isn't the best, the only things that I could think of were that my makefile wasn't right for this task, or that I have circular includes I am failing to identify.

I've spent a lot of time trying to trace and understand what is happening, so I'm hoping for something that could help me better understand what is happening.

Sorry if this is really long! Any help is appreciated!

C++ function that is const &

I recently came across code that looks like this:

const T& operator*() const &;

I know that usually when 'const' follows a function, it indicates that this function does not change member data but I am not sure what the significance of the '&' is. I only see it on the dereferencing operator so I assume it has something to do with that.

Copy extremely large buffer data from watch to a text file

So i have this very very large buffer of size 1296000 which i want to copy at the time of debug from my VS 2015 watch to a text file. The file stream or cout commands are not working thus left to do this manually.

interested to know if there is any quick way to copy all the buffer values i.e. [0] ...to...[1296000]... As of now when i try to do this my systems hangs and copying data in say multiple of 3000's or so is very time consuming.

i need to do this as this buffer / txt file will be used as input to my another code. Please suggest some quick way to use the watch windo in VS.

Why am i getting a runtime error when using malloc()

I some times get a runtime error and sometimes my program triggers a break point. The following programs takes value form user and creates a dynamic array of that size. If the user keeps on entering the add data option the size of array is doubled and user is allowed to add further data. Now if i input the size of dynamic array as 1 then after almost 11 entries i get a runtime error or sometimes the program also triggers a break point. What is the reason for that

#include <iostream>
#include <Windows.h>
using namespace std;
int main() {
    int size = 0;
    cout << "Please Input The Size of Your List: ";
    cin >> size;
    int curremt = 0;
    int in_check = 0;
    int del_check = 0;
    int * list;
    list = (int*)malloc(size);
    char choice = ' ';
    while (choice != 'E'|| choice != 'e') {
        system("cls");
        cout << "Press 1 to Add data"<<endl;
        //cout << "Press 2 to Delete data" << endl;
        cout << "Press 3 to  View data" << endl;
        cout << "Press E to Exit" << endl;
        cout << "Please Input Choice: ";
        cin >> choice;
        if (choice=='1') {
            in_check++;
            if (!(in_check>size))
            {
                cout << "Please Input Data: ";
                cin >> list[curremt];
                curremt++;
            }
            else {
                int * temp = new int[size];
                for (int i = 0; i < size; i++)
                {
                    temp[i] = list[i];
                }
                list = (int*)realloc(list, (size * 2));
                for (int i = 0; i < size; i++)
                {
                    list[i] = temp[i];
                }
                delete[] temp;
                size = size * 2;
                cout << "Please Input Data: ";
                cin >> list[curremt];
                curremt++;
                in_check = ((size/2)+1);
            }
        }
        else if (choice == '3') {
            for (int i = 0; i < curremt; i++)
            {
                cout << "Data At Position " << i << ":" << list[i]<<endl;
            }
            Sleep(500*size);
        }
        else if (choice == '2') {

        }
    }
    return 0;
}

C++ : &(std::cout) as template argument

Why isn't it possible to pass std::cout's address as template argument? Or if it is possible then how?

Here is what I tried:

#include <iostream>

template<std::ostream* stream>
class MyClass
{
    void disp(void)
        { (*stream) << "hello"; }
};

int main(void)
{
    MyClass<&(std::cout)> MyObj;
    MyObj.disp();

    return 0;
}

And the error message I got from clang++ -std=c++11 :

main.cpp:15:11: error: non-type template argument does not refer to any declaration
        MyClass<&(std::cout)> MyObj;
                 ^~~~~~~~~~~
main.cpp:6:24: note: template parameter is declared here
template<std::ostream* stream>
                       ^
1 error generated.

and from g++ -std=c++11 :

main.cpp: In function ‘int main()’:
main.cpp:15:22: error: template argument 1 is invalid
  MyClass<&(std::cout)> MyObj;
                      ^
main.cpp:15:29: error: invalid type in declaration before ‘;’ token
  MyClass<&(std::cout)> MyObj;
                             ^
main.cpp:16:8: error: request for member ‘disp’ in ‘MyObj’, which is of     non-class type ‘int’
  MyObj.disp();
        ^

Any ideas?

while calling a constructor from copy constructor it calls destructor too

I ve made a program that uses copy constructor to copy the object. In copy constructor i ve called the constructor to create memory and copy the contents. It does that successfully in constructor but immediately after the constructor ends destructor is called and i get the garbage value. At last in the main function if i make any attempts to destroy the newly created object the program crashes. why it behaves like that?

here's the code.

#include<iostream>
using namespace std;

class Test
{
    public:
    int a;
    int *p;

    Test(int a,int b,int c)
    {
        this->a=a;
        p=new int(2*sizeof(int));
        p[0]=b;
        p[1]=c;
        cout<<"\n\n "<<this->a<<"   "<<this->p[0]<<"   "<<this->p[1];
    }
    Test(const Test &ob)
    {
        Test(ob.a,ob.p[0],ob.p[1]);
        cout<<"\n\n "<<this->a<<"   "<<this->p[0]<<"   "<<this->p[1];
    }
    void print()
    {
        cout<<"\n\n\n "<<a<<"   "<<p[0]<<"   "<<p[1];
    }
    ~Test()
    {
        cout<<"\n\n\n DESTRUCTOR CALLED "<<endl;
        delete p;
    }
};

int main()
{
    Test *ob1=new Test(2,3,4);
    cout<<"\n\n\n  ob2: new object";
    Test *ob2=new Test(*ob1);
    cout<<"\n\n\n ob1";
    (*ob1).print();
    cout<<"\n\n\n ob2";
    (*ob2).print();
    delete ob1;
    delete ob2;
    return 1;
} 

produces the output:

2 3 4

ob2: new object 2 3 4

DESTRUCTOR CALLED

9968956 9968956 0

ob1

2 3 4

ob2

9968956 9968956 0

DESTRUCTOR CALLED

DESTRUCTOR CALLED

"then the program stops working i.e. crashes"....

uniform_real_distribution not giving uniform distribution

I am trying to generate high quality random numbers in the range (0,1) in my project and I tried testing the uniform_real_distributionfrom a sample code from here. When I ran it the code it worked fine but when I tried to modify the same with seeding the generator like:

#include <random>
#include <iostream>
#include <chrono>

using namespace std;
// obtain a seed from the system clock:
unsigned seed = static_cast<int> (chrono::system_clock::now().time_since_epoch().count());

// globally defining the generator and making it static for safety because in the
// actual project this might affect the flow.

static default_random_engine gen(seed);
uniform_real_distribution<double> distribution(0.0,1.0);

int main(){
  const int nrolls=10000;  // number of experiments
  const int nstars=95;     // maximum number of stars to distribute
  const int nintervals=10; // number of intervals

  int p[nintervals]={};

  for (int i=0; i<nrolls; ++i) {
    double number = distribution(gen);
    ++p[int(nintervals*number)];
  }

  std::cout << "uniform_real_distribution (0.0,1.0):" << std::endl;
  std::cout << std::fixed; std::cout.precision(1);

  for (int i=0; i<nintervals; ++i) {
    std::cout << float(i)/nintervals << "-" << float(i+1)/nintervals << ": ";
    std::cout << std::string(p[i]*nstars/nrolls,'*') << std::endl;
  }

  return 0;

}

The random numbers were not uniformly distributed. The output of the same when executed repeatedly is:

F:\path>randtest

uniform_real_distribution (0.0,1.0):

0.0-0.1: *********

0.1-0.2: **********

0.2-0.3: ********

0.3-0.4: *********

0.4-0.5: *********

0.5-0.6: *********

0.6-0.7: *********

0.7-0.8: *********

0.8-0.9: *********

0.9-1.0: **********

F:\path>randtest

uniform_real_distribution (0.0,1.0):

0.0-0.1: *********

0.1-0.2: *********

0.2-0.3: *********

0.3-0.4: *********

0.4-0.5: *********

0.5-0.6: *********

0.6-0.7: *********

0.7-0.8: *********

0.8-0.9: *********

0.9-1.0: *********

F:\path>randtest

uniform_real_distribution (0.0,1.0):

0.0-0.1: *********

0.1-0.2: *********

0.2-0.3: *********

0.3-0.4: *********

0.4-0.5: **********

0.5-0.6: *********

0.6-0.7: *********

0.7-0.8: *********

0.8-0.9: *********

0.9-1.0: *********

Is it because of the seeding? or is it better to use a different generator?

I use G++ 5.1.0 compiler c++11 standards.

Template function with template arguments or typename

I am creating a template class that contains a vector of numerical data (can be int, float, double, etc). And it has one operation, which calls std::abs() on the data. Something like the following code.

#include <iostream>
#include <complex>
#include <vector>


template<typename T> class MyData
{
public:
   std::vector<T> data;
   MyData<T> my_abs() const;

};


template<typename T>
MyData<T> MyData<T>::my_abs() const
{
    MyData<T> output;
    output.data.reserve(data.size());
    typename std::vector<T>::const_iterator it;

    for (it = data.begin(); it != data.end(); it++)
    {
        output.data.push_back(std::abs(*it));
    }
    return output;
}


int main()
{
    MyData<double> A;
    A.data = std::vector<double>(10, -1.0);

    MyData<double> test = A.my_abs();

    for (auto el : test.data)
    {
        std::cout << el << std::endl;
    }
    return 0;
}

This works correctly for types such as int, float, double. I also want to be able to use this class for types such as std::complex<double>.

Looking around I found that I could use template template arguments:

template<template<typename> class T, typename U> class MyData
{
public:
   std::vector<T<U>> data;
   MyData<U> my_abs() const;

};


template<template<typename> class T, typename U>
MyData<U> MyData<T<U>>::my_abs() const
{
    MyData<U> output;
    output.data.reserve(data.size());
    typename std::vector<T<U>>::const_iterator it;

    for (it = data.begin(); it != data.end(); it++)
    {
        output.data.push_back(std::abs(*it));
    }
    return output;
}

The previous code does not work as my template class expects two arguments,

error: wrong number of template arguments (1, should be 2)
MyData<U> abs() const;
       ^

Ideally I would like something like the previous code. In which the my_abs() function returns the type of the template argument passed to my template. E.g if I use a std::complex<double> then my main function could look something like:

int main()
{
    MyData<std::complex<double>> A;
    A.data = std::vector<std::complex<double>>(10, std::complex<double>(-1.0, -1.0));

    MyData<double> test = A.my_abs();

    for (auto el : test.data)
    {
        std::cout << el << std::endl;
    }
    return 0;
}

I am not sure how this can be achieved (or if it is even possible using the same template class).

How to add Boost.Asio to project?

I'm trying to add the Boostless (despite what the title says) version of Asio to my project but when I build it I always get an error:

../lib/asio/async_result.hpp:18:10: fatal error: 'asio/detail/config.hpp' file not found

I downloaded the library from Sourceforge, ran ./configure --without-boost, copied the content of the include folder into my project and included asio in my project: #include "../lib/asio.hpp"

I can't find any other SO answers or google search results for this. Any help?

pthread c++ invalid conversation from void * (*) to void* (*)(void*)

I'm new in C++ and trying to create multiple threads with pthread.

typedef struct thread_args{
    int &sockfd;
    struct sockaddr_in &serv_addr;
    int size_serv_addr;
    socklen_t &clilen;
    int &newsockfd;
};

void create_server(int &sockfd, struct sockaddr_in &serv_addr, int size_serv_addr, socklen_t &clilen, int &newsockfd){
}

int main(int argc, char *argv[])
{
     int sockfd, newsockfd;
     socklen_t clilen;

     pthread_t t1;
     struct sockaddr_in serv_addr, cli_addr;
     struct thread_args *args;
     args->clilen = clilen;
     args->newsockfd = newsockfd;
     args->serv_addr = serv_addr;
     args->size_serv_addr = sizeof(serv_addr);
     args->sockfd = sockfd;


     pthread_create(&t1, NULL, create_server, &args);
     printf("hello abc");
     return 0; 
}

When I run this code, it has a message:

error:/bin/sh -c 'make -j 4 -e -f   error: invalid conversion from 'void* (*)(int&, sockaddr_in&, int, socklen_t&, int&) {aka void* (*)(int&, sockaddr_in&, int, unsigned int&, int&)}' to 'void* (*)(void*)' [-fpermissive]
      pthread_create(&t1, NULL, create_server, &args);

How can I fix this?

Getting warning while compiling using cryptopp library

I have a encrypted file using AES algorithm in CBC mode. I have key from database. I am trying to compile below code using cryptopp 5.6.2 library. It gets compiled without -Wall flag but when I enable that flag below warnings appears.

#include <iostream>
#include <fstream>
#include <exception>
#include <sstream>

#include "cryptopp/modes.h"
#include "cryptopp/aes.h"
#include "cryptopp/filters.h"
#include "cryptopp/cryptlib.h"
#include "cryptopp/hex.h"
#include "cryptopp/filters.h"
#include "cryptopp/aes.h"
#include "cryptopp/ccm.h"
#include "cryptopp/files.h"

using namespace std;
using namespace CryptoPP;

int main(int argc, char* argv[])
{
    try
    {
        byte no[16]  ;
        byte noiv[16];
        std::string out;
        std::string fileName("./encrypted.txt");
        CBC_Mode< AES >::Decryption d;
        d.SetKeyWithIV(no, sizeof(no), noiv);
        CryptoPP::FileSource (fileName.c_str(), true, new StreamTransformationFilter(d, new CryptoPP::FileSink("decrypted.txt"),CryptoPP::StreamTransformationFilter::PKCS_PADDING));
    }
    catch ( CryptoPP::Exception& e)
    {
        std::cout << std::endl << e.what() << std::endl;
    }
    return 0;
}

Gets below errors on enabling -Wall flag

In file included from ./cryptopp_5.6.2/include/cryptopp/modes.h:12,
                 from poc.cpp:6:
./cryptopp_5.6.2/include/cryptopp/algparam.h: In constructor ‘CryptoPP::ConstByteArrayParameter::ConstByteArrayParameter(const T&, bool) [with T = std::basic_string<char, std::char_traits<char>, std::allocator<char> >]’:
./cryptopp_5.6.2/include/cryptopp/filters.h:793:   instantiated from here
./cryptopp_5.6.2/include/cryptopp/algparam.h:26: warning: unused variable ‘cryptopp_assert_26’
In file included from ./cryptopp_5.6.2/include/cryptopp/modes.h:12,
                 from poc.cpp:6:
./cryptopp_5.6.2/include/cryptopp/algparam.h: In member function ‘void CryptoPP::AlgorithmParametersTemplate<T>::MoveInto(void*) const [with T = std::ostream*]’:
poc.cpp:36:   instantiated from here
./cryptopp_5.6.2/include/cryptopp/algparam.h:322: warning: unused variable ‘p’
./cryptopp_5.6.2/include/cryptopp/algparam.h: In member function ‘void CryptoPP::AlgorithmParametersTemplate<T>::MoveInto(void*) const [with T = const wchar_t*]’:
poc.cpp:36:   instantiated from here
./cryptopp_5.6.2/include/cryptopp/algparam.h:322: warning: unused variable ‘p’
./cryptopp_5.6.2/include/cryptopp/algparam.h: In member function ‘void CryptoPP::AlgorithmParametersTemplate<T>::MoveInto(void*) const [with T = const char*]’:
poc.cpp:36:   instantiated from here
./cryptopp_5.6.2/include/cryptopp/algparam.h:322: warning: unused variable ‘p’
./cryptopp_5.6.2/include/cryptopp/algparam.h: In member function ‘void CryptoPP::AlgorithmParametersTemplate<T>::MoveInto(void*) const [with T = std::istream*]’:
poc.cpp:36:   instantiated from here
./cryptopp_5.6.2/include/cryptopp/algparam.h:322: warning: unused variable ‘p’
./cryptopp_5.6.2/include/cryptopp/algparam.h: In member function ‘void CryptoPP::AlgorithmParametersTemplate<T>::MoveInto(void*) const [with T = const int*]’:
poc.cpp:36:   instantiated from here
./cryptopp_5.6.2/include/cryptopp/algparam.h:322: warning: unused variable ‘p’
./cryptopp_5.6.2/include/cryptopp/algparam.h: In member function ‘void CryptoPP::AlgorithmParametersTemplate<T>::MoveInto(void*) const [with T = unsigned char]’:
poc.cpp:36:   instantiated from here
./cryptopp_5.6.2/include/cryptopp/algparam.h:322: warning: unused variable ‘p’
./cryptopp_5.6.2/include/cryptopp/algparam.h: In member function ‘void CryptoPP::AlgorithmParametersTemplate<T>::MoveInto(void*) const [with T = const byte*]’:
poc.cpp:36:   instantiated from here
./cryptopp_5.6.2/include/cryptopp/algparam.h:322: warning: unused variable ‘p’
./cryptopp_5.6.2/include/cryptopp/algparam.h: In member function ‘void CryptoPP::AlgorithmParametersTemplate<T>::MoveInto(void*) const [with T = CryptoPP::RandomNumberGenerator*]’:
poc.cpp:36:   instantiated from here
./cryptopp_5.6.2/include/cryptopp/algparam.h:322: warning: unused variable ‘p’
./cryptopp_5.6.2/include/cryptopp/misc.h: At global scope:
./cryptopp_5.6.2/include/cryptopp/misc.h:548: warning: ‘std::string CryptoPP::StringNarrow(const wchar_t*, bool)’ defined but not used

Thanks

Regex substitute file extension prefix placement doesn't work - replace matches

I'm quite familiar with regex, but I'm not familiar with C++11's std::regex_replace. I spent like more than an hour trying to figure out how to replace a simple file extension, but nothing is working!

What I want to achieve is quite simple. I want to replace myfile.pdf with myfile.txt. So I wrote my regex to match files that end with .pdf:

std::regex regex("^.*\\.(pdf)$")

And following a reference and following a cheat-sheet, I want to see the prefix (whatever comes before a match), so I use:

std::string myStr = std::regex_replace(std::string("HiThere.pdf"), regex, std::string("$`"))
std::cout<< myStr <<std::endl;

And I get an empty string! This happens, although I get a match! To show that I'm getting a match, simply replace "$`" with "$1", and you'll see the first match replacing the whole string.

One side note, according to all references, $0 should show the whole string, but it doesn't!

All I want to achieve is to replace that match with ".txt". What am I doing wrong here?

std::map (and family) lookup performance issues

I am writing a bitfield abstraction class, which wraps around a 32-bit piece of memory (u32 = unsigned int) and provides access to individual bits or ranges within that memory.

To implement this, I have used a std::map where the unique key is a pointer (not std::string) to a C-character array representing the mnemonic, and the value is a struct containing the bitfield properties (such as mnemonic, starting position, length, initial value and field value). All of these properties are constant and defined on startup, except for the field value which is changed only when the underlying u32 value is changed. (Also note: I have just reused the mnemonic pointer value as the unique key).

This is being used in an emulator where getBitfieldValue(), which returns the bitfield value (read only), is being called many times per second.

On compiling and profiling the code under VS 2015 update 3 (using -O2 and any speed optimisations I could find), it shows that the getBitfieldValue() function, and by extension std::find() is taking up around 60-70% of total cpu time... much too slow.

I have tried using other map implementations, such as Boost::flat_map, google::dense_hash_map or std::unordered_map, and they somewhat help but still end up being too slow (~50-60%).

My guess is I am using a map for the wrong purpose, but I am not sure considering that there is only 5-20 bitfield mappings (small lookup size)... It just seems much too slow. Most of the time would be spent looking up the same field as well.

The relevant class source code can be found here: BitfieldMap32

An example of how the map is initalised at startup (run one-time only):

struct Fields
{
    static constexpr char * ADDR = "ADDR";
    static constexpr char * SPR = "SPR";
};
ExampleClass() // constructor
{
    // registerField(mnemonic, start position, length, initial value)
    registerField(Fields::ADDR, 0, 31, 0);
    registerField(Fields::SPR, 31, 1, 0);
}

And how the field value is accessed (read only):

// getFieldValue definition.
const u32 & BitfieldMap32_t::getFieldValue(const char* fieldName)
{
    return mFieldMap.find(fieldName)->second.mFieldValue;
}

// Field access.
const u32 value = ExampleClassPointer->getFieldValue(Fields::ADDR)

Any ideas on how to reduce the lookup time? Or do I need to change implementation all together?

ERROR C2039: 'vector': is not a member of 'std'

I am new to C++ and I am trying to make a little dungeon crawler game. Currently I have multiple vectors declared in my header files but they seem to give multiple errors. I have tried searching for this problem on StackOverflow but the answers don't really seem to work.

Here is one of my header files: (Hero.h)

#pragma once

class Hero {
public:
    Hero();
    std::string name;
    int experience;
    int neededExperience;
    int health;
    int strength;
    int level;
    int speed;
    std::vector<Item> items = std::vector<Item>();
    void levelUp();
private:
};

Here is my .cpp file: (Hero.cpp)

#include "stdafx.h"
#include <vector>
#include "Hero.h"
#include "Item.h"

Hero::Hero() {

}
void Hero::levelUp()
{

};

Like I said I am new to C++ so there might be a lot more wrong with my code than I know. This is just a test.

Below are the errors that are shown in the Error list of Visual Studio 2015:

Error   C2039   'vector': is not a member of 'std'  CPPAssessment   hero.h  13  
Error   C2143   syntax error: missing ';' before '<'    CPPAssessment   hero.h  13  
Error   C4430   missing type specifier - int assumed. Note: C++ does not support default-int    CPPAssessment   hero.h  13  
Error   C2238   unexpected token(s) preceding ';'   hero.h  13  

Finding endian-ness programatically at compile-time using C++11

I have referred many questions in SO on this topic, but couldn't find any solution so far. One natural solution was mentioned here: Determining endianness at compile time.
However, the related problems mentioned in the comments & the same answer.

With some modifications, I am able to compile a similar solution with g++ & clang++ (-std=c++11) without any warning.

union U1
{
  uint8_t c[4];
  uint32_t i;
};
union U2
{
  uint32_t i;
  uint8_t c[4];
};

constexpr U1 u1 = {1, 0, 0, 0};
constexpr U2 u2 = {0x1};

constexpr bool is_little_endian ()
{
  return u1.c[0] == uint8_t(u2.i);
}

static_assert(is_little_endian(), "The machine is BIG endian");

Demo.

Can this be considered a deterministic method to decide the endian-ness or does it miss type-punning or something else?

memcpy/memmove to a union member, does this set the 'active' member?

C++ is quite strict about unions - you should read from a member only if that was the last member that was written to:

9.5 Unions [class.union] [[c++11]] In a union, at most one of the non-static data members can be active at any time, that is, the value of at most one of the non-static data members can be stored in a union at any time.

Out of curiousity, does this apply only to = assignment, or do memcpy/memmove also have the ability to change the active member?

First, a relatively simple memcpy allowing us to read a uint32_t as an array of uint16_t:

uint32_t u32 = 0x12345678;
uint16_t a16[2];
static_assert(sizeof(u32) == sizeof(a16), "");
std:: memcpy(a16, &u32, sizeof(u32));

But what happens if I make it more complicated with this union:

union {
    double whatever;
    uint16_t a16[2];
} u;
u.whatever = 3.14; // sets the 'active' member
std:: memcpy(u.a16, &u32, sizeof(u32));

// what is the 'active member' of u now, after the memcpy?
cout << u.a16[0] << ' ' << u.a16[1] << endl; // i.e. is this OK?

Which member of the union, u.whatever or u.a16 , is the 'active member'?

mercredi 28 septembre 2016

portable way to store milliseconds with chrono

I've a code as follows -

int main(){
    ....

    auto time = std::chrono::system_clock::now().time_since_epoch() / std::chrono::milliseconds(1);

    ....
    return 0;
}

The variable time here gives output as l with typeid().name() method, but is it safe to assume that if I replace auto with long type, the variable will still store the correct amount of milliseconds across different machines?

I need it because I cannot specify auto as type in class members, since they aren't constexpr or static where it might've been possible. And my intent is to send the data to browser where I can do var d = new Date(time) and it displays correct time. The communication part has been figured out via json format, I'm only stuck at how to store it correctly across different systems.

QT html and CSS to pdf file

I am using QTextDocument and using setHtml to add html. Then I used QPrinter to print in A4 pdf format QPrinter::PdfFormat but the printed pdf did not take the css style sheets. I also tried QTextDocument::setDefaultHtml and setResorce

The code is as follows. How to get the CSS style in pdf format. I use ubuntu and qmake for compiling.

const int highQualityDPI = 300;
QDir::setCurrent(QCoreApplication::applicationDirPath());

QFile  htmlFile ("myhtml.html");
if (!htmlFile.open(QIODevice::ReadOnly | QIODevice::Text)){
    return -1;
}

QString htmlContent;
QTextStream in(&htmlFile);
htmlContent=in.readAll();

QFile  cssFile ("style.css");
if (!cssFile.open(QIODevice::ReadOnly | QIODevice::Text)){
    return -1;
}
QString cssContent;
QTextStream cssIn(&cssFile);
cssContent = cssIn.readAll();

QTextDocument *document = new QTextDocument();
document->addResource( QTextDocument::StyleSheetResource, QUrl( "style.css" ), cssContent );
document->setHtml( htmlContent ); 

QPrinter printer(QPrinter::HighResolution);
printer.setPageSize(QPrinter::A4);
printer.setOutputFormat(QPrinter::PdfFormat);

printer.setOutputFileName("output.pdf");

document->print(&printer);
delete document;
return 0;

Enforcing desired relationship between template function parameters

I'm working on improving an in-house messaging library, designed to send messages internally within our applications, and to external consumers. A message consists of a MessageType (enum class) and some data (struct). Each MessageType:: corresponds to a particular data type (e.g., MessageType::TypeA will always contain Foo). However, multiple message types could use the same struct (e.g., MessageType::TypeM could also use Foo).

We have a class that can send messages. Our previous implementation of the message sender class defines a method for each type:

SendMessageTypeA(Foo data)
SendMessageTypeB(Bar data)
SendMessageTypeM(Foo data)

When there are lots of messages, this can result in a lot of code duplication (the method body is essentially the same, with the exception of the different parameter types).

I've implemented a new method:

template<typename structType>
void Send(MessageType msgType, const structType & messageData)

This single method can send any message, depending on the appropriate template parameter being provided.

The problem is that this new method does not enforce the relationship between MessageType and struct. For example, Send<Foo>(MessageType::TypeB, data) will compile, even though MessageType::TypeB should contain Bar. The mismatch will be detected at runtime, but I'd like to make it a compile time error.

I'm not sure how to achieve this. I've considered:

  1. Declaring all the SendMessageX() methods, and use them to call Send<MessageX>(). This does reduce the duplication, but I still have to create a new method every time a message is defined.
  2. Attempting to use static_assert to catch the mismatch. I'm not sure how to map MessageTypes to their desired struct.
  3. I'm barking up the wrong tree

Is it less computer intensive to load and unload an image every time a new image is needed or to have all of the images loaded at once? (SDL)

I've created a small animation for a game that uses a set of images as frames, and the current image to render changes over a certain amount of time to create the animation illusion. I've done this in two different ways, and I'm wondering which one is more efficient to use.

Method 1: A single image is loaded and rendered. When a different image needs to be rendered, a function is called that unloads the current image, and loads and renders the new one.

Method 2: All of the images needed for the animation are loaded once, and then rendered as needed.

In simpler terms: Method 1 unloads the current image and loads the new one every time a different image is needed, and Method 2 keeps all the images needed loaded at once.

So basically, the question is, it better to constantly load and unload images to keep as little loaded as possible, or to have many loaded at all times and not unload/load anything during the program? Does the computer have a harder time loading and unloading images or keeping many images loaded at once?

I ran looked at the task manager while running each method. CPU usage of Method 1 (loading and unloading) fluctuated between 29% and 30%, while that of Method 2 fluctuated between 28% and 29%.

It appears that keeping all the images loaded is better according to these statistics, but the reason I don't really trust them is because the program only loads seven images.

As the game gets bigger, there could be hundreds of images loaded at once (Method 2) or an image loaded and unloaded nearly every frame (Method 1). Which method is less intensive? Thank you for your time.

VS 2013->2015 Project, Include

So we have a C++ project that was VS2013, and for various reasons we have to upgrade to VS2015. Not a big deal, grabbed the VS2015 libs and compile away. Except now every file that includes i get the following errors

Error C2672 'boost::range_detail::has_member_size_impl::f': no matching overloaded function found EthAgent c:\boost\boost_1_59_0\boost\range\detail\has_member_size.hpp 45

Error C2893 Failed to specialize function template 'UINT16 boost::range_detail::has_member_size_impl::f(...)' EthAgent c:\boost\boost_1_59_0\boost\range\detail\has_member_size.hpp 45

Error C2770 invalid explicit template argument(s) for 'UINT8 boost::range_detail::has_member_size_impl::f(boost::range_detail::has_member_size_impl::check *)' EthAgent c:\boost\boost_1_59_0\boost\range\detail\has_member_size.hpp 45

We use a bunch of other boost functions and those have no issue, i assume this has something to do with C++11 having threads now? But really i'm just grasping at straws.

If i remove the include, my code compiles fine.

Using braced initialization for child struct [duplicate]

This question already has an answer here:

If I have a struct, I can initialize an instance of it without having to manually create a constructor, like this:

struct Struct {
    int x;
    int y;
};

int main() {
    Struct data{1, 2};
    //Struct data = {1, 2};  //Also works
}

However, I can no longer do this if the struct inherits from something else:

struct Parent {
    int x;
};

struct Child : public Parent {
    int y;
};

int main() {
    Child data{1, 2};
    //Child data = {1, 2};  //Also fails, with same error
}

The compiler (GCC 5.3.0) complains that there is "no matching function for call to 'Child::Child(< brace-enclosed initializer list>)". I assume this error happens because Child, since it has a base class, is no longer an aggregate (although it is still a POD).

I would like to avoid manually creating a constructor for Child, and just use braced initialization. I also need Child to directly contain all the members in Parent. In other words, having Child encapsulate Parent wouldn't work. So my main question is, is there a way to use braced initialization with a child class?

Why Visual Studio do not support variables for array size?

So this was a problem statement from CodeLeet to find the Longest Palindromic Substring.

In the codeleet interface this solution works:

class Solution {
public:
string longestPalindrome(string s) {
     int len = s.size();  
        int P[len][len];  
 memset(P, 0, len*len*sizeof(int));  
        int maxL=0, start=0, end=0;  
        for(int i =0; i< s.size(); i++){  
             for(int j =0; j<i; j++){  
                  P[j][i] = (s[j] == s[i] && (i-j<2 || P[j+1][i-1]));  
                  if(P[j][i] && maxL < (i-j+1))  
                  {  
                       maxL = i-j+1;  
                       start = j;  
                       end = i;  
                  }  
             }  
             P[i][i] =1;  
        }  
        return s.substr(start, end-start +1); 
   }
};

But when the write the same thing as a function in Visual Studio:

string User::longestPalindromeStr(string s) {
int len = s.size();
int P[len][len];
memset(P, 0, len*len * sizeof(int));
int maxL = 0, start = 0, end = 0;
for (int i = 0; i< s.size(); i++)
{
    for (int j = 0; j<i; j++)
    {
        P[j][i] = (s[j] == s[i] && (i - j<2 || P[j + 1][i - 1]));
        if (P[j][i] && maxL < (i - j + 1))
        {
            maxL = i - j + 1;
            start = j;
            end = i;
        }
    }
    P[i][i] = 1;
}
return s.substr(start, end - start + 1);
}

it says for the len variable : expression must have a constant value? Is it some problem with the VIsual studio ide. How can I solve this ?

Why a+=b*pow(10,c-i-1) == 99 c++?

I wrote this code and first time of loop result is 99. Why is result 99, when it should be 100?

#include <iostream>
#include<math.h>
using namespace std;
int main ()
{
  int skt = 0;
  int sk[3];
int nsk = 3;
sk[0]=1;
sk[1]=2;
sk[2]=8;
for (int i=0; i<nsk; i++)
{
    skt = skt + (sk[i]*pow(10.0,nsk-i-1));
    cout <<" "<<skt<<endl;
}

}

the result of this code

   99
   119
   127

,but if I use library cmath it is correct answer

#include <iostream>
#include<cmath>
using namespace std;
int main ()
{
  int skt = 0;
  int sk[3];
int nsk = 3;
sk[0]=1;
sk[1]=2;
sk[2]=8;
for (int i=0; i<nsk; i++)
{
    skt = skt + (sk[i]*pow(10.0,nsk-i-1));
    cout <<" "<<skt<<endl;
}

}

the result of this code

    100
    120
    128

Could anybody explain why?

Error handling doubles with strings in C++

My assignment is to take test grades of students in a class room and return the highest, lowest, and the average. I am currently debugging for error that could be entered by the user. I have successfully fixed issues when the user inputs characters for the decimal test score values. What I'm having trouble with is if the user inputs "4k" the program excepts the 4 as a valid input but still gives the error when the program shouldn't approve the score as a valid input but should error and prompt for only numeral values.

I'll provide an output example

heres the code segment:

for (int i = 0; i < students; i++)
      {

        cout << "Please enter a score: " << flush;
        cin >> array[i];
        do{

          if(cin.fail())
          {
            cin.clear();
            cout<<"Error, that's not a decimal number. Please reenter: ";
            std::cin.ignore(numeric_limits<streamsize>::max(), '\n' );
            cin >> array[i];
          }
        }while(cin.fail());

      }

Sample output error::

How many students are in class? 3
Please enter 3 scores
 - - - - - - - - - - -
Please enter a score: jkl
Error, that's not a decimal number. Please reenter: jkl
Error, that's not a decimal number. Please reenter: 4k
Please enter a score: Error, that's not a decimal number. Please reenter: 0
Please enter a score: 3
4
0
3
The worstest score in the class is: 0
The bestest score in the class is: 4
The average score is: 2.33333

Compile error when building qt 5.7 on Windows with msvc 2013

When I try to build the source code of Qt 5.7, I am getting the following compile error

qnode_p.h(108): error C2955: 'Qt3DCore::QNodePrivate::DestructionFunction' : use of alias template requires template argument list

qnode_p.h(105) : see declaration of 'Qt3DCore::QNodePrivate::DestructionFunction' qscene.cpp

qnode_p.h(108) : error C2955: 'Qt3DCore::QNodePrivate::DestructionFun ction' : use of alias template requires template argument list

qnode_p.h(105) : see declaration of 'Qt3DCore::QNodePrivate::DestructionFunction' Generating Code

It is error C2955 use of alias template requires template argument list.

The source code that is causing the problem is below

class QT3DCORE_PRIVATE_EXPORT QNodePrivate : public QObjectPrivate, public    QObservableInterface
{
    public:
   QNodePrivate();
   ~QNodePrivate();
...
   template<typename Caller, typename NodeType>
   using DestructionFunction = void (Caller::*)(NodeType *);

   template<typename Caller, typename NodeType, typename PropertyType>
   void registerDestructionHelper(NodeType *, DestructionFunction<Caller, NodeType>, PropertyType);

   template<typename Caller, typename NodeType>
   void registerDestructionHelper(NodeType *node, DestructionFunction<Caller, NodeType> func, NodeType *&)
   {
      // If the node is destoyed, we make sure not to keep a dangling pointer to it
      auto f = std::bind(func, static_cast<Caller *>(q_func()), nullptr);
      m_destructionConnections.insert(node, QObject::connect(node, &QNode::nodeDestroyed, f));
   }

   template<typename Caller, typename NodeType>
   void registerDestructionHelper(NodeType *node, DestructionFunction<Caller, NodeType> func, QVector<NodeType*> &)
   {
      // If the node is destoyed, we make sure not to keep a dangling pointer to it
      auto f = std::bind(func, static_cast<Caller *>(q_func()), node);
      m_destructionConnections.insert(node, QObject::connect(node, &QNode::nodeDestroyed, f));
   }

   //....
}

line 105 is using

DestructionFunction = void (Caller::*)(NodeType *);

line 108 is

void registerDestructionHelper(NodeType *, DestructionFunction<Caller, NodeType>, PropertyType);

From what I read about C++11 this should compile ok but for some reason vs 2013 gives the above error.

C++ program compiles and runs in codeblocks, but can't compile it in terminal

I created a C++ project that contains several source files and header files. The program compiles and runs well in codeblocks, but I can't compile it in terminal.

All the files are in the same folder.

Here are the command I enter:

clang++ -std=c++11 main.cpp file1.cpp file1.h 

It shows:

clang: warning: treating 'c-header' input as 'c++-header' when in C++ mode, this behavior is deprecated

And a punch of errors about:

error: use of undeclared identifier 'std' 

In the head file.

Using C++ threads with Android - AOSP build

I am writing an C++ application which is included as a part of Android OS (custom ROM). I am not able to use std::thread. Upon compiling the code I get "fatal error: 'thread' file not found". Compiler is not able to find include file 'thread'. Any way to fix this?

C++11 condiional expression on std::greater and std::less got error of different types

The following codes related to conditional expression:

typedef unsigned char uchar;
uchar data[100];
// assign something to array[] here
uchar *start = data;
uchar *end = data+100;
bool cond = f();  // f() could return true or false
char *itr = std::upper_bound(start, end, uchar(20), 
                cond? std::greater<uchar>() : std::less<uchar>());

got an error like this:

error: operands to ?: have different types 
‘std::greater<unsigned char>’ and ‘std::less<unsigned char>’

Is this a compiler bug? In my instinct, the two functor should have the same type.

Sort a Substring in Descending order using Vector, however getting segmentation fault

I want to sort the string from N to M where N indicates the starting index and M indicates the ending index.

However, my code is getting failed with segmentation fault. Here is my code:

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

using namespace std;

int main()
{   
    string s;
    int M,N;

    cout<<"Enter String"<<endl;
    getline(cin,s);

    vector<char> data(s.begin(), s.end());

    cout<<"Enter start_index and end_index for sorting";
    cin>>N>>M;    //Passed externally as N=start_index, M=end_index

    std::sort(data.begin()+N, data.begin()+M, std::greater<char>());

    for (std::vector<char>::const_iterator i = data.begin(); i != data.end(); ++i)
        std::cout << *i << ' ';

    return 0;
}

errors when trying to work with threads

Hello everybody hope all is well. I am trying to work with threads in c++. I compiled the code and got the following error messages.

C:\Users\Peretz\Documents\keylogger\KeyConstants.h|183|warning: unknown escape sequence: '\|' [enabled by default]|
C:\Users\Peretz\Documents\keylogger\Timer.h|10|error: 'thread' in namespace 'std' does not name a type|
C:\Users\Peretz\Documents\keylogger\Timer.h||In member function 'void Timer::SleepAndRun()':|
C:\Users\Peretz\Documents\keylogger\Timer.h|25|error: 'std::this_thread' has not been declared|
C:\Users\Peretz\Documents\keylogger\Timer.h||In member function 'void Timer::Start(bool)':|
C:\Users\Peretz\Documents\keylogger\Timer.h|71|error: 'Thread' was not declared in this scope|
C:\Users\Peretz\Documents\keylogger\Timer.h|71|error: 'thread' is not a member of 'std'|
C:\Users\Peretz\Documents\keylogger\Timer.h||In member function 'void Timer::Stop()':|
C:\Users\Peretz\Documents\keylogger\Timer.h|82|error: 'Thread' was not declared in this scope|
||=== Build failed: 5 error(s), 1 warning(s) (0 minute(s), 0 second(s)) ===|

I looked on Youtube for threads in c++ and threads in c++11 but could not find an answer. Please explain why there are these errors.

#ifndef TIMER_H
#define TIMER_H

#include <thread>
#include <chrono>


class Timer

{

    std::thread Thread;

    bool Alive = false;

    long CallNumber = -1L;


    long repeat_count = -1L;

    std::chrono::milliseconds interval = std::chrono::milliseconds(0);

    std::function<void(void)> funct = nullptr;

    void SleepAndRun ()
    {
        std::this_thread::sleep_for(interval);
        if (Alive)
        {
            Function ()();
        }
    }

    void ThreadFunc ()
    {


        if (CallNumber == Infinite)
            while (Alive)
                SleepAndRun ();
        else

            while (repeat_count--)
                SleepAndRun ();
    }


    public:
    static const long Infinite = -1L;

    Timer () {}

    Timer(const std::function<void(void)> &f) : funct (f) {}

    Timer(const std::function<void(void)> &f,
          const unsigned long &i,
          const long repeat = Timer::Infinite) : funct (f),
        interval (std::chrono::milliseconds(i)), CallNumber (repeat) {}



    void Start (bool Async = true)
    {

        if (IsAlive ())
            return;

        Alive = true;

        repeat_count = CallNumber;

        if (Async)
            Thread = std::thread (ThreadFunc,this);
        else
            this->ThreadFunc ();
    }

    void Stop ()
    {

        Alive = false;


        Thread.join ();
    }
    void SetFunction (const std::function<void (void)> &f)
    {
        funct = f;
    }
    bool IsAlive () const
    {
        return Alive;
    }
    void RepeatCount (const long r)
    {

        if (Alive)
            return;
        CallNumber = r;
    }

    long GetLeftCount () const
    {
        return repeat_count;
    }

    long RepeatCount () const
    {
        return CallNumber;
    }
    void SetInterval (const unsigned long &i)
    {

        if (Alive)
            return;

        interval = std::chrono::milliseconds(i);
    }

    unsigned long Interval () const
    {
        return interval.count();
    }

    const std::function<void(void)> &Function () const
    {

        return funct;
    }
};
#endif

Thank you very much.

Chaining asynchronous calls using boost::coroutines

I want to have chain of asynchronous calls using boost::coroutine.

I've started with the simplest solution.

My async methods are:

class C
{
    void function1(boost::coroutines::symmetric_coroutine<int>::call_type& coro, boost::coroutines::symmetric_coroutine<int>::yield_type& yield)
    {
        thread1 = std::thread([&](){ std::cout << "function1" << std::endl; yield(coro, 100); });

    }

    void function2(boost::coroutines::symmetric_coroutine<int>::call_type& coro, boost::coroutines::symmetric_coroutine<int>::yield_type& yield)
    {
        thread2 = std::thread([](){ std::cout << "function2" << std::endl;  });
    }

    void C::run()
    {
         boost::coroutines::symmetric_coroutine<int>::call_type coro_b(
            [&](boost::coroutines::symmetric_coroutine<int>::yield_type& yield)
            {
                 std::cout << "b entry" << std::endl;
                 function2(coro_b, yield);

                  yield();
                  std::cerr << "Never get this" << std::endl;

                   std::cout << yield.get() << std::endl;
            });

            boost::coroutines::symmetric_coroutine<int>::call_type coro_a(
                [&](boost::coroutines::symmetric_coroutine<int>::yield_type& yield)
            {
                std::cout << "a entry" << std::endl;

                 function1(coro_b, yield);
                 yield();

            });

        coro_a(2);
        coro_b(3);

        std::this_thread::sleep_for(std::chrono::minutes(1));

}


private:
    std::thread thread1;
    std::thread thread2;
};

int main()
{
    C c;
    c.run();

    return 0;
}

My output:

a entry

b entry

function2

function1

And I have an error:

main_tests: /usr/include/boost/coroutine/detail/symmetric_coroutine_impl.hpp:159: R* boost::coroutines::detail::symmetric_coroutine_impl<R>::yield_to_(Other*, typename Other::param_type*) [with Other = boost::coroutines::detail::symmetric_coroutine_impl<int>; R = int; typename Other::param_type = boost::coroutines::detail::parameters<int>]: Assertion is_running()' failed. The program has unexpectedly finished.

I just try to call coro_b when coro_a is finished (exactly when asynchronous function in coro_a is finished)....

Initializing a std::string with function return value, is there a copy?

I have the following code, I am using GCC and C++11:

std::string system_call(const char *cmd){
   std::string a;
   ...
   return a;
}

std::string st = system_call("whatever code");

Is there an implicit copy there? I am calling this function many times, and I guess it is doing a copy from the return value of the system_call to the variable st, and later on releasing the temporary r-value.

Is there any way I can avoid the copy? Using st.swap(system_call()) throws and error in the compiler:

error: no matching function for call to 'std::basic_string::swap(std::string)'

My questions are:

  1. If there is a problem or not
  2. How to avoid it, if there is one

Thanks

SFINAE to determine if a type has a potentially overloaded method

I was looking for an SFINAE solution to check at compile time if a type has a method. My goal is to check if a type is a valid "duck type", but instead of a useless compile error, I want to use static_assert to provide an informative message.

I found [this question], which provides a fairly good answer to my problem, except it fails when the type provides overload to the method:

template<typename...> // parameter pack here
using void_t = void;

template<typename T, typename = void>
struct has_xxx : std::false_type {};

template<typename T>
struct has_xxx<T, void_t<decltype(&T::xxx)>> :
  std::is_member_function_pointer<decltype(&T::xxx)>{};

This works fine with the following example, and differentiate method and member variable:

struct Foo { int xxx() {return 0;}; };
struct Foo2 {};
struct Foo3{ static double xxx;};
double Foo3::xxx = 42;

int main() {
   static_assert(has_xxx<Foo>::value, "");
   static_assert(!has_xxx<Foo2>::value, "");
   static_assert(!has_xxx<Foo3>::value, "");
}

Original live demo

The code fails if there is an overload:

struct Foo { int xxx() {return 0;}  void xxx(int){} };

int main() {
   static_assert(has_xxx<Foo>::value, "");
}

Failing live demo with overloaded method

How can this code be improved to handle overloading?

Pushing derived class to vector of base class in c++

I have the following code:

class Official {
    public:
        explicit Official(int iRow, int iColumn, int iRankHolder, int** aiBoardHolder);
};

class General : public Official {
    public: 
        explicit General(int iRow, int iColumn, int iRankHolder, int** aiBoardHolder) : Official(iRow, iColumn, iRankHolder, aiBoardHolder) {};
};

class Map {
    private:
        std::vector<Official> aoOfficialStack;

    public:
        void generateOfficialObject();
};

void Map::generateOfficialObject() {
    aoOfficialStack.push_back(General(1, 2, 3, aiBoardPosition));
}

Question is why am I getting this error after calling generateOfficalObject()?

Error C2664 'void std::vector>::push_back(const Official &)': cannot convert argument 1 from 'General' to 'Official &&' Project c:\users\user\desktop\project\project\board\board.cpp 12

Thank you very much!

equal value range on a map

I've got a map declared as:

std::map< std::pair<int, int>, bool > allPositions (essentially, keys are just 2D points).

I need to get the range of its elements whose values are true

Using std::equal_range

auto range = std::equal_range(allPositions.begin(), allPositions.end(), true);

gives these errors

Error C2672 'operator __surrogate_func': no matching overloaded function found xutility

Error C2893 Failed to specialize function template 'unknown-type std::less<void>::operator ()(_Ty1 &&,_Ty2 &&) const' xutility

Error C2056 illegal expression xutility

Error C2672 'operator __surrogate_func': no matching overloaded function found algorithm

Error C2893 Failed to specialize function template 'unknown-type std::less<void>::operator ()(_Ty1 &&,_Ty2 &&) const' algorithm

I think I don't need predicate function here because std::pair has got overloaded operator < - otherwise map code wouldn't have been compiled

So how to use std::equal_range for map to get range of equal values ?

vector of unique_ptr, inheritance?

Assuming this code:

class Parent {}
class Child : public Parent {}

static std::vector<std::unique_ptr<Child>> Foo();

Is there a simpler way to write this function:

std::vector<std::unique_ptr<Parent>> Bar() {
  auto children = Foo();

  std::vector<std::unique_ptr<Parent>> parents;
  result.insert(result.end(), std::make_move_iterator(children.begin()),
                std::make_move_iterator(children.end()));
  return parents;
}

This doesn't work:

std::vector<std::unique_ptr<Parent>> Bar() {
  return Foo(); // Compiler error: cannot convert from vector<...> to vector<...>
}

std::ignore for ignoring unused variable

It is good approach to use std::ignore for ignoring unused variables.

So suppose I have a function like this -

  void func(int i)
    {
       //for some reason, I don't need i anymore but I cannot change signature of function

    std::ignore = i;

    }

Why can't I use make_pair to tie?

I'm trying to mimic the behavior of tie pre C++11.

pair<int, int> test() {
    return make_pair(13, 42);
}

int main() {
    int a = 1, b = 2;

    pair<int&, int&>(a, b) = test();

    cout << a << ' ' << b << endl;
}

This works however if I use make_pair instead to the pair constructor a and b are not assigned.
Why does the pair constructor work but not make_pair?

QT Connect QNetworkReply not firing

I know there are a lot of threads already, but... yeah.
I had a look at this link and except the signal spy and debugging i tried at least everything. I took the example from this site.
I haven't set up the debugger for now. My problem is that i want to fire a custom slot and nothing is happening. I tried qmake and rebuild the project, but the result was the same.
I am using QTCreator with QT 5.7 msvc2015_64 as kit on a Windows10 machine. I don't get any unreferenced warnings which should be for the test function (*reply not used). What could be the source of this problem?
Do i have a problem with my finished Signal?

From the flow of the program i assume that it is the following:
I create a new pointer to an instance of class QNetworkAccessManager named manager
Then i connect the manager object's Signal finished to the custom slot test(QNetworkReply*) from the object manager
Now everytime the Signal finished from object manager changes the function test from object manger should be executed.
From the Documentation QNetworReply QNetworkAccessManager::get(QNetworkRequest(QUrl)) i assume that when this function is called a new QNetworkReply object is returned and when this object is finished processing the finished signal is emited. Do i have to connect my Signal and Slot in another way?
I tried to declare QNetworkReply reply* = manager->get.... And connect(reply, SIGNAL(finished()),this,SLOT(test())); but here my application crashes.
When i set up wireshark and filter: http contains "ht tp://www.theuselessweb.com" nothing pops up. (No more then 2 links for reputation 10 or less)

switchwebpanel.h

#ifndef SWITCHWEBPANEL_H
#define SWITCHWEBPANEL_H
#include <QNetworkAccessManager>
#include <QObject>
#include <QUrl>
#include <QNetworkReply>
#include <QFile>
#include <QDateTime>
#include <QNetworkRequest>
#include <QDebug>




class switch_panel : public QObject
{
Q_OBJECT

public:
switch_panel(QObject *parent = 0);
void doDownload();

signals:

public slots:
void replyFinished(QNetworkReply *reply);
void test(QNetworkReply * reply);

private:

QNetworkAccessManager *manager;

};

#endif // SWITCHWEBPANEL_H

switchwebpanel.cpp

#include <switchwebpanel.h>


switch_panel::switch_panel(QObject *parent):
QObject(parent)
{}


void switch_panel::doDownload(){
qDebug()<<"Downloader gestartet";
manager = new QNetworkAccessManager (this);
qDebug()<<"connect...";

Here i want to call the test(QNetworkReply*) function

connect(manager, SIGNAL(finished(QNetworkReply*)),
        this, SLOT(test(QNetworkReply*)));
qDebug()<<"get";
manager->get(QNetworkRequest(QUrl("http://ift.tt/YNxqAc")));
qDebug()<<"manager gegeted";

}

void switch_panel::replyFinished(QNetworkReply *reply){
qDebug()<<"Async starten";
if(reply->error()){
    qDebug()<<"error";
    qDebug()<<reply->errorString();
}
else {
    qDebug()<<reply->header(QNetworkRequest::ContentTypeHeader).toString();
    qDebug()<<reply->header(QNetworkRequest::LastModifiedHeader).toDateTime().toString();
    qDebug()<<reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();
    qDebug()<<"File";
    QFile *file = new QFile("./htmlpanel.txt");
    if(file->open(QFile::Append)){
        file->write(reply->readAll());
        file->flush();
        file->close();
    }
    //delete file;
}
reply->deleteLater();
qDebug()<<"Async fertig";
}
void switch_panel::test(QNetworkReply *reply){
qDebug()<<"test";
}

I get the following output:

Download
Downloader gestartet
connect...
get
manager gegeted

Boost::interprocess file_handle_t and read

How can I read the content of boost::interprocess::file_handle_t?

We are currently prototyping with code found at scoped_lock doesn't work on file?. This demonstrates how to write but we would also like to read from the file. How can this be accomplished? Done the normal google search and looked at boost docs and header files without any luck. Appreciate any input.

#include "boost/format.hpp"
#include "boost/interprocess/detail/os_file_functions.hpp"

namespace ip = boost::interprocess;
namespace ipc = boost::interprocess::detail;

void fileLocking_withHandle()
{
  static const string filename = "fileLocking_withHandle.txt";  

  // Get file handle
  boost::interprocess::file_handle_t pFile = ipc::create_or_open_file(filename.c_str(), ip::read_write);
  if ((pFile == 0 || pFile == ipc::invalid_file()))
  {
    throw runtime_error(boost::str(boost::format("File Writer fail to open output file: %1%") % filename).c_str());
  }

  // Lock file
  ipc::acquire_file_lock(pFile);

  // Move writing pointer to the end of the file
  ipc::set_file_pointer(pFile, 0, ip::file_end);

  // Write in file
  ipc::write_file(pFile, (const void*)("bla"), 3);

  // Unlock file
  ipc::release_file_lock(pFile);

  // Close file
  ipc::close_file(pFile);
}

We are developing on Windows and Linux.

Helping C++11 macros to run code with or without multithreading

I'm trying to create a preprocessing macro that allows code to be multithreaded or not depending on runtime variable. My first attempt was only a compile-time macro and worked, but the runtime version is not.

// Working compile-time version

#ifdef USE_MT

    #define MT_START(Thread)                              \
        std::atomic<bool> Thread ## Ret = true;           \
        std::thread Thread([&]()                          \
        {                                                 \
            std::atomic<bool> & __mtRet = Thread ## Ret;  \
            try{

    #define MT_END                                        \
            }catch(...){__mtRet = false;}                 \
    };

    #define MT_JOIN(Thread)                     \
        if (Thread.joinable()) Thread.join();   \
        if (Thread ## Ret){ throw; }

#else

    #define MT_START(Thread)
    #define MT_END

#endif

// Minimal use example
#define USE_MT

void function()
{
    int i = 0; 
    int j = 0;

    MT_START(th1)
    {
        i += 2;

        MT_START(th3)
        {
            i += 4;
        }
        MT_END;

        MT_JOIN(th3);
    }
    MT_END;

    MT_START(th2)
    {
        j += 2;
    }
    MT_END


    MT_JOIN(th1);
    MT_JOIN(th2);
}

Now here's the conditional version. I'm creating a lambda from user code and executing the lambda if the condition is false, otherwise I'm launching a thread with the lambda.

The main difficulty here is that the compile-time version is already widely in use on the project and I'm trying to change macro without rewriting all previous code (which leads to those __mt references)

#define MT_START(Thread, Cond)                           \
    std::thread Thread;                                  \
    std::atomic<bool> Thread ## Ret = true;              \
    {                                                    \
        auto & __mtTh = Thread;                          \
        const bool __mtCond = Cond;                      \
        auto __mtLambda = [&]() -> void                  \
        {                                                \
            std::atomic<bool> & __mtRet = Thread ## Ret; \
            try {

#define MT_END                                           \
            }catch(...){__mtRet = false;}                \
        };                                               \
        if (__mtCond)                                    \
        {                                                \
            __mtTh = std::thread{__mtLambda};            \
        }                                                \
        else                                             \
        {                                                \
            __mtLambda();                                \
        }                                                \
    }        

This last version makes unit tests to fail randomly, and I can't see why this last set of macros is different from the first one.

If anyone can help. Thanks

C++ setprecision only cuts off the digits.. it does not round

double d = 8.19999999999999999999;  
cout << d  << "\n";
cout << fixed << d  << "\n";
cout << setprecision(15) << d  << "\n";
cout << fixed << setprecision(15) << d  << "\n";

output

8.2
8.200000
8.199999999999999
8.199999999999999

Can I change that so it prints

 8.2
 8.200000
 8.200000000000000
 8.200000000000000

instead?

Reproduce the same result of the C++ 11 random generator

Is it guaranteed by the standard that if std::mt19937 was seeded by the same number, it will produce the same sequence of numbers on all platforms?

In other words, is its implementation well-defined by the standard or it is like std::rand() which was considered as implementation details?

mardi 27 septembre 2016

Template specialization for classes which have a certain method

I have a templated method of a Lua State class, which tests if the object at a given index is of a given type:

template<typename T> bool is(int idx) {
    return luaL_testudata(L, idx, std::remove_pointer<T>::type::name) != NULL;
};

and a few specializations:

template<> inline bool State::is<bool>(int i){ return lua_isboolean(this->L, i); }
template<> inline bool State::is<int>(int i){ return lua_isinteger(this->L, i); }
//etc...

Now I want to add a specialization for any class that has a static "lua_test" method:

template<> inline bool State::is<T>(int i){ return T::lua_test(this->L, i); }

But I don't know the correct syntax for this. The closest I've come is:

template <class T>
inline auto State::is(int idx) ->
decltype(std::declval<T>.lua_test(this, idx), true)
{
    return T::lua_test(this, idx);
}

This fails to compile, because apparently the types don't match:

templates.hpp:87:13: error: prototype for ‘decltype ((declval<T>.lua_test(((Lua::State*)this), idx), true)) Lua::State::is(int)’ does not match any in class ‘Lua::State’
 inline auto State::is(int idx) ->
             ^~~~~
In file included from [...],
                 from debug.cpp:1:
get.hpp:6:27: error: candidate is: template<class T> bool Lua::State::is(int)
 template<typename T> bool is(int idx) {

The idea is supposed to be that the decltype statement evaluates to decltype(true) (due to the comma operator), ie bool, but gcc doesn't seem convinced of this.

This seems like it should be pretty simple, but I've been getting nowhere trying to implement it.

C++ Compile errors on lines that don't exsist. How to make restart function

When I compile this code I get I get Compilation errors: Errors below code.

#include <iostream>

using namespace std;
int main() 
{
    while (true) 
    {
        int go_again;
        go_again = 0;
        //[CODE HERE STARTS THREADS] Removed because it was unnecessary

        while (true) 
        {
            if ((GetAsyncKeyState(Settings()->exit_key)) // exits programm
            {
                go_again = 1;
                exit(0);
            }
            if ((GetAsyncKeyState(Settings()->restart)) // restarts programm
            {
                exit(0);
            }
            else
            {
                Sleep(100);
            }
        }
        if (go_again == 1)
        {
            exit(0);
        }
    }
    return 0;
}

Here are just some of the Errors:

main.cpp(323) : Empty Attribute block is not allowed.
main.cpp(323) : Syntax error: Missing ']' before /
main.cpp(323) : Empty Attribute block is not allowed.
main.cpp(468) : Sytax error: missing ']' before '/'.
main.cpp(468) : Sytax error: missing ';' before '/'.
main.cpp(468) : Sytax error: missing ';' before '{'.

EDIT: Another weird thing about the errors is its saying its on lines that don't exists, as there is only 100 lines of code, yet this says the errors are on line 468 etc. I am using custom version of visual c++ compiler.

There are alot more, but judging by the amount of errors, it seams that I have been doing the restart function wrong. Does anyone know the correct way to do a restart function and a stop function for the code? I am new to C++ so I am not that used to the syntax.

C++11 Regex IfThenElse - Single, closed brackets matched OR no brackets matched

How can I define a c++11/ECMAScript compatible regex statement that matches strings either:

  1. Containing a single, closed, pair of round brackets containing an alphanumeric string of length greater than 0 - for example the regex statement "(\w+)", which correctly matches "(abc_123)" and ignores the incorrect "(abc_123", "abc_123)" and "abc_123". However, the above expression does not ignore input strings containing multiple balanced/unbalanced bracketing - I would like to exclude "((abc_123)", "(abc_123))", and "((abc_123))" from my matched results.

  2. Or a single, alphanumeric word, without any unbalanced brackets - for example something like the regex statement "\w+" correctly matches "abc_123", but unfortunately incorrectly matches with "(abc_123", "abc_123)", "((abc_123)", "(abc_123))", and "((abc_123))"...

For clarity, the required matchings for each the test cases above are:

  • "abc_123" = Match,
  • "(abc_123)" = Match,
  • "(abc_123" = Not matched,
  • "abc_123)" = Not matched,
  • "((abc_123)" = Not matched,
  • "(abc_123))" = Not matched,
  • "((abc_123))" = Not matched.

I've been playing around with implementing the IfThenElse format suggested by http://ift.tt/1dLSWdE, but haven't gotten very far... Is there some way to limit the number of occurrences of a particular group [e.g. "((){0,1}" matches zero or one left hand round bracket], AND pass the number of repetitions of a previous group to a later group [say "num\1" equals the number of times the "(" bracket appears in "((){0,1}", then I could pass this to the corresponding closing bracket group, "()){num\1}" say...]

Output Stream with templates c++ doesn't work [duplicate]

This question already has an answer here:

I have a template class and i want to overload the output operator <<, but my code doesn't work, I don't know why... I don't know how do the same thing, but with the input operator... Can you help me?

This is my code:

#include <iostream>

template<class TypeData, int S>
class TD{
  private:
      int size;
      int augmentation;
      int capacity;

      TypeData * array;

      void changeCapacity();

  public:
    TD();

    TD(const TD<TypeData,S> & array);

    TypeData & operator [](int position) const;

    void addElement(TypeData element);

    friend std::ostream & operator << (std::ostream & output, const TD<TypeData, S> & array);

    ~TD();
};

Here the implementation:

template<class TypeData, int S>
TD<TypeData, S>::TD(): 
size(0), augmentation(S), capacity(S){
    this->array = new TypeData[S];
}

template<class TypeData, int S>
TD<TypeData, S>::TD(const TD<TypeData,S> & array): size (array.size),
augmentation(array.augmentation), capacity(array.capacity){
    this->array = new TypeData[array.capacity];

    for (int i = 0; i < array.size; i++){
        this->array[i] = array[i];
    }
}

template<class TypeData, int S>
TypeData& TD<TypeData, S>::operator [](int position) const{
    if (position > this->size){
            return this->array[0];
    }

    return this->array[position];
}

template<class TypeData, int S>
void TD<TypeData, S>::addElement(TypeData element){
    if (this->capacity <= this->size){
        TypeData * ptTmp = new TypeData[this->capacity];

        for (int i = 0; i < this->size; i++){
            ptTmp[i] = this->array[i];
        }

        delete this->array;

        this->capacity += this->augmentation;
        this->array = new TypeData[this->capacity];

        for (int i = 0; i < this->size; i++){
            this->array[i] = ptTmp[i];
        }

        delete[] ptTmp;
    }

    this->array[size] = element;
    size++;
}

template<class TypeData, int S>
std::ostream & operator << (std::ostream & output, const TD<TypeData, S> & array){
    for (int i = 0; i < array.size; i++){
        output << array[i] << " - ";
    }

    return output;
}

Here the main:

int main(){

   TD<int,20> t;
   t.addElement(5);
   t.addElement(10);

   std::cout << t << std::endl;

   return 0;
}

I have this error:

Undefined symbols for architecture x86_64:
  "TD<int, 20>::~TD()", referenced from:
    _main in test9-134633.o
  "operator<<(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, TD<int, 20> const&)", referenced from:
      _main in test9-134633.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)