lundi 1 août 2016

Best way to specialise operator<< for std::ostream and std::vector with generic template functions?

I am having trouble with the two-phase look-up as specified by the standard and (correctly) implemented by clang in connection with an overload of operator<< for std::ostream and std::vector.

Consider a very generic template function which shifts its argument into a stream (really useful only with recursion, but the simple example is enough to trigger the problem):

// generic.h
template<typename Stream, typename Arg>
void shift(Stream& s, Arg& arg) { s << arg; }

This generic.h may be used throughout a project. Then in some other file, we want to output a std::vector, so we define an overload

// vector.h
#include <iostream>
#include <vector>
std::ostream& operator<<(std::ostream& s, std::vector<int> const& v) {
  for(auto const& elem : v) { s << elem << ", "; }
  return s;
}

And the main file, we firstly (indirectly) use the generic.h and then, due to some other include, the vector overload:

// main.cpp
#include "generic.h"
#include "vector.h"

int main() {
  std::vector<int> v{1,2,3,4,5};
  shift(std::cout, v);
}

This code is accepted by GCC (5.4.0) and ICC (16.0), but clang complains call to function 'operator<<' that is neither visible in the template definition nor found by argument-dependent lookup.

The annoying thing is that clang is right and I’d like to fix this in my code. There are as far as I can see three options:

  • Move the definition of operator<< before shift(). This has the disadvantage that when including some (possibly other) files which indirectly include generic.h and vector.h, one would also have to take care to order them correctly.

  • Use a custom namespace, import everything needed from std into that namespace and define the operator on the new-namespace classes inside that namespace, so that ADL can find it.

  • Define operator<< in the std namespace. I think this is undefined behaviour.

Did I miss any option? What would be the best way in general to define overloads for functions of std-only classes (the issue does not exist if I want to shift NS::MyClass, since then I can just define the operator in NS).

How do I debug a C++ multi-threaded application?

please share if any techniques are available for debugging a multi-threaded application in C++? my basic need include - which tool to use, what is the state of other threads when a crash occurred, how to know the state of detached threads.

C++11 / Genrated constructor

I have been working on a C++ project started by someone else (who left the company). He has written a piece of code which seems to work pretty well but I cannot understand it.

Here is below a simplified version of the code:

There are two classes :

class Algo_t {
protected :
    Matrix_t m_Matrix ;
public:
    Algo_t(Matrix_t && Matrix) {
        DoSomething();
    }
};

class Matrix_t {
protected :
    std::ifstream & m_iftsream ;
public:
    Matrix_t(std::ifstream && ifstream) {
        DoSomething();
    }
};

In the main:

There is the following call in the main function:

char * pMyFileName = agrv[1] ;
Algo_t MyAlgo(ifstream(pMyFileName));

First I was very surprised that the code compiled without any error because there is no constructor of Algo_t taking ifstream as a parameter. I was more surprised to notice that this code works very well.

Are the constructor generated by the compiler or there is some new feature introduced by C++11 (with the rvalue...)?

terminate called after throwing an instance of 'std::out_of_range' what<>::stoi, with using array of strings?

I was solving this problem at topcoder. After a while I came up with a solution and tried to apply it, But now I am having some trouble with std::stoi() which is throwing an exception .I saw few answers related to stoi errors but I can't figure it out and I'm stuck, scratching my head for an hour now. Please look at my code to help and if you need a problem statement, then see the following:

The people of RGB Street have decided to paint each of their houses red, green, or blue. They've also decided that no two neighboring houses will be painted the same color. The neighbors of house i are houses i-1 and i+1. The first and last houses are not neighbors.

You will be given a String[] houses, where the ith element corresponds to house i. Each element of houses will be formatted as "R G B" (quotes for clarity only), where R, G and B are the costs of painting the corresponding house red, green, and blue, respectively. Return the minimal total cost required to perform the work.

#include <iostream>
#include <memory>
#include <vector>
#include <algorithm>
#include <string>
#include <cstring>
#include <cmath>
using namespace std;
class RGBStreet{
 public:
  int estimateCost(vector<string> houses){
   int a[50][3],ans[50][3];
   string s[3];
   for(int i=0;i<houses.size();i++){
    int k=0;
    for(int j=0;j<houses[i].length();++j){
        if(houses[i][j]!=' ')s[k]+=houses[i][j];
        else ++k;
    }
    a[i][0]=stoi(s[0]);
    a[i][1]=stoi(s[1]);
    a[i][2]=stoi(s[2]);
   }
   ans[0][0]=a[0][0];
   ans[0][1]=a[0][1];
   ans[0][2]=a[0][2];
   for(int i=1;i<houses.size();i++){
    ans[i][0]=min(ans[i-1][1],ans[i-1][2])+a[i][0];
    ans[i][1]=min(ans[i-1][0],ans[i-1][2])+a[i][1];
    ans[i][2]=min(ans[i-1][0],ans[i-1][1])+a[i][2];
   }
    return min(min(ans[houses.size()-1][0],ans[houses.size()-1][1]),ans[houses.size()-1][2]);            
     }
  };

The exact error I am getting is:

Terminate called after throwing an instance of 'std::out_of_range' what<>::stoi

I am using gcc-4.9.3 with c++11 enabled.

A standard way for getting variable name at compile time

Is there some way in C++11 or higher to achieve a similar behavior to:

int some_int;
std::string x=type_name<some_int>::value; //Theoretical code 
std::cout << x;

Result should be:

some_int

If not, is there a compiler specific way to do it? I am targeting MSVS.

C++11 constexpr causes compiler's internal error (C1001)

I am using Visual Studio 2015 Update 3.

I get a fatal error:

(code C1001) : An internal error has occurred in the compiler.

Here is the code :

template<typename T>
constexpr T epsilon = std::numeric_limits<T>::epsilon();

I read it was fixed in Visual Studio Update 2. Can someone explain me why I am getting this error? Thanks in advance.

dimanche 31 juillet 2016

Use of Union with reference

At work I've been using linux and the GCC compiler for C++11 and C++14. In some of the code at work, I've used a union to store both a reference and a pointer, as so: (Simplified to just the important parts)

struct MyStruct
{
    //Stuff
    union { double& x; double* x_ptr; };
    MyStruct(double& value) : x(value) {}
    //More stuff
};

I believe this code is clear, readable, unambiguous, and provides a convenient way to store references which can be shifted to something else. It provides easily understandable syntactic sugar without costing performance while improving readability. When I attempted to use code like this in visual studio 15, however, the code failed to compile due to "an illegal union member of type double&".

  1. Is this code illegal under the standard, or just under Visual Studio 2015?
  2. Can I MAKE it compile in Visual Studio 2015, or submit a bug report/change request/something?
  3. Is use of a union in that way bad practice?

Note: At my work, pretty much all code is written for Linux and compiled with GCC, and for my specific project, C++11 is guaranteed and GCC is the only compiler that's going to be used.