mardi 27 juin 2017

C++ template specialization between map and multimap

Reading other topic here I've already wrote code detecting if class is associative container[1]. Right now in order to use equal_range I need to detect if it's normal map or multimap. Is there any way I can achieve my goal?

wcin and cin in same program to read user input

I know it is not recommended to use both narrow and wide character versions of the same stream (e.g., cin and wcin), but I need exactly this functionality.

How can I read user input safely in the same program into both narrow and wide characters?

Here is a (bad) sample program, which after reading in and printing out wch, is done. Does not wait for inputting ch, possibly reads some garbage, and does not print anything.

#include <iostream>
using namespace std;

int main()
{
    wchar_t wch[10];
    char     ch[10];

    wcin >> wch;
    wcout << wch;
    cin >> ch;
    cout << ch;
}

What would be an acceptable version of the above program that handles narrow and wide inputs (and outputs)? (Don't bother with size safety!) Thanks!

CppCoreChekcer C-Style cast warning when using range based for loop on vector

Assume the following code:

std::vector<std::string> lines;
lines.push_back("line");
for (const auto& s : lines) {
    std::cout << s;
}

At the line of the for loop I get the following warning:

C26493 Don't use C-style casts that would perform a static_cast downcast, const_cast, or reinterpret_cast.

Can someone explain where this is coming from? Im using Visual Studio 2017 Community Edition Version 15.2.

Write float nan (from C++ code) to sql server 2012

I am using following environment:
Database - Sql Server 2012
Language - C++11, Visual Studio 2015

I have a float, null parameter in a table in DB.
From my C++11 application, I want to write nan value to DB table as NULL.

I am doing following:
1. Converting nan to L"NULL" and store in CComBSTR
2. In DB, converting this string back to NULL and write this against float column.

My question: any better way of writing nan to DB in this case?
Specifically I want to avoid this CComBstr conversion as frequency of updates are quiet high and using many float parameters in table.

'invalid use of 'auto'' in building static library with Android NDK r10e

I'm building some C++ project for android to use it on unity plugin. I succeed to compile for iOS, but I get the following error for android:

~/android-ndk-r10e/sources/cxx-stl/gnu-libstdc++/4.9/include/bits/stl_algo.h:3789:14: error: invalid use of 'auto'

~/android-ndk-r10e/sources/cxx-stl/gnu-libstdc++/4.9/include/future:114:11: error: declaration of 'class std::future<void>'
 class future;

I'm using android-ndk-r10e and this CMakeLists.txt code:

cmake_minimum_required(VERSION 2.8)
project(PluginAndroid)

# Android configuration
set(CMAKE_SYSTEM_NAME Android)
set(CMAKE_SYSTEM_VERSION 19) # API level
set(CMAKE_ANDROID_ARCH_ABI armeabi-v7a)
set(CMAKE ANDROID_STL_TYPE stlport_static)
set(CMAKE_ANDROID_TOOLCHAIN_NAME arm-linux-androideabi-4.8)
set(CMAKE_CXX_STANDARD 11)


include_directories ("${PROJECT_SOURCE_DIR}/3rdParty/common/")
....

file(GLOB source_files
    "*.h"
    "*.cpp"
)

add_library(PluginAndroid STATIC ${source_files})

Any clue to fix this issue?

passing a 2D array to a function and multiplying it by two

so i Am trying to pass this array and then multiply it by 2. My code works, but it multiples it by 4 instead i think its because of the for loop inside another for loop. can someone explain how to fix this?

5x5 array:

int numbers  [5][5] = { { 1,3,5,7,9},{-2,-4,-6, -8, -10},{3,3,3,3,3},{ 55, 77, 99, 22, 33 },{ -15, -250, -350, -450, -550 } };



    // function
    int multiply_bytwo(int n[5][5])
    {

        int total_times = 0;
        for (int row = 0; row < 5; row++)
        {


            for (int col = 0; col < 5; col++)
            {
                n[row][col] = n[row][col] * 2;
            }

            return total_times;
        }
    }

lundi 26 juin 2017

C++11: Issue with a simple event loop implementation

I am trying to implement a simple event loop implementation with the following characteristics: 1. Single consumer, multiple producers 2. Looper thread starts when BasicEventLoop object is constructed and automatically ends when BasicEventLoop Is destroyed 3. No busy wait when there is no work to do

Code (.h and .cpp) pasted below. But I am seeing some issues in some cases when the object is destroyed on the thread that is owned by the object itself. This can happen with a peculiar use of shared_ptr to hold BasicEventLoop.

Here is the code: basic_event_loop.h:

#ifndef BASE_BASIC_EVENT_LOOP_H_
#define BASE_BASIC_EVENT_LOOP_H_

#include <atomic>
#include <condition_variable>
#include <functional>
#include <mutex>
#include <queue>
#include <thread>

namespace base {

// This ia basic implementation of an event loop. It does the following:
// * Spawns a new thread (a standard thread)
// * Exposes an API to add tasks to run on the background thread.
// * Continually runs tasks already queued up.
// * Shuts down the thread automatically in destructor.
class BasicEventLoop {
public:
  // Starts the event loop.
  BasicEventLoop();
  // Add a new task to run on the loop.
  void AddTask(std::function<void()> f);
  // Stops the loop and shuts down the thread.
  ~BasicEventLoop();
private:
  void RunLoop();

  std::mutex mQueueMutex;
  std::condition_variable mConditionVariable;
  std::atomic_bool mShouldQuit;
  std::queue<std::function<void()>> mTaskQueue;
  std::unique_ptr<std::thread> mEventThread;
};

}  // namespace base

#endif  // BASE_BASIC_EVENT_LOOP_H_

basic_event_loop.cpp:

#include "base/basic_event_loop.h"

#include <atomic>

using std::function;
using std::lock_guard;
using std::unique_lock;
using std::mutex;
using std::thread;

namespace base {

BasicEventLoop::BasicEventLoop()
  : mShouldQuit(false),
    mEventThread(new thread(&BasicEventLoop::RunLoop, this)) {
}

BasicEventLoop::~BasicEventLoop() {
  // Indicate the thread to stop executing tasks.
  mShouldQuit = true;
  mConditionVariable.notify_one();
  // In some cases the destructor will be caleld on the same thread that is running the loop.
  // so the thread will be waiting for itself to join. That will cause a deadlock.
  // Hence, wait for the thread to finish if it's a different thread, otherwise detach.
  if (mEventThread->get_id() != std::this_thread::get_id()) {
    if (mEventThread.get())
      mEventThread->join();
  } else {
    mEventThread->detach();
  }
}

void BasicEventLoop::AddTask(function<void()> f) {
  if (mShouldQuit)
    return;

  lock_guard<mutex> lock(mQueueMutex);
  mTaskQueue.push(f);
  mConditionVariable.notify_one();
}

void BasicEventLoop::RunLoop() {
  // The wait operation after acquiring the mutex atomically releases the 
  // mutex and suspends the execution of the thread. When the condition 
  // variable is notified, the thread is awakened and the mutex is atomically
  // reacquired.
  while(1) {
    std::function<void()> task;
    { // new scope for unique_lock
      // need unique_lock for condition_variable
      unique_lock<mutex> lock(mQueueMutex);
      // The condition variable wakes up whenever the predicate specified as the 
      // lambda is true.
      mConditionVariable.wait(lock, [&] {return !mTaskQueue.empty() || mShouldQuit; });

      // Means no tasks to process and destructor has already been called.  
      if (mTaskQueue.empty() && mShouldQuit)
        return;

      if (!mTaskQueue.empty()) {
        task = mTaskQueue.front();
        mTaskQueue.pop();
      }
    }
    task();
  }
}

}  // namespace base