mercredi 30 septembre 2015

How to check if class has pointers in C++14

I've got the classes:

struct A { // has no pointer members, POD - it's fine
  int a, b;
  char c;
};

struct B { // has no pointer members, but not POD - it's still fine
  int a, b;
  std::string s;
};

struct C { // has pointer members, it's not fine
  int a,b;
  char* cs;
};

I need to detect in compile time if any class has the properties of struct C, i.e. has pointers as members.

Short reasoning: I need to assure a user-defined type can be safely serialized and deserialized to some buffer by copying or assignment (e.g. struct A) or by providing user-defined serialize() and deserialize() methods in the class (e.g. struct B and struct c).

If B or C do not have these methods implemented, then compilation should fail, but if A does not have the methods, then the compilation should succeed.

Why won't opendir() open a path after converting the path type with c_str()?

I'm trying to open a directory, the name of which (path) is currently in a std::string read in originally from a .csv file (although I don't think that changes anything about the string itself). Calling opendir(path.c_str()) returns NULL. I tried the following code, doing the conversion outside of opendir():

DIR *dir;
bool first = True;
string level = "";
struct dirent *ent;

const char * c = path.c_str();
// A
if ((dir = opendir(c)) != NULL){
    // do stuff
    // should open the directory and go here
}else{
    // always ends up here
}

While this failed with path="LeanDataBase", a directory in the project folder, substituting opendir("LeanDataBase") for opendir(c) does seem to open the directory. However, this function is recursive, so I can't hard code this value or it doesn't work and falls into an infinite loop.

I also tried printing the types, with the following two lines inserted right after "A" in the previous code:

cout << typeid(c).name() << endl;
cout << typeid("LeanDataBase").name() << endl;

Which yielded the following output:

PKc
A13_c

Does this mean that I'm passing the wrong type to opendir()? It seems like it can handle PKc, but not A13_c. Is there a way to convert the path string to the proper type?

NetBeans build 201509300002 - make command & include library errors

I am having some trouble with NetBeans and clang++, I cannot find the Make Command which the IDE requests upon my trying to run a basic project with a main file containing a print statement. As well, I am receiving an error from the IDE that in cannot include cstdlib even though I have c++11 enabled in the idea, as far as I am concerned. Cannot include file is the error NetBeans provides. Solutions would be appreciated. Also, my default namespace std created by default when I created the project is not being identified, it also returns an error at this line: using namespace std; above the main method.

Get all elements but the first as a separate vector

I'm trying to write a basic command-line program in C++. While the rest of the code probably has problems galore, too, the one I'm facing now is this: I've split the inputted line into pieces, but I can't figure out how to get all but the first so I can pass it down the line as the list of arguments for the command.

If this was Ruby, I'd do something like this, where parts is the array of space-separated arguments for the command:

command = parts[0]
args = parts[1..-1]

where parts is the array of bits that were space-separated.

TL;DR: How can I get all but the first elements of a vector?

If using another type makes it easier, feel free to say as much -- I don't think I'll have that much trouble porting it over.

I've tried using a deque, but I don't want to modify parts, just get pieces of it. I've also searched around on this site, but all of the questions that turn up are either related but solved in a way that I can't use, starts of a really hacky workaround that I'd rather avoid, or totally unrelated.


P.S. I'm not using namespace std, but std:: is a pain to type so I omitted it here. Please do provide it in your answers, where applicable.

P.P.S. I'm just (re)starting at C++ so please provide an explanation along with your answer.

How do I parse arrays in C++ for duplicates

Please help me use C++ to parse an array and only display numbers that are unique. I have written a program which answers most of the question below.

Question: Use a one-demensional array to solve the following problem. Read in 20 numbers, each of which is between 10 and 100, inclusive. As each number is read, validate and store it in the array only if it isn't a duplicate of a number already read. After reading all the values, display only the unique values that the user entered. Provide for the "worst case" in which all 20 number are different. Use the smallest possible array to solve this problem.

What I've done: My program creates a 20 item array. Prompts user for data, validates it and displays it. I have tried several way to only display unique data, however I have not accomplished what the question asks.

Sample User Input:

11, 12, 12, 12, 13, 14, 15, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27

My Program Output:

{ 11, 12, 12, 12, 13, 14, 15, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27 }

Correct Program Output:

{ 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27 }

Any advice where to go with this. See below for code. Thank you for your help!

#include <iostream>  
#include <array> // needed for c++11 arrays
using namespace std;

int main()
{
    const int arraySize = 20; // limit array length to 20
    array  <int, arraySize userArray>  = {}; 

    //Populate array with user input and validate it to be between 10 and 100

    for (int i = 0; i < userArray.size(); i++)
    {
            cout << "Enter a number between 10 and 100" << endl;
            cin >> userArray[i]; // get user input assign it to proper array subscript

            while(userArray[i] > 100 || userArray[i] < 10)//validate user input to be between 10 and 100
            {
                    cout << "Number needs to be between 10 and 100. Enter a new number" << endl;
                    cin >> userArray[i]; //reassign the proper array subscript if needed
            }

    }

    cout << endl;

    //display the information to look like an array
    //result looks like [ v, w, x, y, z ]

    cout << "[ ";
    //display array values
    for (int i = 0; i < userArray.size() - 1; i++)
    {
            cout << userArray[i] << ", ";
    }
    //properly display last array item
    cout << userArray[(userArray.size() - 1)] << " ]" << endl;


    return 0; }

C/C++ .. such language doesn't exist [migrated]

I came across several questions in SOO where lot of them make use of the term C/C++ which is (in my opinion) widely accepted in the industry (at least in the last two decades). In general the SOO users ask the person who is asking the question to choose a language: C or C++. Why?

I understand that both of them are different languages but when I was learning C++ I was always told that C is a subset of C++ or C++ is C with classes. And that was quiet true until the appearance of C++x0, C++11 (or the modern C++ 11/14/17 in general). In fact (specially when working on embedded systems) it's very likely to find code written in C++ but with a lot of parts written entirely in pure C language. Here I have several questions:

  1. Should I stop using the term C/C++?
  2. If the answer to #1 is yes, how would I call a program that use a mix of C and C++?
  3. Given that both of them are 'different' languages is it likely that at some point C++ compilers stop supporting code written in the C language (since modern c++ is diverging from the C mentality for basic stuff like pointers, dynamic memory handling, etc)
  4. Is there right now any collaboration between the people who makes the standards of C/C++ to keep the compatibility
  5. If #4 is yes, such collaboration could end up in the near future with the appearance of the modern c++ (11/14/17)

I know that there already similar questions, but I'm sure that a lot of people share these doubts so I'm very interested to get good answers specially for the points that have to do with the C++ tendency in the near future.

Thanks in advance,

C++ : Different deduction of type auto between const int * and cont int &

Here are the code samples.

a. int ii = 0;
b. const int ci = ii;
c. auto e = &ci; --> e is const int *
d. auto &f = 42; --> invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’
e. const auto &g = 42 --> ok

Observation:
1. for clause c) the type const is automatically deduced
2. for clause d) the type const is not automatically deduced
3. for clause e) the type const has to be added manually in order for it to work.

Why type const is automatically deduced for clause c but not d?

return the answer from "void" to another function

I got question how can i return the answer to display because i kept getting an error that void can't return a variable. How can i send it to my display function.

 void Rational::add(const Rational&h2)
    {

        int num = 0;
        int dem = 0;
        add(h2);
        int P = num * h2.dem + h2.num*dem;
        int Q = dem*h2.dem;


    }

    void display() const; // _p:_q
    {
         if (Q == 1) // e.g. fraction 2/1 will display simply as 2
                cout << P << endl;
            else
                cout <<P << "/" << Q << endl;
    }

C++ unique_ptr destructor saying object has never been allocated

I have a main process that owns a Model object. The purpose of this is to share a Model between various objects that performs tasks and modifies the same Model.

Right now, I create a unique_ptr to this object and pass a reference to that unique_ptr to other objects to perform certain tasks.

The tasks all complete correctly, but something weird happens when it tries to call the destructor on the unique_ptr. It shows:

RAW: memory allocation bug: object at 0xd0ebdfb2b8 has never been allocated

Question:

  1. Why is this error happening?
  2. Is unique_ptr the right way to tackle this problem?

Thanks

Casting char to int reference in a template

I am trying to write a serialization function, as a part of which, I need to convert char to int, and leave other types unchanged. I have written the following code:

template<typename T1>
struct return_type {typedef T1 type;};
template<>
struct return_type<char> {typedef int type;};

template<typename T1>
typename return_type<T1>::type &type_transform(T1 &&t) 
{ 
    //If writing/reading char, cast it to int
    return static_cast<typename return_type<T1>::type &>((t));
} 

The idea is to be able to write

ofstream f1;
......
f1<<type_transform(variable);
f1<<type_transform(func());

and

ifstream f1;
......
f1>>type_transform(variable);

Where variable/function could be any variable or function. But I keep getting an error saying invalid cast from char to int&, when I try using char type. Could somebody please explain?

Ambiguous call in custom member detector

I was working in my own implementation of a member detector to improve my programming skills. The following code compile well with g++ but clang++ reject the code, the error is :

error: call to 'check' is ambiguous main.cpp:19:17: note: candidate function [with U = has_member::HasIt]

static char check( decltype(U::i)* );

main.cpp:22:16: note: candidate function [with U = has_member::HasIt]

static int check(U*);

Here's the code of the class

template<typename T>
struct has_member 
{

    struct Fallback
    {
        int i;
    };

    struct HasIt : Fallback, T
    {};

    template<class U>
    static char check( decltype(U::i)* ); 

    template<typename U>
    static int check(U*);    

    static const bool value = sizeof(check<HasIt>( nullptr ) ) == sizeof(int);
};

class Test
{
public:

};

int main()
{
    auto v  = has_member<Test>::value;

    std::cout << std::boolalpha << v;
}

Live example here

The question is : is the code valid ? If it is why g++ accepts it ?

const char * value lifetime

I am trying to understand how and when the string pointed to by const char * gets deallocated.

Consider:

const char **p = nullptr;

{
    const char *t = "test";
    p = &t;
}

cout << *p;

After leaving the inner scope I would expect p to be a dangling pointer to const char *. However in my tests it is not. That would imply that the value of t actually continues to be valid and accessible even after t gets out of scope.

It could be due to prolonging the lifetime of the temporary by binding it to const reference. But I do no such thing and even by saving the reference to t in a member variable and printing the value from different function later still gives me its correct value.

class CStringTest
{
public:
    void test1()
    { 
        const char *t = "test";
        m_P = &t;
        test2();
    }

    void test2() 
    { 
        cout << *m_P;
    }

private:
    const char **m_P = nullptr;
};

So what is the lifetime of the t's value here? I would say I am invoking undefined behaviour by dereferencing a pointer to a value of a variable that went out of scope. But it works every time so I think that is not the case.

When trying some other type like QString:

QString *p = nullptr;

{
    QString str = "test";
    p = &str;
}

cout << *p;

the code always prints the value correctly too even though it should not. str went out of scope with its value and I have not prolonged its lifetime by binding it to const reference either.

Interestingly the class example with QString behaves as I would expect and test2() prints gibberish because the value indeed went out of scope and m_P became dangling pointer.

So what is the actual lifetime of const char *'s value?

How to write a test for a network listener?

I am currently writing a piece of C++ code that will listen for network connections. I'm using gtest to write unit tests but I've reached a problem I don't know how to fix:

How can I test the functions that listen for network connections? If I put this in my unit test they'll block.

Any ideas?

Odd return behavior with std::function created from lambda (C++)

I'm having trouble with std::functions created from lambdas if the function returns a reference but the return type isn't explicitly called out as a lambda. It seems that the std::function is created fine with no warnings, but upon calling it, a value is returned when a reference is expected, causing things to blow up. Here's a very contrived example:

#include <iostream>
#include <vector>
#include <functional>

int main(){
   std::vector<int> v;
   v.push_back(123);
   std::function<const std::vector<int>&(const std::vector<int>&)> callback =
      [](const std::vector<int> &in){return in;};
   std::cout << callback(v).at(0) << std::endl;
   return 0;
}

This prints out garbage, however if the lambda is modified to explicitly return a const reference it works fine. I can understand the compiler thinking the lambda is return-by-value without the hint (when I originally ran into this problem, the lambda was directly returning the result from a function that returned a const reference, in which case I would think that the const reference return of the lambda would be deducible, but apparently not.) What I am surprised by is that the compiler lets the std::function be constructed from the lambda with mismatched return types. Is this behavior expected? Am I missing something in the standard that allows this mismatch to occur? I'm seeing this with g++ (GCC) 4.8.2, haven't tried it with anything else.

Thanks!

Access to different struct with same name

I'm trying to implement a workaround for boost versions that cause problems with scoped enums on linking in C++11 mode: See http://ift.tt/1H7SdWl and http://ift.tt/1haLphx

The problem is simply: Most pre-distributed boost libs expose (namespaces stripped):
detail::copy_file(path const&, path const&, copy_option::enum_type, error_code*)
But C++11 compilation tries to find:
detail::copy_file(path const&, path const&, copy_option, error_code*)
due to the fact, that C++98 boost uses emulated scoped enums, instead of the C++11 ones.

I though I might be able to write an adapter for that put it into an own object file and link that into the program, but I failed with my naive approach:

#define copy_option native_copy_option__
#include <boost/filesystem/operations.hpp>
#undef copy_option

namespace boost {
namespace filesystem {

    struct copy_option{
        enum enum_type{none, fail_if_exists = none, overwrite_if_exists};
    };

namespace detail {

    void copy_file(const path& from, const path& to, copy_option::enum_type option, system::error_code* ec=0);

    using copy_option = native_copy_option__;
    void copy_file(const path& from, const path& to, copy_option option, system::error_code* ec)
    {
        copy_file(from, to, static_cast<boost::filesystem::copy_option::enum_type>(option), ec);
    }

}  // namespace detail
}  // namespace filesystem
}  // namespace boost

The problem is: I need to define a function with the C++11 enum in the signature but also declare a function with the C++98 enum which has the same name.

Is this somehow possible?

A container for integer intervals, such as RangeSet, for C++

I am trying to work with ranges, as in ranges of numbers. By that I mean integer intervals, in maths speak. And I want to store a set of them. I also want this set to naturally merge (or coalesce) ranges I insert.

Let's go for a simple example, I start with an empty set: { }

  • I insert the range [0,5], now I have { [0,5] }
  • I insert the range [10,15], now I have { [0,5], [10,15] }
  • I insert the range [5,7], now I have { [0,7], [10,15] }
  • I insert the range [12,17], now I have { [0,7], [10,17] }
  • I insert the range [6,13], now I have { [0,17] }

I found out thanks to a similar question that this exists in Java as a Google Guava library and is called a RangeSet.

I was initially thinking of using a std::set of std::pairs that would be sorted on the lower bound (so the first element of each pair). Then after each insertion I would have to manually merge any overlapping sets.

As this seems a common problem, is a good implementation I couldn't find due to the noise with all the synonyms of "range" in C++ ? Or does anyone care to share his own? I only want to print the final ranges but bonus points for generality if you have other set operations.

Getting the function name (__FUNCTION__) from a class name and a pointer to member function

I am writing a unit test library and I need to log the name of the test function during the assertion, like as follows:

struct my_test_case : public unit_test::test {
    void some_test()
    {
        assert_test(false, "test failed.");
    }
};

When I run the test case, I want to produce an output like:

ASSERTION FAILED (&my_test_case::some_test()): test failed.

I know there are some ways to solve this issue:

  1. Give __FUNCTION__ to assert_true()

  2. Define a macro like ASSERT(a, b) that expands to assert_true(a, b, __FUNCTION__)

  3. Define a macro like TEST to cache the __FUNCTION__ in the test function:

    struct my_test_case : public unit_test::test { void some_test() { TEST assert_test(false, "test failed."); } };

But these are error-prone and ugly solutions. Are there any other solutions to this problem?

Unexpected evaluate result when calling std::set functions in "if" statement

I found the behavior of calling std::set function in the "if" statement does something I can't understand, here is my code.

#include<set>
#include<iostream>
#include<cstdio>
using namespace std;
set<int>s;int t;
set<int>::iterator i;
int main()
{
    while (cin>>t) {
        if ((i=s.insert(t).first)==s.begin())
/*Expected: 
insert the new element, 
get the iterator of the new inserted element and save it into i,
and compare it to the begin of the set to see if it is the smallest. */
            puts("the new int is the smallest");
        else puts("the new int is not the smallest");
    }
    return 0;
}

If I input:

3 2 1

The output would be:

the new int is not the smallest
the new int is not the smallest
the new int is not the smallest

However, if I move the insert out of the "if":

while (cin>>t) {
        (i=s.insert(t).first);
        if (i==s.begin())
            puts("the new int is the smallest");
        else puts("the new int is not the smallest");
    }

Then I can get the expected output:

the new int is the smallest
the new int is the smallest
the new int is the smallest

I also tried to test using the following code:

int a() {
    puts("fun a encountered");
    return 1;
}
int b() {
    puts("fun b encountered");
    return 1;
}
int main()
{
    int x;
    if ((x=a())==b());
}

And the output is:

fun a encountered
fun b encountered

Seems like the order is what was expected in the first code. Now I am very confused. what is the reason for the first code went wrong?

Complier error reported for const vector

The following code compiles OK using Visual Studio 2013.

#include <vector>
#include <string>

int main()
{
    const std::string constString("fred");
    const std::vector<const std::string> myVector{ constString };
}

If I try to compile it using Visual Studio 2015 the following error is reported:

1>xmemory0(587): error C2338: The C++ Standard forbids containers of const elements because allocator<const T> is ill-formed.

I've seen various posts, and in particular this one Does C++11 allow vector<const T>?, about vector<const T> and why it's not allowed but I don't really get it. However, in the above example the vector itself is const.

Can someone please explain? Is VS 2013 wrong to compile it successfully?

C++ Visual Studio 13 using threads: minimal example not working

i got a minimal example from http://ift.tt/1cF1r9u for the implementation of threads.

Unfortunately this example did not compile and ERROR C2664 is thrown:

// thread example
#include <iostream>       // std::cout
#include <thread>         // std::thread

void foo() 
{
  // do stuff...
}

void bar(int x)
{
  // do stuff...
}

int main() 
{
  std::thread first (foo);     // spawn new thread that calls foo()
  std::thread second (bar,0);  // spawn new thread that calls bar(0)

  std::cout << "main, foo and bar now execute concurrently...\n";

  // synchronize threads:
   first.join();                // pauses until first finishes
  second.join();               // pauses until second finishes

  std::cout << "foo and bar completed.\n";

  return 0;
}

error C2664: 'std::thread::thread(const std::thread &)' : cannot convert argument n from 'void' to 'std::thread &&'

Can someone explain what ist wrong with the example // with Visual Studio?

Thanks

Is undefined behavior in given code?

What is the return value of f(p,p), if the value of p is initialized to 5 before the call? Note that the first parameter is passed by reference, whereas the second parameter is passed by value.

int f (int &x, int c) {
       c = c - 1;
       if (c==0) return 1;
       x = x + 1;
       return f(x,c) * x;
}

Options are :

  1. 3024
  2. 6561
  3. 55440
  4. 161051

I try to explain :


In this code, there will be 4 recursive calls with parameters (6,4), (7,3), (8,2) and (9,1). The last call returns 1. But due to pass by reference, x in all the previous functions is now 9. Hence, the value returned by f(p,p) will be 9 * 9 * 9 * 9 * 1 = 6561.


This question is from competive exam GATE , (see Q.no.-42) . Answer key is given by GATE "Marks to all" (means there is no option correct.) key set-C, Q.no.-42. somewhere explained as :

In GATE 2013 marks were given to all as the same code in C/C++ produces undefined behavior. This is because * is not a sequence point in C/C++. The correct code must replace

return f(x,c) * x;
with
 res = f(x,c);
 return res * x;


But given code works fine , Is GATE's Key wrong? or Is really the mistake with question ?

Can't understand the error with Classes and headerfile:

Error List ////////////////////////////////////////////////

Rational.h: In function ‘void add(const Rational&)’:

Rational.h:8:5: error: ‘int Rational::dem’ is private

int dem; // q ^ Rational.cpp:37:22: error: within this context

 int P = num * h2.dem + h2.num*dem;

                 ^

In file included from Rational.cpp:1:0:

Rational.h:7:5: error: ‘int Rational::num’ is private int num; //p ^ Rational.cpp:37:31: error: within this context int P = num * h2.dem + h2.num*dem; ^ In file included from Rational.cpp:1:0:

Rational.h:8:5: error: ‘int Rational::dem’ is private

int dem; // q

 ^

Rational.cpp:38:20: error: within this context

 int Q = dem*h2.dem;

                ^

Rational.cpp:25:9: warning: unused variable ‘i’ [-Wunused-variable]

 int i = 0;

     ^

Rational.cpp:26:9: warning: unused variable ‘k’ [-Wunused-variable]

 int k = 0;

     ^

Rational.cpp:37:9: warning: unused variable ‘P’ [-Wunused-variable]

 int P = num * h2.dem + h2.num*dem;

     ^

Rational.cpp:38:9: warning: unused variable ‘Q’ [-Wunused-variable]

 int Q = dem*h2.dem;

////////////////////////////////////////////////////////////////////////////////

keep getting error and error. Learning classes and header but not going that great. Can someone explain me these error . header file

#ifndef _RATIONAL_H_
#define _RATIONAL_H_
#include <iostream>
using namespace std;
class Rational
{
int num; //p
int dem; // q


public:

Rational();

Rational(int P, int Q = 1);

void display() const; // _p:_q

void add(const Rational&);

 };
#endif

.cpp file As you can tell trying different methods for adding but every time i get bench of errors.

void add(const Rational&h2)
{
    /*
        Get the input of the rational numbers
        Put in the equations

        add = ((p/q)


    */
    //int _p, _


   // int  i  , k ;
   // add(h2);
   // i = h2._q;
   // k = h2.dem;
   // num*= k;
   // dem*=k;
 //  num = +h2.num*i;
    int num = 0;
    int dem = 0;
    int i = 0;
    int k = 0;
    add(h2);

   // i = dem;
   // k = h2.dem;
   // num*= k;
   // dem*=k;
  //  num = +h2.num*i;
//    fract (num,dem);


    int P = num * h2.dem + h2.num*dem;
    int Q = dem*h2.dem;

}
void display() const; // _p:_q
{
     if (Q == 1) // e.g. fraction 2/1 will display simply as 2
            cout << P << endl;
        else
            cout <<P << "/" << Q << endl;
}

C++ random numbers: What are the advantages of using uniform_int_distribution vs a modulus operation?

According to following results, generating uniform random integers between 2 numbers using % operation is almost 3 times faster then using uniform_int_distribution.

Is there any good reason to use uniform_int_distribution?

Code:

#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>
#include <random>

#include <cstdio>
#include <cstdlib>

using namespace std;

#define N 100000000

int main()
{

clock_t tic,toc;

for(int trials=0; trials<3; trials++)
{
    cout<<"trial: "<<trials<<endl;

    // uniform_int_distribution
    {
        int res = 0;
        mt19937 gen(1);
        uniform_int_distribution<int> dist(0,999);

        tic = clock();
        for(int i=0; i<N; i++)
        {
            int r = dist(gen);
            res += r;
            res %= 1000;
        }
        toc = clock();
        cout << "uniform_int_distribution: "<<(float)(toc-tic)/CLOCKS_PER_SEC << endl;
        cout<<res<<" "<<endl;

    }

    // simple modulus operation
    {
        int res = 0;
        mt19937 gen(1);

        tic = clock();
        for(int i=0; i<N; i++)
        {
            int r = gen()%1000;
            res += r;
            res %= 1000;
        }
        toc = clock();
        cout << "simple modulus operation: "<<(float)(toc-tic)/CLOCKS_PER_SEC << endl;
        cout<<res<<" "<<endl;

    }

    cout<<endl;
}

}

Output:

trial: 0
uniform_int_distribution: 2.90289
538 
simple modulus operation: 1.0232
575 

trial: 1
uniform_int_distribution: 2.86416
538 
simple modulus operation: 1.01866
575 

trial: 2
uniform_int_distribution: 2.94309
538 
simple modulus operation: 1.01809
575 

Pattern-match/SFINAE on parameterization of container for specific classes?

I have Base class and some Derived classes. Certain bit patterns that come in from external code can make these, and there is generic code which builds them. That generic code has to use an explicit template "factory":

auto d = factory<D>(data); // where D is some Derived class

This factory is SFINAE-enabled for classes that are derived from Base:

template<
    class T,
    typename = typename std::enable_if<
        std::is_base_of<Base, T>::value
    >::type
>
T factory(ExternalData &data) {
    T result;
    if (!result.initFromData(&data))
        throw std::runtime_error("data is not set");
    return result;
}

I'd like to add another variant that works with std::optional<Derived> for the cases when the bit patterns indicate things are unset. In this case the generic code would be passing in either type:

auto dod = factory<DOD>(data); // DOD can be Derived or std::optional<Derived>

Using explicit parameterization like this, how would I create another SFINAE variant which would "pattern match" into existence only for for std::optional<any class whose base is Base>?

The desire would be if I could write:

template<
    std::optional<class T>, // imaginary
    typename = typename std::enable_if<
        std::is_base_of<Base, T>::value
    >::type
>
std::optional<T> factory(ExternalData &data) {
    T result;
    if (!result.initFromData(&data))
        return nullopt;
    return result;
}

Is there a non-imaginary version of implementing the desire? I looked at "using SFINAE for template class specialisation" (and several others) and it seems like maybe there are some ways to cooperatively hack something together to do it with a container if I wrote it (?), but am I missing an easy answer?

Forwarding cv-ref-qualifier for member functions

If there are no another overloadings (say, f(T &) or f(volatile T &&)) of a (member) function template template< typename T > f(T &&);, then T && is so-called forwarding reference, and T is either U, or U & for some cv-qualified type U. But for cv-ref-qualifiers of member functions there is no no such a rule. In struct S { void f() && { ; } }; a S::f() has always rvalue-reference qualifier.

In generic code it would be very useful to avoid a definition of 4 (or even 8, if we also consider volatile qualifier) overloadings of some member function, in cases if all of them doing generally the same thing.

Another problem that arises in this way, it is impossibility to define an effective cv-ref-qualifier of *this in a particular sense. Following code not allows one to determine whether the ref-qualifier of a member function operator () is && of &.

#include <type_traits>
#include <utility>
#include <iostream>

#include <cstdlib>

#define P \
{                                                                       \
    using this_ref = decltype(*this);                                   \
    using this_type = std::remove_reference_t< this_ref >;              \
    std::cout << qual() << ' '                                          \
              << (std::is_volatile< this_type >{} ? "volatile " : "")   \
              << (std::is_const< this_type >{} ? "const " : "")         \
              << (std::is_lvalue_reference< this_ref >{} ? "&" : "&&")  \
              << std::endl;                                             \
}

struct F
{
    constexpr int qual() & { return 0; }
    constexpr int qual() const & { return 1; }
    constexpr int qual() && { return 2; }
    constexpr int qual() const && { return 3; }
    constexpr int qual() volatile & { return 4; }
    constexpr int qual() volatile const & { return 5; }
    constexpr int qual() volatile && { return 6; }
    constexpr int qual() volatile const && { return 7; }
    void operator () () & P
    void operator () () const & P
    void operator () () && P
    void operator () () const && P
    void operator () () volatile & P
    void operator () () volatile const & P
    void operator () () volatile && P
    void operator () () volatile const && P
};

int
main()
{
    {
        F v;
        F const c{};
        v();
        c();
        std::move(v)();
        std::move(c)();
    }
    {
        volatile F v;
        volatile F const c{};
        v();
        c();
        std::move(v)();
        std::move(c)();
    }
    return EXIT_SUCCESS;
}

But it would be very nice, if there was above syntax. I.e. decltype((*this)) is exact cv-ref-qualified type of *this. It would not be a breaking-change to introduce such a syntax into coming version of the C++ standard at my mind. But && as forwarding cv-ref-qualifier is (and it looks like an omission of the committee (namely, core language working group)).

Is there a proposal regarding this issue, prepared for use in C++17?

mardi 29 septembre 2015

C++11 constexpr and typeid(type)

Is there a way, how to get typeid into variable in compile time using constexpr?

This is not working, since std::type_index has no constexpr ctor

constexpr std::type_index i = typeid(double);

std::thread as member of class executing random thread causing an abort at asignate thread

In my class I have thread object as public membe:

class AppManager{
   ...
    public:
    std::thread m_thread;
};

Then when I initialize the thread:

void* BridgeFunction(void *pctx) {
    ((AppManager*)pctx)->MainAppThread();
    return 0;
}

void AppManager::CreateAppThread(){
   m_thread = std::thread(&BridgeFunction, this);
   m_thread.detach();
}

I got an Abort on std::terminate:

 thread& operator=(thread&& __t) noexcept
    {
      if (joinable())
      std::terminate();
      swap(__t);
      return *this;
    }

Why? I'm calling detach, I tried changing from:

m_thread = std::thread(&BridgeFunction, this);

To:

m_thread = std::thread(&AppManager::MainAppThread, this);

And the same, it works only if I declare the m_thread as global and I debugged why it works, turns out that the thread declared as member execute a random thread before I assign the thread, I know this because I printed the id to see if it was joinable:

    auto myid = m_thread.get_id();
    std::stringstream ss;
    ss << myid;
    std::string thread_id = ss.str();

    LogPrintDebug("[Thread Activity] -  Id of thread not created yet: %s", thread_id.c_str());

    m_thread = std::thread(&BridgeFunction, this);
    m_thread.detach();

It prints:

[Thread Activity] - Id of thread not created yet: 1074643408

When I declare global the thread it prints:

[Thread Activity] - Id of thread not created yet::id of a non-executing thread

I printed also the Id of my actual thread and it's different than the Id of the random thread, so try to terminate it due to the part:

if (joinable())
 std::terminate();

I'm using Visual Studio 2015 running an Android Native Activity using Clang 3.6 and the GNU STL libraries, ndk r10e.

I tested the same code on windows and the id of the thread is 0, doesn't get any Abort.

Thanks

Emscripten can't find path to cmake

I've gone over the instructions several times, looked in countless forums, and still can't resolve this issue.

I'm running Windows 10, and simply trying to install Emscripten. I've got Emscripten installed:

enter image description here

I run

# Fetch the latest registry of available tools.
emsdk update

followed by

# Download and install the latest SDK tools.
emsdk install latest

enter image description here

But it continues to throw the same warning about being unable to find the path to cmake.

I've downloaded and installed cmake-3.3.2-win32-x86. I cannot create the PATH from the installation though, because it says the file length is too long. odd, because it is installed here:

C:\Program Files (x86)\CMake\bin

I figured I could set the path myself, as seen in this SO post. Therefore, I used this command after the image above:

set PATH="C:\Program Files (x86)\CMake\bin\";%PATH%

and have the same issue. I'm fresh out of ideas.

Need help Fixing these errors with classes

I need help understanding these error. I have been trying to figure out but can't get to working. Is my algorithm for adding even right?

Here is my current error:

'dem' was not declared in this scope.

I thought the header file takes care of the initialization.

Rational.h

#ifndef _RATIONAL_H_
#define _RATIONAL_H_
#include <iostream>
using namespace std;
class Rational
{


    int num; //p
    int dem; // q


public:

Rational();

Rational(int P, int Q = 1);

void display() const; // _p:_q

void add(const Rational&);

};
#endif

Rational.cpp

#include "Rational.h"
int main()


{

    Rational r1(1 ,2);
    Rational r2(1,4);
    r1.add(r2);
    r1.display();


}
void add(const Rational&h2)
{

    int  i, k;
    Rational fract;
    add(h2);

    i = dem;
    k = h2.dem;
    num*= k;
    dem*=k;
    num = +r2.num*i;
    //return

}

C++11 accessing each variadic parameter

Is it possible to split variadic parameter into list of items and access them? below you can see example of what I want to achieve - first piece, is standard, simple example of using variadic parameters

template<typename ... Types>
float sum(float first, Types ... rest)
{
    return first + sum(rest...);
}

below, you can see what I'd like to do

template<typename ... Types>
float sum(float first, Types ... rest)
{
    std::cout<<first<<std::endl;
    for(auto item : rest)
             cout<<rest<<std::endl;
}

I know I can print and do things recursively, but is there way to access params w/o recursion?

C++ Passing a reference variable to the thread in g++-4.7.4

I need to start a thread passing complex parameters (std::thread<>) as a parameter when the thread starts. I´m using `std::ref. This code works fine with updated environments (g++-4.8.2 running on Ubuntu).

Now I have to compile this same code in a old compiler (g++4.7.4) and I´m getting errors.

The code is shown below, as well as the error:

ReaderThread.hpp

class ReaderThread {
    void start(Reader reader, SyncController &syncController);
}

ReaderThread.cpp

void ReaderThread::start(Reader reader, SyncController &syncController)
{

        Do something...
}

main.cpp

int main()
{

    ...do stuff...

    /* 
     * Create and start the reader thread. The created object must live
     * during the whole thread life.
     * std::ref is used to pass as reference
     */
    myReader = ReaderFactory(params);

    std::shared_ptr<ReaderThread> ptr(new ReaderThread); 
    std::thread th(&ReaderThread::start, ptr, myReader, std::ref(syncController));


    ...do other stuff...
}

ERROR:

In file included from /usr/gcc-4.7.4/lib/gcc/i586-pc-linux-gnu/4.7.4/../../../../include/c++/4.7.4/bits/move.h:57:0,
                 from /usr/gcc-4.7.4/lib/gcc/i586-pc-linux-gnu/4.7.4/../../../../include/c++/4.7.4/bits/stl_pair.h:61,
                 from /usr/gcc-4.7.4/lib/gcc/i586-pc-linux-gnu/4.7.4/../../../../include/c++/4.7.4/bits/stl_algobase.h:65,
                 from /usr/gcc-4.7.4/lib/gcc/i586-pc-linux-gnu/4.7.4/../../../../include/c++/4.7.4/bits/char_traits.h:41,
                 from /usr/gcc-4.7.4/lib/gcc/i586-pc-linux-gnu/4.7.4/../../../../include/c++/4.7.4/ios:41,
                 from /usr/gcc-4.7.4/lib/gcc/i586-pc-linux-gnu/4.7.4/../../../../include/c++/4.7.4/ostream:40,
                 from /usr/gcc-4.7.4/lib/gcc/i586-pc-linux-gnu/4.7.4/../../../../include/c++/4.7.4/iostream:40,
                 from ./main.cpp:11:
/usr/gcc-4.7.4/lib/gcc/i586-pc-linux-gnu/4.7.4/../../../../include/c++/4.7.4/type_traits: In instantiation of 'struct std::_Result_of_impl<false, false, std::_Mem_fn<void (ReaderThread::*)(Reader, SyncController&)>, std::shared_ptr<ReaderThread>, Reader, std::reference_wrapper<SyncController> >':
/usr/gcc-4.7.4/lib/gcc/i586-pc-linux-gnu/4.7.4/../../../../include/c++/4.7.4/type_traits:1857:12:   required from 'class std::result_of<std::_Mem_fn<void (ReaderThread::*)(Reader, SyncController&)>(std::shared_ptr<ReaderThread>, Reader, std::reference_wrapper<SyncController>)>'
/usr/gcc-4.7.4/lib/gcc/i586-pc-linux-gnu/4.7.4/../../../../include/c++/4.7.4/functional:1563:61:   required from 'struct std::_Bind_simple<std::_Mem_fn<void (ReaderThread::*)(Reader, SyncController&)>(std::shared_ptr<aeirtuthread::ReaderThread>, Reader, std::reference_wrapper<SyncController>)>'
/usr/gcc-4.7.4/lib/gcc/i586-pc-linux-gnu/4.7.4/../../../../include/c++/4.7.4/thread:133:9:   required from 'std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (ReaderThread::*)(Reader, SyncController&); _Args = {std::shared_ptr<ReaderThread>&, Reader&, std::reference_wrapper<SyncController>}]'
./aeirtu/aeirtu/main.cpp:155:96:   required from here
/usr/gcc-4.7.4/lib/gcc/i586-pc-linux-gnu/4.7.4/../../../../include/c++/4.7.4/type_traits:1834:9: error: no match for call to '(std::_Mem_fn<void (ReaderThread::*)(Reader, SyncController&)>) (std::shared_ptr<ReaderThread>, Reader, std::reference_wrapper<SyncController>)'

I can´t find out if this error is being caused by the use of std::ref on older compilers or from something different.

Help appreciated.

Safely release a resource on a different thread

I have a class similiar to:

class A{
    public:
    boost::shared_ptr< Foo > m_pFoo;
}

Instances of A are destroyed on the GUI thread where they hold the last reference to a Foo. The destructor for Foo is potentially long running, causing an undesirable pause on my GUI thread. I would like for Foo to be destroyed on a separate thread, Foo's are self contained and it is not critical they get released immediately.

Currently, I use a pattern like this:

A::~A(){
    auto pMtx = boost::make_shared<boost::mutex>();
    boost::unique_lock<boost::mutex> destroyerGate(*pMtx);
    auto pFoo = m_pFoo;
    auto destroyer = [pMtx,pFoo](){
        boost::unique_lock<boost::mutex> gate(*pMtx);
    };

    m_pFoo.reset();
    pFoo.reset();
    boost::thread destroyThread(destroyer);
}

Essentially, capture it in a lambda and lock until released from the object. Is there a better way to accomplish this?

Specifying input and output ranges to algorithms

There are a number of use cases in the standard library, and I have run into my own code, situations where I want to pass an input and an output range that must be the same size, often to some algorithm. At present this requires three, or four if you want to be careful, iterators. Often there is then a bunch of checking to make sure the iterators make sense.

I am aware that array_view might, in some cases, coalesce pairs of being/end iterators but that still leaves checks required that the input and output array_views might be different size. Has there been any discussion on a class to contain both the input and the output range specifications? Maybe the range proposal solves some or all of this of this but I'm not clear how it does.

Check function overwriting in the derived class in CRTP pattern

I'm trying to implement compile-time checking of correct implementation of CRTP pattern.

Here is the code:

#include <iostream>
#include <type_traits>

using namespace std;

#define static_interface_check(BaseClass, DerivedClass, FuncName) \
    static_assert(!std::is_same<decltype(&DerivedClass::FuncName), decltype(&BaseClass<DerivedClass>::FuncName)>::value, "CRTP error: function " #BaseClass "::" #FuncName " was not overwritten in the class " #DerivedClass); 

template <class T>
class Interface
{
public:
    Interface();

    void foo1()
    {
        static_cast<T*>(this)->foo1();
    }

    void foo2()
    {
        static_cast<T*>(this)->foo2();
    }
};

// Checking inside Interface<T> declaration results in incomplete type error, so I had to move it to the default constructor
template <class T>
Interface<T>::Interface()
{
    static_interface_check(Interface, T, foo1);
    static_interface_check(Interface, T, foo2);
}

class A: public Interface<A>
{
public:
    void foo1() { cout << "A::foo1()" << endl; }
};

template <class T>
void bar(Interface<T> &obj)
{
    obj.foo1();
    obj.foo2();
}

int main()
{
    A a;
    bar(a);

    return 0;
}

It fails during compilation as expected:

error: static assertion failed: CRTP error: function Interface::foo2 was not overwritten in the class T

But I want to use also function overloading, const and non-const versions of the same function.

The question is: how can I implement it for the interface containing void foo(), void foo(int) and void foo(int) const?

Overload resolution produces ambiguous call when template parameters added

In the following code the compiler can successfully resolve the call to f() to call f(int&, const char*).

The call to g(), however, is ambiguous. It lists all four overloads as the possible overload set. If I remove , typename T2, std::size_t I from the template argument list for the array argument, and hard code them instead, there is no ambiguity and the compiler picks g(T&, const char*).

How is it that adding the two template arguments makes this ambiguous? I can see how, though decay and casting, it could resolve to any one of the overloads, but I cannot figure out how adding those template parameters introduces the ambiguity.

I have testing this on Clang 3.8 (unreleased) and VC++ 2015.

#include <string>

void f(int&, const char*){}
void f(int&, char(&)[8]){}
void f(int&, bool){}
void f(int&, const std::string&){}

template <typename T>
void g(T&, bool){}
template <typename T>
void g(T&, const char*){}
template <typename T>
void g(T&, const std::string&){}
template <typename T, typename T2, std::size_t I>
void g(T&, T2(&)[I]){}

int main(int argc, char* argv[])
{
   int i = 1;
   f(i, "       ");
   g(i, "       ");
   return 0;
}

Checking if a variable is constant qualified

I was reading about const_cast and it seemed unsafe and not very helpful. The best answer about it in SO states the it would be useful in a scenario like this:

void func(const char* param, bool modify){
    if(modify)
        //const_cast and change param
    // stuff that do not change param
}

Although this a possible use, it has its risks because you have to correctly provide the value of "modify", or else you will get an undefined behaviour since you are changing something that was supposed to be constant. I wonder if you could achieve the same functionality without having to supply this extra argument and for that you would most likely need to check the existence of a const qualifier.

The closes thing I found was the std function is_const, but it seems to be limited to a different kind of usage:

is_const<const int>::value //returns true
is_const<int>::value // returns false
const int myVar=1;
is_const<myVar>::value // what it would look like ( does not compile)

I've also tried using similar function signatures that only differ by a "const" qualifier, but that is perceived as a redefinition. So is it possible at all to do it? If so, how can it be done?

How one can use locks atomics when programming simple database? [on hold]

Suppose we have simplified key value database using std::map and each client is served by thread.

If several clients select data there is nothing to worry about.

If some client updates / delete data, there must be no selects, also there must be no two updates running at the same time.

How this can be done with locks? What will the lock looks like? What part of the code will need to check the lock?

Thing like this is done in MyISAM. How MySQL (MyISAM) is doing it?

Can this be done with atomics? Single atomic per "record" is not an option, because will be definitely expensive.

Why the `std::equal_to` is useful?

The C++ standard stbrary provides std::equal_to function. This function object invokes operator== on type T by default.

What's the benefit of using std::equal_to in a C++ code? Could you provide an example where the std::equal_to is very useful?

How to use std::lock_guard on a class member mutex

In the following code the bad method fails to compile, but the good method does not. Why is providing the explicit reference to this making a difference here?

#include <mutex>

class Foo
{
 private:
  std::mutex lock_;

 public:
  Foo() = default;
  ~Foo() = default;

  void bad();
  void good();
};

void Foo::bad()
{
  std::lock_guard<std::mutex>(lock_);
}

void Foo::good()
{
  std::lock_guard<std::mutex>(this->lock_);
}

int main()
{
  return 0;
}

compile error:

test.cpp: In member function ‘void Foo::bad()’:
test.cpp:18:36: error: no matching function for call to ‘std::lock_guard<std::mutex>::lock_guard()’
   std::lock_guard<std::mutex>(lock_);

You can play with the ideone if you want.

Why does the value assigned by get<>() in my code change outside the construct?

Why is the output of statement 2 different from that of statement 1?

// a is of type vector < tuple <int, int> >

for (auto i: a)
{
    get<0>(i)+=get<1>(i);                                       
    cout << get<0>(i) << " " << get<1>(i) << endl;              // 1
}

for (auto i: a) cout << get<0>(i) << " " << get<1>(i) << endl;  // 2

Suppose that initially, a contains [7, 3] , [9, 1]

Then 1 outputs

10 3
10 1

whereas 2 outputs

7 3
9 1

In short, the loop enclosing statement 1 seems to have no effect.

I think it has something to do with my usage of auto and not using *i to change the value, but I don't think that we can use *i in get.

Why doesn't the compiler warn about unsigned to signed conversion?

I recently got bit in the butt with this code:

std::size_t s = 10;
std::vector<int> v{s};

Rather than initialize with a size of 10, this initializes with a size of 1 with one element 10. However, the vector has an explicit constructor that takes a std::size_t. With all the hype about "use braces everywhere", I would expect many people have fallen into this trap. This could be avoided if the compiler simply warned that we were trying to turn a size_t into an int.

Why isn't the compiler required to do this?

EDIT: My original code had const std::size_t s. Apparently none of the compilers I use warn unless I remove the const. Is this a bug?

C++ variadic template iteratre vector and compare elements

I have a variadic template

template <size_t ...T>
struct Foo 
{
   vector<size_t> t;

   bool IsEqual()
   {
     //??
   }

}

I create

Foo<1,2,3,4> foo;
foo.data = {1,2,3,4};
foo.IsEqual();

How can I implement IsEqual to iterate and compare every element of array and return false / true depending if elements are in the same order as in template parametrs?

C++11 std::multiplies on vector containing 0's

I have a vector, containing the following values

0 0 1 1

And my aim is to multiply this vector and return a double, for this, I am using the std::accumulate and std::multiplies but I have noticed a problem, because there is 0's contained the returning value is always 0. For example (0 * 0 * 1 * 1) = 0

Is it possible to do use std::multiplies to ignore all values that are 0's? Technically, in this part, I am just after the result of: (1 * 1) for example.

I am using:

std::accumulate(diag1.begin(), diag1.end(), 1, std::multiplies<double>());

Where diag1 contains the values inside this example.

make_shared makes a segfault

So - I have a shared_ptr which shall get a new content. But while trying that, I get a segfault.

The class will be used by the shared_ptr later:

class MatrixClass
{
public:
  MatrixClass(const MatrixClass &other)
    : matrix(
      std::make_shared<std::vector<std::vector<MyListType> > >(
        (*other.matrix).begin(),
        (*other.matrix).end()
      )
    )
  {
  }

  MatrixClass(std::initializer_list<std::initializer_list<MyListType> > &matrixIn)
    : matrix(
      std::make_shared<std::vector<std::vector<MyListType> > >(
        matrixIn.begin(),
        matrixIn.end()
      )
    )
  {
  }

  virtual ~MatrixClass() = default;

private:
  std::shared_ptr<std::vector<std::vector<MyListType> > > matrix;
};

The class that generates the segfault:

class SomeClass
{
public:
  SomeClass()
  {
    // fill contents field of this class
    // (left out here for simplicity of the example code)

    this->Regenerate();
  }

  // calling this once is okay,
  // but twice results in Segmentation violation signal
  Regenerate()
  {
    int possibleContents = this->contents.size();
    int contentNumber = myrand(0, possibleContents - 1);
    auto matrix = this->contents[contentNumber];

    this->myMatrix = std::make_shared<MatrixClass>(
      matrix
    );
  }

  std::shared_ptr<MatrixClass> GetMatrix() const
  {
    return this->myMatrix;
  }

private:
  std::shared_ptr<MatrixClass> myMatrix;

  // contents is filled in the constructor
  std::vector<std::initializer_list<std::initializer_list<MyListType> > > contents;
};

And some code to run it:

int main()
{
  auto someClass = std::make_shared<SomeClass>();

  auto firstMatrix = someClass->GetMatrix();

  someClass->Regenerate(); // throws segfault

  auto secondMatrix = someClass->GetMatrix();

  // here would be some code to check that
  // firstMatrix does not equal secondMatrix 

  return 0;
}

So what is going wrong here?

Unique Template Class without __LINE__ or __COUNTER__ Macros

First, let me start with what I'm trying to do. I'm working on a library that makes embedding a Python interpreter in C++ code a bit easier, and I'd like to leverage some C++11 features. I'm using std::functions quite heavily, which is a problem since Python makes heavy use of classic function pointers.

I've been using fredbaba's solution found at http://ift.tt/1h79SUZ

which may not be a good idea, but the reasoning seems sound; for every std::function you'd like a pointer too, you need to create some class or struct with a static function that invokes the std::function of interest, and any class function pointers can point to the static function.

However, that means you've got to ensure every struct created is unique; the poster from that thread uses a unique integer as an identifier, which is cumbersome. In my code I use the LINE macro (COUNTER never seems to work), but that of courses forces me to put everything in one file to avoid line number conflicts.

I've found similar questions asked but none of them really do it; in order for this to work the identifier has to be a compile time constant, and many of the solutions I've found fail in this regard.

Is this possible? Can I cheat the system and get pointers to my std::functions? If you're wondering why I need to... I take a std::function that wraps some C++ function, capture it in yet another function, then store that in a std::list. Then I create a function pointer to each list element and put them in a Python Module I create.

// Store these where references are safe
using PyFunc = std::function<PyObject *(PyObject *, PyObject *)>;
std::list<PyFunc> lst_ExposedFuncs;

...

// Expose some R fn(Args...){ ... return R(); }
template <size_t idx, typename R, typename ... Args>
static void Register_Function(std::string methodName, std::function<R(Args...)> fn, std::string docs = "")
{
    // Capture the function you'd like to expose in a PyFunc
    PyFunc pFn = [fn](PyObject * s, PyObject * a)
    {
        // Convert the arguments to a std::tuple
        std::tuple<Args...> tup;
        convert(a, tup);

        // Invoke the function with a tuple
        R rVal = call<R>(fn, tup);

        // Convert rVal to some PyObject and return
        return alloc_pyobject(rVal);
    };

    // Use the unique idx here, where I'll need the function pointer
    lst_ExposedFunctions.push_back(pFn);
    PyCFunction fnPtr = get_fn_ptr<idx>(lst_ExposedFunctions.back());
}

From there on I actually do something with fnPtr, but it's not important.

Is this crazy? Can I even capture a function like that?

John

Performant way to write lambda in std accumulate when init is string.

I was implementing some code that required something like this

const auto concat = std::accumulate(ints.begin(), ints.end(), string{}, 
[](string& acc, const int& val) { return string(std::move(acc))+to_string(val);});

2 questions:
1) is it safe to move from acc?
2) is it faster(than having const string& acc argument?

Member function pointer cast, from Derived to Base class

I'm doing the following:

  • Taking a member function pointer with 3 params from a derived class.
  • Casting it to a member function pointer from the base class with 0 params.
  • Casting it to the base class with the 3 params back.
  • Calling it.

It works fine (so far), should i keep it? Thanks

EventsWarehouse is used to store and invoke events:

#include <iostream>
#include <functional>
#include <unordered_map>

class EventsWarehouse
{
public:
    typedef std::tuple<AView*, void (AView::*)()>           box_t;
    typedef std::unordered_multimap<std::string, box_t>     boxes_t;

    void        storeEvent(std::string const &event, AView *v, void (AView::*callback)())
        {
            this->_events.insert(std::make_pair(event, std::make_tuple(v, callback)));
            return ;
        }

    template<typename... Args>
    bool        fireEvent(std::string const &event, Args... args)
        {
            auto                it = this->_events.find(event);
            AView               *v;
            void                (AView::*callback_)();
            void                (AView::*callback)(Args...);

            for (; it != this->_events.end(); it++)
            {
                v = std::get<0>(it->second);
                callback_ = std::get<1>(it->second);
                /*
                ** CAST #2
                ** <void (AView::*)()>
                **  to
                ** <void (AView::*)(std::string, int, double)>
                **  before call
                */
                callback = reinterpret_cast<void (AView::*)(Args...)>(callback_);
                (v->*callback)(args...);
            }
            return (true);
        }
private:
    boxes_t         _events;

};

View classes stored in the above class:

class AView
{
protected:
    AView(){}
};

class DerivedView : public AView
{
public:
    void    fooCallback(std::string s, int i, double d)
        {
            std::cout << "DerivedView::fooCallback received " << s << ", " << i << ", " << d << std::endl;
            return ;
        }
};

Main:

int                         main(void)
    {
        DerivedView     dv;
        EventsWarehouse ewh;

        /*
        ** CAST #1
        ** <void (DerivedView::*)(std::string, int, double)>
        **  to
        ** <void (AView::*)()>
        **  for storing purpose
        */
        ewh.storeEvent("event 1", &dv, reinterpret_cast<void (AView::*)()>(&DerivedView::fooCallback));
        ewh.fireEvent("event 1", std::string("Hello World"), 42, 84.42);
        return (0);
    }

How to find all occurrences of a pattern using std::regex_search?

I have the following code to parse a bunch of part numbers (basically serial numbers of components of a product) from an arbitrarily formatted file.

auto buildPartNumberRegexString( bool preFlash ) -> std::string
{
    std::ostringstream patternBuilder;

    // The original, raw literal as tested on https://regex101.com/ is:
    //
    // @@PART_NUMBER_POST_FLASH\<\s*(\S+)\s*\,\s*(\d+)\s*\>@@
    //
    // In C++, each backslash needs to be doubled. Alternatively, we could use raw string literals ( R"\w" ).

    patternBuilder << "@@PART_NUMBER_" << ( preFlash ? "PRE" : "POST" )
        << "_FLASH\\<\\s*(\\S+)\\s*\\,\\s*(\\d+)\\s*\\>@@";

    return patternBuilder.str();
}

auto parsePartNumberAddresses( const std::string& templateFileContent, bool preFlash ) -> ParamAddressContainer
{
    const std::regex regEx( buildPartNumberRegexString( preFlash ) );
    std::smatch match;

    if ( std::regex_search( templateFileContent, match, regEx ) )
    {
        assert( match.size() > 1 );
        const std::size_t capturedGroups = match.size() - 1;

        assert( capturedGroups % 2 == 0 );
        const std::size_t partNumberAddressesFound = capturedGroups / 2;

        ParamAddressContainer results;
        results.reserve( partNumberAddressesFound );

        std::cerr << "DEBUG: capturedGroups = " << capturedGroups << ", partNumberAddressesFound = " << partNumberAddressesFound
            << "\n";

        for ( std::size_t i = 0; i < partNumberAddressesFound; ++i )
        {
            const std::size_t paramIdMatchIndex = i * 2 + 1;
            const std::string paramIdString = match.str( paramIdMatchIndex );
            const std::string paramIndexString = match.str( paramIdMatchIndex + 1 );

            results.emplace_back( util::string_funcs::fromString< ParamId_t > ( paramIdString ),
                util::string_funcs::fromString< ParamIndex_t > ( paramIndexString ) );
        }

        std::cerr << "DEBUG: Going to read the following part numbers (" << ( preFlash ? "pre" : "post" ) << "-flash):\n\n";

        for ( const auto& paramAddress : results )
        {
            std::cerr << "\t" << std::hex << std::noshowbase << paramAddress.paramId << std::dec << "<" << paramAddress.paramIndex
                << ">\n";
        }

        return results;
    }

    return ParamAddressContainer();
}

I've written the "beautified" regex (i.e. without the double backslashes required to escape the actual backslashes) in the comment in the buildPartNumberRegexString function.

A sample file that I'm using this regex on might look like this:

Component alpha;@@PART_NUMBER_POST_FLASH<F12C,0>@@
Component beta;@@PART_NUMBER_POST_FLASH<F12C,1>@@

I've tested my regex, using that same sample file, on https://regex101.com/ and it works exactly as it should, matching both occurrences and extracting the desired match groups. The problem is that, when I try to do the same thing via std::regex it only finds the first match. Now on https://regex101.com/ I had to enable the g modifier (global, All matches, don't return on first match) for the regex to find all matches. I'm assuming (hoping) that a similar flag is available for std::regex_search, but the description of the available flags (http://ift.tt/1MXKGyq) doesn't seem to list any that meets my requirements. Surely there has to be a way to find more than one occurrence of a pattern, right? Does anyone have an idea?

std::move and RVO optimizations

I've recently read how std::move can speed up code by just moving the values instead of copying them. So I made a test program to compare the speed using std::vector.

The code:

#include <iostream>
#include <vector>
#include <stdint.h>

#ifdef WIN32
#include <Windows.h>
#else
#include <sys/time.h>
#include <ctime>
#endif
#undef max

// Returns the amount of milliseconds elapsed since the UNIX epoch. Works on both
// windows and linux.

uint64_t GetTimeMs64()
{
#ifdef _WIN32
    // Windows
    FILETIME ft;
    LARGE_INTEGER li;

    // Get the amount of 100 nano seconds intervals elapsed since January 1, 1601 (UTC) and copy it
    // to a LARGE_INTEGER structure.
    GetSystemTimeAsFileTime(&ft);
    li.LowPart = ft.dwLowDateTime;
    li.HighPart = ft.dwHighDateTime;

    uint64_t ret = li.QuadPart;
    ret -= 116444736000000000LL; // Convert from file time to UNIX epoch time.
    ret /= 10000; // From 100 nano seconds (10^-7) to 1 millisecond (10^-3) intervals

    return ret;
#else
    // Linux
    struct timeval tv;

    gettimeofday(&tv, NULL);

    uint64 ret = tv.tv_usec;
    // Convert from micro seconds (10^-6) to milliseconds (10^-3)
    ret /= 1000;

    // Adds the seconds (10^0) after converting them to milliseconds (10^-3)
    ret += (tv.tv_sec * 1000);

    return ret;
#endif
}

static std::vector<std::string> GetVec1()
{
    std::vector<std::string> o(100000, "abcd");
    bool tr = true;
    if (tr)
        return std::move(o);
    return std::move(std::vector<std::string>(100000, "abcd"));
}

static std::vector<std::string> GetVec2()
{
    std::vector<std::string> o(100000, "abcd");
    bool tr = true;
    if (tr)
        return o;
    return std::vector<std::string>(100000, "abcd");
}

int main()
{
    uint64_t timer;
    std::vector<std::string> vec;

    timer = GetTimeMs64();
    for (int i = 0; i < 1000; ++i)
        vec = GetVec1();
    std::cout << GetTimeMs64() - timer << " timer 1(std::move)" << std::endl;
    timer = GetTimeMs64();
    for (int i = 0; i < 1000; ++i)
        vec = GetVec2();
    std::cout << GetTimeMs64() - timer << " timer 2(no move)" << std::endl;
    std::cin.get();
    return 0;
}

I got the following results:

Release (x86) /O2. tr = true

4376 timer 1(std::move)

4191 timer 2(no move)

Release (x86) /O2. tr = false

7311 timer 1(std::move)

7301 timer 2(no move)

The results between the 2 timers are really close and don't really differ that much. I already assumed this is because of Return value optimization (RVO) which means that my returns by value are already moved by the compiler without me knowing, right?

So then I ran new tests without any optimizations to make sure I was right. The results:

Release (x86) /Od. tr = true

40860 timer 1(std::move)

40863 timer 2(no move)

Release (x86) /Od. tr = false

83567 timer 1(std::move)

82075 timer 2(no move)

Now even though the difference between /O2 and /Od is really significant, the difference between no move or std::move (and even between tr being true or false) is minimal.

Does this mean that even though optimizations are disabled, the compiler is allowed to apply RVO or is std::move not as fast as I thought I'd be?

initialize an array of non trivialy constructible objects

I have a class Foo that operates that need a reference to be built (it will be used to work on that memory space)

template<typename T>
class Foo {
  public:
    Foo(T& value) : _value(value) {}
    ...
  private:
    T& _value;
};

I also have a linear memory space of multiple instances of T

std::array<T, SIZE> buffer;

What I'd like to build is an array of object of type Foo which maps the differents instances of my buffer. Which means each instance of Foo has to be built using the correct reference.

std::array<Foo<T>, SIZE> operators;

Still, operators is cannot be trivially initialize, and I can manage to build it by 'mapping' the buffer through the 'Foo' constructor.

Is there any way to do ? I tried using std::forward and std::initializer_list but those cannot be constructed from my buffer.

Note that I need my buffer to stay aligned for communication purposes, and I will en up overloading the Foo class to implement different behaviour for different elements of my array.

Overload based on existence of dependent type

I have two templated functions with the same name (foo). Their signatures differ only in the type of the second parameter, which is dependent on the template parameter T. What has surprised me is that I can use this to overload depending on whether T::A or T::B is an existent type. Is this something which is specially provided for in the standard (if so, a reference would be much appreciated), or am I just being dense in not recognising this as basic overload resolution?

#include <iostream>
using namespace std;

template<typename T>
void foo(T t, typename T::A* a = 0) {
  cout << "Had an A" << endl;
}

template<typename T>
void foo(T t, typename T::B* b = 0) {
  cout << "Had a B" << endl;
}

struct HasAnAType {
  typedef int A;
};

struct HasABType {
  typedef int B;
};

struct HasAAndBTypes {
  typedef int A;
  typedef int B;
};

int main() {
  HasAnAType a;
  HasABType b;
  HasAAndBTypes ab;

  foo(a);  // prints "Had an A"
  foo(b);  // prints "Had a B"
  foo(ab); // won't compile: 'ambiguous call to overloaded function'
}

For background, I discovered this was possible when looking into the implementation of std::enable_shared_from_this, which relies on this type of overloading.

Mismatch function passing lambda function as argument

I try to make a list and remove all then just keeping the positive members of it. I want to do it by passing lambda as an argument. I wonder why I get function mismatch error.

#include <vector>
#include <algorithm>
#include <functional>

template<typename T>
std::vector<T> keep(
        const std::vector<T> &original,
        std::function<bool(const T&)> useful)
{
    std::vector<T> out;
    for(T item:original)
    {
        if(useful(item))
            out.push_back(item);
    }
    return out;
}

int main()
{
    std::vector<int> a={4,6,2,-5,3,-8,13,-11,27};
    a=keep(a,[](const int& x)->bool{return x>0;});
    for(int y:a)
    {
        std::cout<<y<<std::endl;
    }
    return 0;
}

And this is the error message:

error: no matching function for call to ‘keep(std::vector<int>&, main():<lambda(const int&)>)’
     a=keep(a,[](const int& x)->bool{return x;});
                                               ^

Error C3867 Multithreading C++

I'm trying to create multiple threads to handle clicking tasks. Now Visual Studio 2015 doesn't display syntax error, however upon compiling I get the error

C3867 'action::Chrome::click': non-standard syntax; use '&' to create a pointer to member

int main()
{
    std::unique_ptr<action::Chrome>chrome(new action::Chrome());
    const std::vector<uint_16>xLocation = { 1155, 1165, 1205, 1245, 1285 };
    std::vector<uint_16>yLocation;

    //Fill yLocation
    //Yada yada, other code

    std::thread task[6];
    for(uint_8 i = 0; i < 6; i++)task[i] = std::thread((chrome->click, xLocation, yLocation[i]));
    for(uint_8 i = 0; i < 6; i++)task[i].join();
}

C++ String to double conversion in scientific notation

I want to convert a given string into double without converting the value into decimal, if the string is in scientific format.

That is 1.23e1 should be saved as 1.23e1 and not as 12.3.

I checked stringstream, strtod, boost::lexical_cast and other methods but all of these convert 1.23e1 into 12.3.

Is there a way that so that 1.23e1 can be saved as 1.23e1 instead of 12.3??

Is a move constructor created by default?

I know that a copy constructor is always created by default even if I don't explicitly create one. Is the same true for a move constructor? Let's assume a have a very simple class:

class SimpleClass
{

public:
    SimpleClass(int value) :
            member(value)
    {}

    int member;

};

Do I explicitly need to write SimpleClass(SimpleClass &&other) default to create the default move constructor or not?

Not able to store data in a private member variable from a const member function - FIX8 c++

This is my header :

class my_router_client : public FIX8::my::mine_Router {

private:
    mine_session_client& _session;
    mutable std::vector<std::string> vSymbolList;

public:
    my_router_client(mine_session_client& session) : _session(session) {}

    virtual bool operator() (const FIX8::my::SecurityList *msg) const;
    void sendToServer(FIX8::Message *); 
    void logout();
    void itertool();
    };

I am trying to save the data obtained from security list response to the vSymbolList vector. After handling security response I am trying to iterate through the vector by itertool method. But every time I end up with an empty vector. I tried printing the contents of the vector inside securitylist response function

virtual bool operator() (const FIX8::CX::SecurityList *msg) const;

and I am able to print the contents. Is it some kind of race condition inside threads?

this is the security list response handler

bool cx_router_client::operator() (const CX::SecurityList *msg) const
{
    GroupBase *dad(msg->find_group< CX::SecurityList::NoRelatedSym >());
    if (dad) {
        for (size_t cnt(0); cnt < dad->size(); ++cnt) {
            CX::Symbol symbol;
            MessageBase *details(dad->get_element(cnt));
            details->get(symbol);
            string ss; 
            ss = symbol();
            vSymbolList.push_back(ss);
//          cout << "at :: :: " << vSymbolList[cnt] << endl;

        }   
        cout << "no of symbol : " << vSymbolList.size() << endl;
        hypersleep<h_seconds>(1);
    }   

    return true;
}

Visual Studio : Compile Errors related to std library (iostream/cout)

Don't understand why this is happening. These errors only occur in visual studio...I just compiled via xcode on mac.

enter image description here

This is my actual code (although really only the beginning is significant to this issue...(because everyone wants all the code!):

#include "stdafx.h"
#include <fstream>
#include <sstream>
#include <algorithm>
#include <ctime>
#include "Student.h"
#include <iostream>
using namespace std;

Student* readStudentsFromFile(string filename, int num) {
ifstream studentsStream;
studentsStream.open(filename.c_str());
if (!studentsStream.is_open()) {
    cerr << "Couldn't open the file " << filename << endl;
    return NULL;
}
// create a new array of students with size 'num'
Student* students = new Student[num];
string name, school, sid;
int id;
// read student records from file
for (int i = 0; i < num; i++) {
    getline(studentsStream, name, ',');
    getline(studentsStream, sid, ',');
    getline(studentsStream, school);
    istringstream idConv(sid);
    idConv >> id;
    // create a student object from the record and store it in the array
    students[i] = Student(id, name, school);
}
studentsStream.close();
return students;
}


void writeStudentsToFile(Student students[], int num, string filename) {
ofstream output(filename.c_str());
output.open(filename.c_str());
for (int i = 0; i < num; i++)
{
    output << students[i].toString() << endl;
}
}


Student* findCommonStudents1(Student group1[], int len1, Student group2[],
int len2, int numCommon) {

// YOUR CODE HERE

// Hint: Two nested for loops
int tempv = 0;

Student* commonstu = new Student[numCommon];
for (int j = 0; j < len1; j++)
{
    for (int k = 0; k < len2; k++)
    {
        if (group1[j] == group2[k])
        {
            commonstu[tempv] = group1[j];
            tempv = tempv + 1;
        }

    }
}
return commonstu;
}

Student* findCommonStudents2(Student group1[], int len1, Student group2[],
int len2, int numCommon) {

bool inboth = false;
int tempv = 0;
Student* commonstu = new Student[numCommon];

sort(group2, group2 + len2);
for (int m = 0; m < len1; m++)
{
    inboth = binary_search(group2, group2 + len2, group1[m]);
    if (inboth == true)
    {
        commonstu[tempv] = group1[m];
    }
}

return 0;
}


int main() {

const int UC_SIZE = 10;
const int SMC_SIZE = 5;
const int SMC_UC_GRADS_SIZE = 2;
Student* uc = readStudentsFromFile("sample_uc_students.txt", UC_SIZE);
Student* smc = readStudentsFromFile("sample_smc_grads.txt", SMC_SIZE);*/

const int UC_SIZE = 350000;
const int SMC_SIZE = 75000;
const int SMC_UC_GRADS_SIZE = 25000;
Student* uc =   
readStudentsFromFile("uc_students.txt", 
UC_SIZE);
Student* smc = 
readStudentsFromFile("smc_grads.txt", 
SMC_SIZE);

// Rough timing
time_t start, end;

time(&start);
Student* common1 = findCommonStudents1(uc, UC_SIZE, smc, SMC_SIZE,
    SMC_UC_GRADS_SIZE);
time(&end);
cout << "Using linear search it took " << difftime(end, start) << " 
seconds."
    << endl;

sort(common1, common1 + SMC_UC_GRADS_SIZE);
writeStudentsToFile(common1, SMC_UC_GRADS_SIZE, "smc_grads_at_uc_1.txt");

time(&start);
Student* common2 = findCommonStudents2(uc, UC_SIZE, smc, SMC_SIZE,
    SMC_UC_GRADS_SIZE);
time(&end);
cout << "Using binary search it took " << difftime(end, start)
    << " seconds." << endl;

sort(common2, common2 + SMC_UC_GRADS_SIZE);
writeStudentsToFile(common2, SMC_UC_GRADS_SIZE, "smc_grads_at_uc_2.txt");

delete[] smc;
delete[] uc;
delete[] common1;
delete[] common2;
return 0;
}

lundi 28 septembre 2015

C++11 parallel For

I am trying to write a small parallel for loop. However, the output gives me 0 1, 2,3,4,5,6,7,5,4,0,0,0,0,0.. etc I'm testing if it is the way I'm passing iterators, but I'm quite sure. what is a better way to implement a template parallel for loop?

#include <iostream>
#include <iterator>
#include <vector>
#include <thread>
#include <memory>
using namespace std;

template<class InputIterator, class OutputIterator, class Func>
void parallel_for(InputIterator begin, InputIterator end, OutputIterator result, Func func )
{
    unsigned int num_elements = std::distance(begin,end);
    if( (std::thread::hardware_concurrency() == 1) || (std::thread::hardware_concurrency() > num_elements) )
    {
        func(begin,end,result);
    }
    else
    {
      std::vector<std::unique_ptr<std::thread>> tasks;
      const unsigned int num_threads = std::thread::hardware_concurrency();
      unsigned int grp = num_elements / num_threads;
      while( begin != end)
      {
        if( num_elements > grp )
            {
                tasks.push_back(unique_ptr<std::thread>(new std::thread(func, begin, begin + (grp - 1), result)));
                begin += grp;
                num_elements -= grp;
            }
        else
            {
                tasks.push_back(unique_ptr<std::thread>(new std::thread(func, begin, begin + num_elements, result)));
                begin += num_elements;
            }
      }

       for(auto & task : tasks)
        task->join();
    }

}
int main() {
    vector <int> a1= {0,1,2,3,4,5,6,7,5,4,6,7,8,8,5,4,5,6,7,4,5,6,7,8,5,4,6,7,8,9,7,5,4,5,6,7,8,6,5,4,3,33,45,67,100};
    vector<int> a2(45);

    parallel_for(a1.begin(),a1.end(),a2.begin(),[](auto a,auto b, auto c)
    {
        while(a!=b)
        {
            *c = *a;
            ++a;
            ++c;
        }
    });
    for(auto i : a2)
    cout<<i<<"\n";
    return 0;
}

How to wrap another class (c++)

I'm trying to learn to c++ after programming in other OO languages for many years.

I'm trying to create a wrapper class for another class, but having a hard time figuring out how to set this up properly.

For instance, with the following...

main.cpp

#include "foo.cpp"
#include <iostream>

int main() {
  Foo foo(42);
  std::cout << foo.get_barx() << std::endl; 
  return 0;
}

foo.cpp

#include "bar.cpp"

class Foo {
  public:
    // I'm trying to declare the member variable `m_bar` here.  I
    //   don't want to be instantiating an instance of Bar yet,
    //   but I think that might be exactly what's happening.
    Bar m_bar;

    Foo(int y) {
      // Here's where I really want to instantiate an instance of Bar
      //   and assign it to m_bar.
      Bar m_bar(y*2);
    }   

    int get_barx() {
      return m_bar.getx();
    }   
};

bar.cpp

class Bar {
  public:
    int m_x;

    // I seem to need this default constructor for the declaration
    //   of `m_bar` above, but I don't think that line should be 
    //   calling any constructors.
    Bar() { m_x = 21; };

    Bar(int x) {
      m_x = x;
    }   

    int getx() {
      return m_x;
    }   
};

When I compile and run this, I get back 21, but I expect 84. I'm pretty sure I'm doing something fundamentally wrong, and I'm pretty sure it's got something to do with how I'm declaring the m_bar member variable in Foo, but I can't figure out what the right way is to accomplish this.

Redirection from/to stream with intermediate class redirection

Suppose I can do ostream << Intermediate and I can do Intermediate << Example, can I do ostream << Example without adding a special overloading of operator<< from Example to ostream? Alternatively, is there any other approach I can use to support both serialization/deserialization using a intermediate class and still remove boilerplate? The following was my attempt:

#include <iostream>
#include <sstream>

using namespace std;

class Intermediate
{
};

ostream & operator<<(ostream &stream, const Intermediate& intermediate)
{
  (void)intermediate;
  return stream;
}

istream & operator>>(istream &stream, const Intermediate& intermediate)
{
  (void)intermediate;
  return stream;
}

class Example
{
};

Intermediate & operator<<(Intermediate &intermediate, const Example &example)
{
  (void)example;
  return intermediate;
}

Intermediate & operator>>(Intermediate &intermediate, Example &example)
{
  (void)example;
  return intermediate;
}

int main()
{
  stringstream stream;
  Intermediate intermediate;
  Example example;

  intermediate << example; // WORKS
  stream << intermediate; // WORKS

  stream << example; // ERROR

  return 0;
}

The error is cannot bind ‘std::basic_ostream<char>’ lvalue to ‘std::basic_ostream<char>&&’. c++11 compiler is enabled.

Cannot remove unwanted overloads

The function transform conducted by

const std::vector<int>         a = {1,     2,       3,       4,    5};
const std::vector<double>      b = {1.2,   4.5,     0.6};
const std::vector<std::string> c = {"hi", "howdy", "hello", "bye"};
std::vector<double> result(5);

transform<Foo> (result.begin(),
    a.begin(), a.end(),
    b.begin(), b.end(),
    c.begin(), c.end());

is to carry out a generalization of std::transform on multiple containers, outputing the results in the vector result. One function with signature (int, double, const std::string&) would apparently be needed to handle the three containers in this example. But because the containers have different lengths, we instead need to use some overloads. I will test this using these member overloads of a holder class Foo:

static int execute (int i, double d, const std::string& s) {return i + d + s.length();}
static int execute (int i, const std::string& s) {return 2 * i + s.length();}
static int execute (int i) {return 3 * i - 1;}

However, the program will not compile unless I define three other overloads that are never even called, namely with arguments (int, double), (const std::string&) and (). I want to remove these overloads, but the program won't let me. You can imagine the problem this would cause if we had more than 3 containers (of different lengths), forcing overloads with many permutations of arguments to be defined when they are not even being used.

Here is my working program that will apparently show why these extraneous overloads are needed. I don't see how or why the are forced to be defined, and want to remove them. Why must they be there, and how to remove the need for them?

#include <iostream>
#include <utility>
#include <tuple>

bool allTrue (bool a) {return a;}

template <typename... B>
bool allTrue (bool a, B... b) {return a && allTrue(b...);}

template <typename F, size_t... Js, typename Tuple>
typename F::return_type screenArguments (std::index_sequence<>, std::index_sequence<Js...>, Tuple& tuple) {
    return F::execute (*std::get<Js>(tuple)++...);
}

// Thanks to Barry for coming up with screenArguments.
template <typename F, std::size_t I, size_t... Is, size_t... Js, typename Tuple>
typename F::return_type screenArguments (std::index_sequence<I, Is...>, std::index_sequence<Js...>, Tuple& tuple) {
    if (std::get<2*I>(tuple) != std::get<2*I+1>(tuple))
        return screenArguments<F> (std::index_sequence<Is...>{}, std::index_sequence<Js..., 2*I>{}, tuple);
    else
        return screenArguments<F> (std::index_sequence<Is...>{}, std::index_sequence<Js...>{}, tuple);
}

template <typename F, typename Tuple>
typename F::return_type passCertainArguments (Tuple& tuple) {
    return screenArguments<F> (std::make_index_sequence<std::tuple_size<Tuple>::value / 2>{},
        std::index_sequence<>{}, tuple);
}

template <typename F, typename OutputIterator, std::size_t... Is, typename... InputIterators>
OutputIterator transformHelper (OutputIterator result, const std::index_sequence<Is...>&, InputIterators... iterators) {
    auto tuple = std::make_tuple(iterators...);
    while (!allTrue(std::get<2*Is>(tuple) == std::get<2*Is + 1>(tuple)...))
        *result++ = passCertainArguments<F>(tuple);
    return result;
}

template <typename F, typename OutputIterator, typename... InputIterators>
OutputIterator transform (OutputIterator result, InputIterators... iterators) {
    return transformHelper<F> (result, std::make_index_sequence<sizeof...(InputIterators) / 2>{}, iterators...);
}

// Testing
#include <vector>

struct Foo {
    using return_type = int;
    static int execute (int i, double d, const std::string& s) {return i + d + s.length();}
    static int execute (int i, const std::string& s) {return 2 * i + s.length();}
    static int execute (int i) {return 3 * i - 1;}
    // These overloads are never called, but apparently must still be defined.  
    static int execute () {std::cout << "Oveload4 called.\n";  return 0;}
    static int execute (int i, double d) {std::cout << "Oveload5 called.\n";  return i + d;}
    static int execute (const std::string& s) {std::cout << "Oveload6 called.\n";  return s.length();}
};

int main() {
    const std::vector<int>         a = {1,     2,       3,       4,    5};
    const std::vector<double>      b = {1.2,   4.5,     0.6};
    const std::vector<std::string> c = {"hi", "howdy", "hello", "bye"};
    std::vector<double> result(5);

    transform<Foo> (result.begin(),
        a.begin(), a.end(),
        b.begin(), b.end(),
        c.begin(), c.end());
    for (double x : result) std::cout << x << ' ';  std::cout << '\n';
    // 4 11 8 11 14 (correct output)
}

Declaring member reference variables in the same line

I wrote these apparently harmless lines inside my code just for naming convenience:

struct Foo{
    double vec[2];
    double& a=vec[0],b=vec[1];
};

But for some reason the variable "a" works fine and "b" does not ( it returns garbage). This is strange since it seemed to be a valid way to declare them. I then tested some alternate ways to do it:

#include <iostream>
using namespace std;
struct Foo{
    double vec[2];
    double& a=vec[0],b=vec[1]; //does not work

    double& c=vec[0];
    double& d=vec[1]; //works

    double ev,fv;
    double& e=ev,f=fv; // does not work

    double& g,h; // does not work
    Foo() : g(vec[0]) ,h(vec[1]){};

    void bar(){
        vec[0]=1;
        vec[1]=2;
        ev=1;
        fv=2;
        cout<<"a: "<<a<<endl;
        cout<<"b: "<<b<<endl;    
        cout<<"\nc: "<<c<<endl;
        cout<<"d: "<<d<<endl;
        cout<<"\ne: "<<e<<endl;
        cout<<"f: "<<f<<endl;        
        cout<<"\ng: "<<g<<endl;
        cout<<"h: "<<h<<endl;

        double& i=vec[0], j=vec[1]; //works
        cout<<"\ni: "<<i<<endl;
        cout<<"j: "<<j<<endl;
    }
};

int main(int, char **) {
    Foo X;
    X.bar();

    double vec[2];
    vec[0]=1;
    vec[1]=2;
    double& k=vec[0],l=vec[1];//works
    cout<<"\nk: "<<k<<endl;
    cout<<"l: "<<l<<endl;
}

In summary, the pairs (a,b), (e,f) and (g,h) don't work properly in the same way (i.e. the second variable returns some garbage). I know this could be easily avoided by writing like (c,d), but this whole behaviour is puzzling, specially because (a,b) fails while (i,j) and (k,l) work, even though the main difference seems to be where the declaration takes place. Why is that so?

Note: C++11 standard. Using -pedantic -Wall -Wextra in g++ did not throw any warnings

Using cin.bad() to check for integer [duplicate]

This question already has an answer here:

If I type in letters it will just print out "Please enter a positive integer value: Please enter a positive integer value:", it does not allow me to reenter an input.

cout << "Please enter a positive integer value: ";
int num;
cin >> num ;

if(cin.bad() || num <= 0 ) {
    cout << "Please enter a positive integer value: ";
    cin >> num;
}

if(cin.bad() || num <= 0 ) {
    cout << "Please enter a positive integer value: ";
    cin >> num;
}

c++11 std::regex bug?

I tried to use the regex library in c++11 on OSX using clang:

// product format
//   "AAPL  150918C00099500"
// python regex
//   "(?P<Symbol>[a-zA-Z0-9]+)\s*(?P<Expiry>\d{6})(?P<Payoff>[C|P])(?P<Strike>\d{8})"
#include <string>
#include <regex>
#include <iostream>
void parseProductString()
{
   std::string s{ "AAPL  150918C00099500" };
   std::regex pat{ R"([a-zA-Z0-9]{1,6})\s*(\d{6})([CP]{1})(\d{8})" };
   bool isMatch = std::regex_match( s, pat );
   std::sregex_iterator it( s.begin(), s.end(), pat );
   for( ; it != std::sregex_iterator{}; ++it )
   {
      std::cout << ( *it )[0] << std::endl;
   }
}

The output of the code below should be:

AAPL
150918
C
00099500

Instead it spits out

AAPL
150918
C00099
500

This seems like a bug... Does anybody know of a way around this ?

Thanks

System details:

$  uname -a
Darwin MBP.fios-router.home 14.5.0 Darwin Kernel Version 14.5.0: Wed Jul 29 02:26:53 PDT 2015; root:xnu-2782.40.9~1/RELEASE_X86_64 x86_64 i386 MacBookPro11,2 Darwin

$ g++ --version
Configured with: --prefix=/Applications/http://ift.tt/1d5DwEL --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 7.0.0 (clang-700.0.72)
Target: x86_64-apple-darwin14.5.0
Thread model: posix

Unordered_map to binary file

Why I can't write unordered_map structure to a file ?

std::ostream& operator<<(std::ostream& stream, PassLibrary const& data){
    stream << data.local_login << " " //std::string
           << data.local_pass << " "  //std::string
           << data.libs;              //std::unordered_map - error
    return stream;
}

Best regards.

g++ (tdm-1) 4.7.1 doesnt support all c++11 features

it's supposed g++ (tdm-1) 4.7.1 that comes with codeblocks for windows support all C++11 features, std::stoi(str) isnt reconized, same for other c++11 functions. (string header is included).

Do i need to look for another compiler ?

C++11 hexfloat compile-time parsing

The C99 language features the ability to directly specify the exponent and mantissa of a binary floating point literal (hence referred to as "hexfloats"), e.g. 0x1.0p0 is 1 * pow(2, 0), or 1.0. The C++11 standard includes the C99 standard library, including the ability to serialize and deserialize hexfloats from strings, but for some mysterious reason does not include the literals themslves.

(1) Why did the language committee not add this very simple feature that is pretty much essential for numeric computing?

(2) How can I implement compile-time hexfloat parsing in the C++11 subset supported by Visual Studio 2013? GCC allows hexfloat literals in C++, so this is not a problem in the GNU world.