mercredi 29 juillet 2015

Copy element of nested std::vector to std::vector

I have encountered problem in copying the element of nested std::vector to another std::vector.

Example 1

std::vector<std::vector<int>> foo;
std::vector<int> temp;
std::vector<int> goo;

foo[0].push_back(12345);
goo = foo[0]; //error

Example 2

for(int i = 0; i<foo[0].size(); i++) {temp.push_back(foo[0][i])};
goo = temp; //error

Thus, can i know where is the problem and what should i do to copy the element of a nested vector to another vector??

Output stream operator Argument Dependent Lookup (ADL) for fundamental/STL types/classes

I want to convert an unsigned char and a std::vector<unsigned char> to a hexadecimal string. Currently I am using the output stream operator<< to realize the conversion, but that approach seems to have some drawbacks regarding Argument Dependent Lookup (ADL). It just works only (without additional actions) if I put the two operators in the std namespace (see code below).

Four approaches come to my mind, to realize the conversion:

  1. Put operator operator<< in the same namespace as the type definition. Problem: The compiler doesn't find the declaration, a using statement has to be used.
  2. Put operator operator<< in the global namespace. Problem: The compiler doesn't find the declaration, I don't know how-to fix that.
  3. Put operator operator<< in the std namespace. Problem: Overrides the default behavior and feels wrong.
  4. Use some kind of wrapper/proxy in the same namespace as the type definition. Problem: I can't make it work with std::vector.

The above approaches are realized in the following source code. Approaches 1. and 2. can be tested by moving the two operator<< free functions in the std namespace to another namespace. The macro BOOST_REQUIRE_EQUAL is used, because it utilizes operator<<.

// Production code

// STL includes
#include <climits>
#include <cstdint>
#include <iomanip>
#include <ostream>
#include <vector>

// Boost includes
#include <boost/operators.hpp>
#include <boost/io/ios_state.hpp>
namespace fw {

using Byte = unsigned char;
using ByteVector = std::vector<Byte>;

// 4. Approach

class ByteWrapper final {
 public:
  ByteWrapper(Byte const kByte) : kByte_{kByte} {
    // NOOP
  }

  operator Byte() const {
    return kByte_;
  }

 private:
  Byte const kByte_;
};

inline std::ostream& operator<<(std::ostream& os, ByteWrapper const& kByte) {
  static_assert(!(CHAR_BIT & 3), "CHAR_BIT has to be a multiple of 4");
  boost::io::ios_all_saver guard{os};

  return os << std::hex << std::setfill('0') << std::uppercase
            << std::setw(CHAR_BIT >> 2) << +kByte;
}

inline ByteWrapper to_hex(Byte const kByte) {
  return {kByte};
}

class ByteVectorWrapper final
    : private boost::equality_comparable<ByteVectorWrapper> {
 public:
  ByteVectorWrapper(ByteVector const& kBytes) : kBytes_{kBytes} {
    // NOOP
  }

  // TODO(wolters): This is ugly, why can't a conversion operator be used?
  ByteVector operator() () const {
    return kBytes_;
  }

  bool operator==(ByteVectorWrapper const& kOther) const {
    return kOther.kBytes_ == kBytes_;
  }

 private:
  ByteVector const kBytes_;
};

inline std::ostream& operator<<(std::ostream& os,
                                ByteVectorWrapper const& kVector) {
  for (auto i = 0; i < (kVector().size() - 1); ++i) {
    os << to_hex(kVector()[i]) << ' ';
  }

  return os << to_hex(kVector()[kVector().size() - 1]);
}

inline ByteVectorWrapper to_hex(ByteVector const& kByteVector) {
  return {kByteVector};
}

}  // namespace fw

// 3. Approach I don't think this a correct approach, since the default
// behavior of the fundamental data type `unsigned char` and the STL template
// class `std::vector<_Tp, _Alloc>` is overwritten!

namespace std {

inline std::ostream& operator<<(std::ostream& os, fw::Byte const& kByte) {
  static_assert(!(CHAR_BIT & 3), "CHAR_BIT has to be a multiple of 4");
  boost::io::ios_all_saver guard{os};

  return os << std::hex << std::setfill('0') << std::uppercase
            << std::setw(CHAR_BIT >> 2) << +kByte;
}

inline std::ostream& operator<<(std::ostream& os,
                                fw::ByteVector const& kBytes) {
  for (auto i = 0; i < (kBytes.size() - 1); ++i) {
    // Calls `operator<<(std::ostream&, fw::Byte const&)`.
    os << kBytes[i] << ' ';
  }

  return os << kBytes[kBytes.size() - 1];
}

}  // namespace std

// Test code

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN

#include <iostream>

#include <boost/test/unit_test.hpp>

namespace {

// If the two operators would have been placed in the `fw` namespace, one of the
// following lines would be required:
//using namespace fw;
//using fw::operator<<;

BOOST_AUTO_TEST_CASE(OutputStreamOperator_Byte) {
  fw::Byte const kByte{0xA};
  std::cout << kByte << '\n';
  std::cout << fw::to_hex(kByte) << '\n';
  BOOST_REQUIRE(true);
}

BOOST_AUTO_TEST_CASE(OutputStreamOperator_ByteVector) {
  fw::ByteVector const kByteVector{0xA, 0x0, 0xF, 0x9};
  std::cout << kByteVector << '\n';
  std::cout << fw::to_hex(kByteVector) << '\n';
  BOOST_REQUIRE(true);
}

BOOST_AUTO_TEST_CASE(OutputStreamOperator_Byte_Equal) {
  fw::ByteVector const kFirstByte{0xA};
  fw::ByteVector const kSecondByte{kFirstByte};

  BOOST_REQUIRE_EQUAL(kFirstByte, kSecondByte);
  BOOST_REQUIRE_EQUAL(fw::to_hex(kFirstByte), fw::to_hex(kSecondByte));
}

BOOST_AUTO_TEST_CASE(OutputStreamOperator_ByteVector_Equal) {
  fw::ByteVector const kFirstByteVector{0xA, 0x0, 0xF, 0x9};
  fw::ByteVector const kSecondByteVector{kFirstByteVector};

  // TODO(wolters): Raises a GCC compiler error if using approach 1. or 2.
  // error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'const std::vector<unsigned char>')
  // ostr << t; // by default print the value
  //      ^

  BOOST_REQUIRE_EQUAL(kFirstByteVector, kSecondByteVector);
  BOOST_REQUIRE_EQUAL(fw::to_hex(kFirstByteVector), fw::to_hex(kSecondByteVector));
}

}  // namespace

What do you think? What is a good approach, to realize what I want? Do not rely on the output stream operators at all and use explicit free functions? What about the namespacing? If using operators, in which namespace should I put them and why?

I am using C++11 with GCC 4.7.1 and Boost 1.49.

Is constexpr always forced to be evaluated compile-time or only when it is needed? [duplicate]

This question already has an answer here:

What I meant for 'needed' is something like this.

constexpr int f(int a) {
  return a;
}

constexpr int a = f(2); // since a is constexpr, f() should be constexpr

Is is possible that f() is called in runtime if a is not constexpr?

int a = f(2);

Since a is not constexpr, f() doesn't need to be evaluated in compile-time. But I wonder if constexpr is forced to be evaluted in compile-time when all the arguments are compile-time constants.

Recognising a chess piece with bitboards

When the chessboard is stored in a variety of bitboards, how do modern chess engines recognise what type/side piece is situated on a particular cell? I'm having problems with this, since to find out what type/side piece a particular bit is, I have to always do:

if((bit_check & occupied) == 0ULL) ... // empty
else if((bit_check & white) != 0ULL) // white
    if((bit_check & white_pawns) != 0ULL) ... // white pawns
    else if((bit_check & white_rooks) != 0ULL) ... // white rooks
    ....
    else if((bit_check & white_kings) != 0ULL) ... // white kings
else if((bit_check & black) != 0ULL) // black
    if((bit_check & black_pawns) != 0ULL) ... // black pawns
    ....
    else if((bit_check) & black_kings) != 0ULL) ... // black kings

This is quite a tedious process and it has to be done quite a few times (for example, during move generation to see what is being captured). I'm not sure if I should just go with this or whether it would be faster to simply create a 64 array of type Piece[64], which will inherently store the piece type.

Which would be better, considering it will have to be millions of times, for capture analysis in the search functions. Am I doing this wrong?

mardi 28 juillet 2015

Is it possible to use std::unique_ptr to manage DLL resource?

I have many LoadLibrary in my project, and need to call FreeLibrary manually for each LoadLibrary. I want to use the std::unique_ptr with specific deleter to make it auto release my dll resource.

This is what I am trying to define:

std::unique_ptr<HMODULE, BOOL(*)(HMODULE)> theDll(LoadLibrary("My.dll"), FreeLibrary);

But the compiler complains the type does not match. I found out it expects *HMODULE from LoadLibrary. That is std::unique_ptr<A> will expect A* as its pointer type. It looks I still need to define a new class to manage DLL resource(LoadLibrary in constructor and FreeLibrary in destructor).

Is is possible to make std::unique_ptr<A> to just expect the A as its pointer type?

C++ crash when summarazing class instances

It's a simple Hello World code, which should use copy constructor to summarize objects

below is a code and output it generates

i guess the crash is because destructor called where it shouldn't (or wasn't expected by author of my C++ learning book lol), but may be you could give me few advices

i use default GNU GCC compiler of Code Blocks with extra options -std=c++11 -fno-elide-constructors (they dont matter in this case anyway)

#include <iostream>
#include <string>
#include <cstring>
#include <sstream>

using namespace std;

class MyString
{
private:
  char* Buffer;

  MyString(): Buffer(NULL)
  {
    cout << "Default constructor called" << endl;
  }

public:
  MyString( const char* InitialInput )
  {
    cout << "Constructor called for: " << InitialInput << endl;
    if(InitialInput != NULL)
    {
      Buffer = new char [strlen(InitialInput)+1];
      strcpy( Buffer, InitialInput );
    }
    else
      Buffer = NULL;
  }

  MyString operator+ (const MyString& AddThis)
  {
    cout << "operator+ called for '" << Buffer << "' to add: " << AddThis.Buffer << endl;
    MyString NewString;
    if (AddThis.Buffer != NULL)
    {
      NewString.Buffer = new char[GetLenght() + strlen( AddThis.Buffer ) + 1];
      strcpy( NewString.Buffer, Buffer );
      strcat( NewString.Buffer, AddThis.Buffer );
    }
  }

  MyString& operator= (const MyString& CopySource)
  {
    cout << "Copy assignment operator for '" << Buffer << "' to copy from: " << CopySource.Buffer << endl;
    if ((this != &CopySource) && (CopySource.Buffer != NULL))
    {
      if (Buffer != NULL)
        delete[ ] Buffer;
      // гарантирует глубокую копию с предварительным
      // резервированием собственного буфера
      Buffer = new char [strlen(CopySource.Buffer) + 1];
      // копирование оригинала в локальный буфер
      strcpy(Buffer, CopySource.Buffer);
    }
    return *this;
  }

  MyString( const MyString& CopySource )
  {
    cout << "Copy constructor for '" << Buffer << "' to copy from: " << CopySource.Buffer << endl;
    if(CopySource.Buffer != NULL)
    {
      Buffer = new char [strlen(CopySource.Buffer)+1];
      strcpy(Buffer,CopySource.Buffer);
    }
    else
      Buffer = NULL;
  }

  ~MyString()
  {
    cout << "Destructor called for: " << Buffer << endl;
    if( Buffer != NULL )
      delete [] Buffer;
  }

  int GetLenght()
  {
    return strlen(Buffer);
  }

  operator const char*()
  {
    return Buffer;
  }
};

int main( )
{
  MyString Hello("Hello ");
  MyString World("World");
  MyString CPP(" of C++");

  MyString sayHelloAgain ("overwrite this");
  sayHelloAgain = Hello + World + CPP;

  return 0;
}

the output is

Constructor called for: Hello
Constructor called for: World
Constructor called for:  of C++
Constructor called for: overwrite this
operator+ called for 'Hello ' to add: World
Default constructor called
Destructor called for: Hello World
operator+ called for '├РРРРР■   ' to add:  of C++
Default constructor called
Destructor called for: ├РРРРР■    of C++
Move assignment operator for 'overwrite this' to move from: 
<CRASH>
Process returned -1073741819 (0xC0000005)   execution time : 37.566 s
Press any key to continue.

Why is "true;" (and others) a valid line of code C++?

Adding true; / false; is clearly valid C++ code. It compiles and runs just fine.

Similarly, this is the same for statements like int;, void;, {}(no ()), 1+1;, 1 == 1;, or even just 1; ... why? (I'm using Visual C++)