mercredi 31 décembre 2014

read data from file and manipulate


#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdlib>

using namespace std;

int main(){

//Declare file streams & open the file
ifstream input;
input.open("price.txt");

if(input.fail())
{
cout << "price.txt could not be accessed!" << endl;
exit(1);
}

string temp, test; //String data from file, to be converted to an double

//Get data from file
for(int i = 1; i <= 10; i++)
{
if(!input.eof()){
getline(input,temp); //Get 1 line from the file and place into temp
cout<< i << ". " << temp <<"\n";
test[i] = atof(temp.c_str()); //set the test variable to the double data type of the line

}
}

input.close();
return 0;
}


The question is how can I use the data I get from the file to assign to another variable so I can use the variable guy to the whole program of c++


my txt file looks like 3.00 4.00 5.00 3.20 3.00 3.55 1.60 4.90 2.00 1.50


c++11: what is its gc interface, and how to implement?

I was watching Bjarne Stroustrup's talk "The Essential C++".


In 44:26 he mentioned "C++11 specifies a GC Interface".


May I ask what is the interface, and how to implement it? Any more detailed good introduction online, or some sample codes to demonstrate it pls?


C++ reference for both LValue and Rvalue without type deduction

I was reading a good tutorial on lvalue/rvalue references. If I've understood correctly when there is type deduction something like T&& can accept both an lvalue and an rvalue.


But is there a way to achieve that without a generic class? I'd like to avoid duplicating all my methods for accepting both lvalues and rvalues. And of course avoid passing big objects by value.


What makes a singleton thread-unsafe?

I read somewhere that a singleton was thread-unsafe. I'm trying to understand why this is. If I have a singleton object like this:



class singleton final
{
public:
static singleton& instance()
{
static singleton unique;
return unique;
}

singleton() = default;
singleton(singleton const&) = delete;
singleton& operator=(singleton const&) = delete;
};


And if I have code like this:



singleton *p1, *p2;

auto t1 = std::thread([] { p1 = &singleton::instance(); });
auto t2 = std::thread([] { p2 = &singleton::instance(); });

t1.join();
t2.join();


Is it possible for p1 and p2 to point to two different singleton instances? If unique is static, does its "static" nature not take affect until it's fully initialized? If that's so, does that mean that a static object's initialization can be accessed concurrently and thus creating multiple static objects?


std::condition_variable::wait_for exits immediately when given std::chrono::duration::max

I have a wrapper around std::queue using C++11 semantics to allow concurrent access. The std::queue is protected with a std::mutex. When an item is pushed to the queue, a std::condition_variable is notified with a call to notify_one.


There are two methods for popping an item from the queue. One method will block indefinitely until an item has been pushed on the queue, using std::condition_variable::wait(). The second will block for an amount of time given by a std::chrono::duration unit using std::condition_variable::wait_for():



template <typename T> template <typename Rep, typename Period>
void ConcurrentQueue<T>::Pop(T &item, std::chrono::duration<Rep, Period> waitTime)
{
std::cv_status cvStatus = std::cv_status::no_timeout;
std::unique_lock<std::mutex> lock(m_queueMutex);

while (m_queue.empty() && (cvStatus == std::cv_status::no_timeout))
{
cvStatus = m_pushCondition.wait_for(lock, waitTime);
}

if (cvStatus == std::cv_status::no_timeout)
{
item = std::move(m_queue.front());
m_queue.pop();
}
}


When I call this method like this on an empty queue:



ConcurrentQueue<int> intQueue;

int value = 0;
std::chrono::seconds waitTime(12);

intQueue.Pop(value, waitTime);


Then 12 seconds later, the call to Pop() will exit. But if waitTime is instead set to std::chrono::seconds::max(), then the call to Pop() will exit immediately. The same occurs for milliseconds::max() and hours::max(). But, days::max() works as expected (doesn't exit immediately).


What causes seconds::max() to exit right away?


This is compiled with mingw64:



g++ --version

g++ (rev5, Built by MinGW-W64 project) 4.8.1
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Hybrid (List+Dict) container in C++11

I am in the final stages of rewriting a C++ Python wrapper.


In Python everything is a PyObject, and I have an Object class wrapping a PyObject*.


I've provided [] access. If the underlying PyObject is a dictionary, ob["key"] will retrieve its value, on the other hand if it is a sequence type, ob[42] retrieves the value.


I now want to provide for(auto x:X) type syntax.


The original project (PyCXX) comprised a base Object class, and for each Python Type derived an associated class.


Sequence types (list,tuple, set) would derive from a Sequence class, and dictionary would have a Dict class.


The Sequence class contains the machinery for a stdlib vector type container (code here). Similarly, the Dict class contains the machinery for a std::map type container (code here).


I apologise that the code is messy -- in due course I will clean it up and present it at the bottom of this question.


I would like to attempt something ambitious -- to provide functionality for both of these container types within the same Object class.


So, if the underlying PyObject is a sequence type, we can do things like: for(auto x:X), and similarly we can apply a stdlib sorting algorithm for a dictionary type.


I would like to know in advance whether this is possible, practical, ill-advised, etc.


I'm not worried about designing something that if used improperly would crash or cause undefined behaviour. My concern is to design something that if used properly provides an effortless bridge between C++ and Python.


If this is indeed possible, might someone be willing to draft a basic roadmap?


If it is impossible, a clear exposition of why would help me towards a practical ultimate design.


Poor performance SDL2 - WaitForSingleObject

I'm using SDL2 to create a cross platform, single threaded application, Mostly the development is happening on OSX where in debug i have no performance issues but on Window using much beefier hardware, and more memory (in debug) I have almost unusable performance (around 700-1000 draw calls).


Using the Very Sleepy profiler my biggest drain seems to be from SDL2 interacting with Windows API - WaitForSingleObject (rather than explicitly my application). Have I done something obviously daft here? Any way I can improve the performance?


How to retrieve table information using libcurl

I am new to using the libcurl libraries in C++ just to learn some new stuff, however i cant seem to find to much useful info on the subject with good practical examples.


I am trying to retrieve some stats from this website: http://ift.tt/1tBsZwm


For this, after the proper includes i am pulling the webpage using:



int main()
{
CURL *curl;
CURLcode res;

curl = curl_easy_init();
if(curl)
{
// Set URL
curl_easy_setopt(curl, CURLOPT_URL, "http://ift.tt/1AbOMKn
14/2015#r-madrid#all-player-positions#16#34#0#0#90#23/08/2014#14/11/2014#season#1#all-matches#total#desc#total");

// Perform the request, res will get the return code
res = curl_easy_perform(curl);

// Check for errors
if(res != CURLE_OK)
{
fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
}

// Print the code
cout << res << endl;

// Always cleanup each call to curl_easy_init
curl_easy_cleanup(curl);
}
return 0;
}


From the websites source code i can check for example that the name Messi is in Messi in . However if i run a search on the printed code i can´t see the name Messi, nor his stats anywhere. What am i missing so i can tell the site to download all the players data? Shouldnt this be done automatically when i give the URL?


I tried using something like this: Add paramethers to libcurl GET in c++ with no success.


Thanks in advance for some basic guidelines so i can continue with this.


What would be the difference between derivation and templatized using? (please see context)

I'm programming various types of binary search trees (classic, splay, reb-black, avl, Treap, randomized, etc).


For each type of tree, I define a generic class that receives as parameters the node type, the key type, and function comparison between the keys. For example, for a p AVL tree define (and implement) the following class:



template <template <typename> class NodeType, typename Key, class Compare>
class Gen_Avl_Tree
{
...
};


One reason for this approach is to separate the handling of memory of handling of tree. The tree does not care about allocate or deallocate the node simply inserts, deletes, or searches nodes with a key value; and so on with other operations. Another reason is to allow the possibility according to application circumstances that node has or not a virtual destructor.


Then, I define two classes as follows:



template <typename Key, class Compare = less<Key>>
struct Avl_Tree : public Gen_Avl_Tree<AvlNode, Key, Compare>
{
using Base = Gen_Avl_Tree<AvlNode, Key, Compare>;
using Base::Base;
};

template <typename Key, class Compare = less<Key>>
struct Avl_Tree_Vtl : public Gen_Avl_Tree<AvlNodeVtl, Key, Compare>
{
using Base = Gen_Avl_Tree<AvlNodeVtl, Key, Compare>;
using Base::Base;
};


Avl_Tree uses "normal" nodes and Avl_Tree_Vtl uses nodes with virtual destructor. Both types export the nested type Node. For instances: Avl_Tree::Node and Avl_Tree_Vtl::Node.


Appreciating the fact that both classes are functionally identical, I considered more practical to replace the previous definitions for the following:



template <typename Key, class Compare = less<Key>>
using struct Avl_Tree = Gen_Avl_Tree<AvlNode, Key, Compare>;

template <typename Key, class Compare = less<Key>>
using Avl_Tree_Vtl = Gen_Avl_Tree<AvlNodeVtl, Key, Compare>;


However, this last approach causes a compiler error (clang compiler 3.6) when the following function is instantiated:



template <template <typename, class> class TreeType,
typename Key,
class Compare = Aleph::less<Key>>
tuple<Stat, Stat, int, int> sample_tree(TreeType<Key, Compare> & tree,
gsl_rng * r, int n, int k)
{ ... }


from another function:



template < template <typename /* key */, class /* Compare */> class TreeType>
void test(unsigned long n, gsl_rng * r)
{
...
tuple<Stat, Stat, int, int> stats = sample_tree(tree, r, i, log(i)/log(2));
...
}


A line as:



test<Avl_Tree>(n, r);


causes the error:



timeAllTree.C:190:6: error: no matching function for call to 'sample_tree'
sample_tree(tree, r, i, log(i)/log(2));
^~~~~~~~~~~
timeAllTree.C:344:4: note: in instantiation of function template specialization
'test<Avl_Tree>' requested here
test<Avl_Tree>(n, r);
^
timeAllTree.C:56:29: note: candidate template ignored: could not match 'type-parameter-0-1'
against 'AvlNode'
tuple<Stat, Stat, int, int> sample_tree(TreeType<Key, Compare> & tree,
^


By contrast, Avl_Tree defined by derivation from Gen_Avl_Tree compiles and works perfectly.


My question is if there is reason to believe that Avl_Tree derived from Gen_Avl_Tree is functionally distinct from Avl_Tree declared by using. Or is this a problem with the compiler


Is there a way to initialize an array with a buffer at time of declaration?

Basically, I'm trying to do this:



char x[] = "hello";
char* y = new char[sizeof(x)](x); // won't work.


demo


Is there a way to do this cleanly? No comments on DO NOT USE raw arrays, or raw pointers please.


How to get a SFINAE expression to work with template and non-template classes?

I have made this for SFINAE:



// Type 'type' exists iff X is a base of COLLECTION
template<typename X, typename COLLECTION, typename RET_TYPE = void>
struct enable_if_is_base_of : std::enable_if<std::is_base_of<X, COLLECTION>::value, RET_TYPE>
{};


Which works well for something like this:



class A {}; class B {}; class C{};
class collection : A, B {};

template <typename X>
typename enable_if_is_base_of<X, collection>::type fn(X&& x) { }

int main() {

fn(A());
fn(B());
// fn(C()); // Fails as expected
return 0;
}


However, if I want collection to be derived from a template as well as non-template classes, I'm not sure how I would go about that.


Something like this:



class A {};
template <typename X> class B {};
class C {};
template <typename X> class D {};

template <typename X>
class collection : A, B<X> {};

C++11: track object lifetime in lambda

Sometimes, we know nothing about lifetime of lambda that captures an object state (e.g. return it from object, register it as a callback without ability to unsubscribe etc.). How to make sure that the lambda won't access already destroyed object on invocation?



#include <iostream>
#include <memory>
#include <string>

class Foo {
public:
Foo(const std::string& i_name) : name(i_name) {}

std::function<void()> GetPrinter() {
return [this]() {
std::cout << name << std::endl;
};
}

std::string name;
};

int main() {
std::function<void()> f;

{
auto foo = std::make_shared<Foo>("OK");
f = foo->GetPrinter();
}

auto foo = std::make_shared<Foo>("WRONG");

f();

return 0;
}


This program prints "WRONG" instead of "OK" (http://ideone.com/Srp7RC) just by coincidence (it seems it just reused the same memory for the second Foo object). Anyway, this is a wrong program. First Foo object is already dead when we execute f.


Proper way of using Variadic template function call with string arguments c++ [duplicate]


Hello what wrong Iam doing here in using variadic templates via string? How to use it properly to achieve the below task?



#include <iostream>
#include<string>

int sum(int a, int b, int c, int d) { return a+b+c+d; }
int strcopy(char* str) { strcpy(str,"Hello World!!!"); return 1; }

template<typename Func, typename... Args>
auto MainCall(Func func, Args&&... args)-> typename std::result_of<Func(Args...)>::type
{
return func(std::forward<Args>(args)...);
}

template<typename... funcname, typename... Args>
int CallFunction(std::string const& Func , Args&&... args)
{

if(!Func.compare("sum"))
{
return MainCall(sum, args...);
}
else if(!Func.compare("strcopy"))
{
return MainCall(strcopy, args...);
}
else
{
return 0;
}

}


int _tmain(int argc, _TCHAR* argv[])
{
char buffer[512];
cout << CallFunction("sum",1,2,3,4) << end1; /* How to properly execute "sum" function by sending string name to variadic function template function??? */
CallFunction("strcopy",buffer); /* How to properly execute "strcopy" function by sending string name to variadic function template function??? */
printf("Buffer says = %s" , buffer); /* Should print "Hello World!!!" */
getchar();
return 0;
}


I get compiler error like

error C2197: 'int (__cdecl *)(char *)' : too many arguments for Maincall

see reference to class template instantiation 'std::_Result_type<false,_Fty,_V0_t,_V0_t,_V2_t,_V2_t,_V4_t,_V4_t,_V6_t,_V6_t,std::_Nil,std::_Nil,std::_Nil,std::_Nil,std::_Nil>' being compiled


Is it possible for C++ to write a template that takes a Container as parameter?

I would try to put my point clear by an example:


We have



template <class RandomAccessIterator>
void sort (RandomAccessIterator first, RandomAccessIterator last);


But I'm think of if it is ok to make it more convenient



template <typename T> void sort(std::vector<T>& container) {
std::sort( container.begin(), container.end() );
}
template <typename T> void sort(std::list<T>& container);
template <typename T> void sort(std::array<T>& container);
//e.t.c


You know there are many container types, it is possible to code once for all the container types?



void sort(ContainerType<ElementType> &container);
//and container should have begin() and end() methods, otherwise the compiler would warn me.

mardi 30 décembre 2014

c++1y way to generate random floating point number

I need in random floating point numbers. I want to test implementations of an elementary functions in my JIT-compiler for a custom floating point type. So I do the following:



  • I testing the function (say, exp) for fixed points (say, zero -> one, one -> Euler constant, ln2 -> two)

  • Then I generate full-range floating-point numbers (adjacent to domain of the elementary function) and testing my function on them.


How to generate desired numbers? What I do at the moment is the following:



#include <iostream>
#include <iomanip>
#include <random>
#include <chrono>
#include <limits>

#include <cmath>
#include <cstdlib>

int
main()
{
using G = long double;
G const one = G(1);
std::mt19937_64 random_(static_cast< typename std::mt19937_64::result_type >(std::chrono::high_resolution_clock::now().time_since_epoch().count()));
std::uniform_real_distribution< G > zero_to_one_; // uniform [0;1) ditribution
std::uniform_int_distribution< int > uniform_int_(std::numeric_limits< G >::min_exponent - 1, std::numeric_limits< G >::max_exponent - 1);
std::cout.precision(std::numeric_limits< G >::digits10);
for (std::size_t i = 0; i < 100; ++i) {
std::cout << std::scalbn(one + zero_to_one_(random_), uniform_int_(random_)) << std::endl;
}
return EXIT_SUCCESS;
}

Why are lambda arguments passed by value read-only in C++11?

When a function takes an argument by value, it can usually modify it. However, this does not seem to be the case with lambdas. Why?



int main()
{
int x = 0;
auto lambda = [x] { x = 1; }; // error: assignment of read-only variable ‘x’
return 0;
}

c++ container with constant element indices on insertion and removal

I am working on an EventDispatcher class that implements the publish-subscribe pattern. Here is a simplified interface:



class EventDispatcher
{
friend Subscription;
public:
void publish(const std::string& event_name, std::shared_ptr<Event> event);
std::unique_ptr<Subscription> subscribe(const std::string& event_name, std::unique_ptr<Callback> callback);

private:
std::unordered_map<std::string, some_container<std::unique_ptr<Callback>>> m_subscriptions;
}


This class needs to hold a collection of callback functions for each type of event. To do this I use std::unordered_map, which maps from event names to a container of Callback functions.


The subscribe function returns a unique pointer to an Subscription instance. The job of this object is to unsubscribe from its destructor. Now, the question is how does the Subscription class unsubscribe?


It needs to remove a particular Callback pointer from some_container. Insertion, deletion and forward iteration over some_container needs to be fast. I considered the following method:



  1. Subscription stores the insertion index into some_container for the Callback pointer that it manages.

  2. The Subscription class's destructor then removes the Callback pointer from some_container at the insertion index.


That's all very simple. The problem now is which container do I use for some_container? Using the insertion index requires that the contents do not move when I remove one element. This rules out any linked list based containers in addition to std::vector. Is there common type of container that meets these requirements or do I need to create my own?


Why not multimap?


To preempt one suggestion, why not use multimap<Subscription*, std::unique_ptr<Callback>> for some_container? Whilst this would certainly work, I believe that multimap does not store its values contiguously in memory, which will probably hurt when I come to iterate over all of the callbacks subscribed to a particular event.


Why does async seem to be blocking? [duplicate]


This question already has an answer here:




I am learning how to use threading and I am having trouble understanding why the use of future makes the program run asynchronously as expected, but when I do not use it, async seems to be blocking. Why don't both of these programs take 3 seconds to run? I don't understand why Case 1 takes 6 seconds?


CASE 1: slower version


Observation: Blocking? I didn't expect this to take 6 seconds to run. I thought that calling async would spawn a separate thread of execution. But instead, it seems the function sendmsg() takes 3 seconds and then completes, and then getmsg() takes the additional 3 seconds. I don't see evidence of 2 threads being executed simultaneously here.



$ time ./filesync

real 0m6.018s
user 0m0.001s
sys 0m0.003s

$ cat main.cpp
#include <iostream>
#include <stdlib.h>
#include <future>
#include <unistd.h>

int sendmsg()
{
sleep(3);
return 5;
}

int getmsg()
{
sleep(3);
return 10;
}

int main(int argc, char** argv)
{
std::async(std::launch::async, sendmsg);
std::async(std::launch::async, getmsg);
}


CASE 2: faster version


Observation: In this case, the program only takes 3 seconds to run total! The only difference is that I am using future.



$ time ./filesync

real 0m3.017s
user 0m0.002s
sys 0m0.003s

$ cat main.cpp
#include <iostream>
#include <stdlib.h>
#include <future>
#include <unistd.h>

int sendmsg()
{
sleep(3);
return 5;
}

int getmsg()
{
sleep(3);
return 10;
}

int main(int argc, char** argv)
{
std::future<int> f1 = std::async(std::launch::async, sendmsg);
std::future<int> f2 = std::async(std::launch::async, getmsg);
int finalval = f1.get() + f2.get(); // even when I comment this line out,
// it still only takes 3 seconds to run
}

'template argument deduction/substitution failed' after addition of an argument

I need template function which will call other function with arguments taken from std::tuple. I had written some code, which compiles properly:



#include <tuple>

template<typename ...ARGS1, typename ...ARGS2>
void foo(const std::tuple<ARGS1...> &, const std::tuple<ARGS2...> &)
{
//call function
}

int main()
{
std::tuple<int, bool> tuple1(0, false);
std::tuple<double, void*, float> tuple2(0.0, nullptr, 0.0f);
foo(tuple1, tuple2);
return 0;
}


Now I need add one more argument which is pointer to function:



#include <tuple>

template<typename ...ARGS1, typename ...ARGS2>
void foo(const std::tuple<ARGS1...> &, const std::tuple<ARGS2...> &, void (*)(ARGS1..., ARGS2...))
{
//call function
}

void bar(int, bool, double, void*, float)
{
}

int main()
{
std::tuple<int, bool> tuple1(0, false);
std::tuple<double, void*, float> tuple2(0.0, nullptr, 0.0f);
foo(tuple1, tuple2, &bar);
return 0;
}


I tried to do it in many different ways but compiler always returns template argument deduction/substitution failed and inconsistent parameter pack deduction with '' and ''. I don't understand, what's wrong with my code. There is not any helpful information in compiler output.


Could somebody help me write this properly?


Generic lambdas Vs Standard template functions (What to use and When)

Generic Lambdas are a way of defining lambdas that read as follows:



auto identity = [](auto a){return a;}


Compare this with:



template <typename T>
T Identity(T t){return t;}


or with



template <typename T>
struct Identity { T operator()(T a) { return a; } };


This is my understanding




  1. lambdas allow context capture using [&], [=], etc, I am not sure how this will be used / applied in generic lambdas. Is this the main difference ?




  2. generic lambdas can be cast to function pointers whereas, template specialisation can be cast to function pointers.




A simple real world example will be useful to understand what to use and when.


[Appended] Here is the generic lambda proposal : http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3559.pdf


Why is template type deduction failing here?

Why in the following piece of code, does the template type cannot be deduced automatically from the last argument, like it does in std::condition_variable::wait ?



template< typename Predicate >
//requires Truth< Predicate >
class lock_monitor_guard
{
public:
lock_monitor_guard( std::mutex& mutex, std::condition_variable& monitor, Predicate predicate );
~lock_monitor_guard();

private:
std::unique_lock<std::mutex> lock;
std::condition_variable& monitor;
};

template< typename Predicate >
//requires Truth< Predicate >
lock_monitor_guard<Predicate>::lock_monitor_guard( std::mutex& mutex, std::condition_variable& monitor, Predicate predicate )
: lock( mutex ), monitor( monitor )
{
monitor.wait<Predicate>( lock, predicate );
}

template< typename Predicate >
//requires Truth< Predicate >
lock_monitor_guard<Predicate>::~lock_monitor_guard()
{
lock.unlock();
monitor.notify_one();
}


When I try to build a line like lock_monitor_guard guard( jobs_mutex, jobs_monitor, ([]()->bool{return true;}) );, I have an error message : use of class template 'lock_monitor_guard' requires template arguments. But why ? And why does it work with the STL std::condition_variable::wait. Thank you for any help !


Is it possible to convert a type T to a string/char* in C++11/14?

This is a follow up questions from How to convert typename T to string in c++


I am asking because I would really like to generate nice error messages like



static_assert(one_of<T,Components...>::value,
"Unable to access T because you didn't
use it in filter<Components...>.");


Would print



Unable to access Foo because you did not use it in filter<Bar,Baz,Bat>.


Is something like this now possible in C++11 / 14?


I have the following traits class(IsLexCastable) to check if a type can be converted to a string by calling boost::lexical_cast<string>. It erroneously returns true for vector<int>.



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

#include <boost/lexical_cast.hpp>

using namespace std;
using namespace boost;

namespace std
{
/// Adding to std since these are going to be part of it in C++14.
template <bool B, typename T = void>
using enable_if_t = typename std::enable_if<B, T>::type;
}

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

template <typename T>
struct IsLexCastable<T, std::enable_if_t<std::is_same<std::string, decltype(boost::lexical_cast<std::string>(std::declval<T>()))>::value> > : std::true_type
{
};

int main()
{
vector<int> a = {1, 2, 3};
// cout << lexical_cast<string>(a) << endl;
cout << IsLexCastable<decltype(a)>::value << endl;
return 0;
}


This program prints 1, but lexical_cast<string>(a) results in a compile error. What is the right way to implement IsLexCastable?


(This was compiled with g++48 -std=c++11, and boost 1.55.0.)


Getting c++11 auto initialization syntax right

I am newbie programmer in C++ (but a veteran programmer in other languages) and I am trying to use "Modern C++" in my code.


I am wondering what I am doing wrong here, trying to initialize an istream from a boost::asio::streambuf:



#include <iostream>
#include <boost/asio/streambuf.hpp>

class A {
public:
void foo();
private:
boost::asio::streambuf cmdStreamBuf_{};
};

void A::foo() {
std::istream is1{&cmdStreamBuf_}; // works
auto is2 = std::istream{&cmdStreamBuf_}; // does not compile
}


I get this error:



try.cpp:13:41: error: use of deleted function 'std::basic_istream<char>::basic_istream(const std::basic_istream<char>&)'


I am not trying to copy; I thought I was constructing an std::istream!


Why isn't abs constexpr?

In <cinttypes>, since C++11, there are the following two overloads:



std::intmax_t abs( std::intmax_t n );
std::intmax_t imaxabs( std::intmax_t n );


Why aren't those two functions constexpr?


Using move to insert into a STL container

I am trying to better understand how move works when used in inserting an element into an STL container. I am looking at a code where an objected is allocated using new (created on the heap). Later on, when an insert is done, it seems the STL container allocates a new object and calls the move constructor. Is there a way to make the STL container directly use the object (take over the object (ptr) that was alloced).


I have the following sample code for some additional questions:



#include <iostream>
#include <vector>
using namespace std;

class foo
{
public:
uint32_t i[3];
string s1;

foo()
{ cout << "def ctor" << endl; }

foo(const foo& fm)
{ cout << "copy ctor" << endl; }

foo(const foo&& fm)
{ cout << "move ctor" << endl; }

foo& operator= (const foo& fm)
{ cout << "copy assign" << endl; return *this; }
};

vector<foo> vec_f;

int main()
{
foo f1;
cout << "---" << endl;
vec_f.push_back(f1);
cout << endl;

foo f2;
cout << "---" << endl;
vec_f.push_back(move(f2));
cout << endl;

foo *f3 = new (foo);
cout << "---" << endl;
vec_f.push_back(*f3);
cout << endl;

foo *f4 = new (foo);
cout << "---" << endl;
vec_f.push_back(move(*f4));
cout << endl;
}


Output as follow:



def ctor
---
copy ctor

def ctor
---
move ctor
copy ctor

def ctor
---
copy ctor
copy ctor
copy ctor

def ctor
---
move ctor


I am ignoring the calls to the default ctor for f1, f2, f3, f4 and focusing on the calls after "---".


f1 : foo is created using copy ctor. However, is this object created as a result of the STL code doing a new OR part of passing the object by value to a function (nothing to do with STL but a compiler thing)? I am guessing the latter. If so, where is the object creation when the element is inserted into the container?


f2 : foo is created using move ctor, by the STL code, right? And why/how is the copy ctor invoked right after? Is it because f2 is created on the stack (not heap)? If so, how does the STL code figure that out?


f3 : Most puzzling to me. Guessing the first copy ctor is invoked as part of passing a parameter by value (nothing to do with STL). How/why are the other two copy ctor called.


f4 : STL invoking the move ctor, so the move ctor can use the guts of the foo object. Is it possible to make the STL code just use the ptr (since it is created on heap). My understanding is objects in STL container are created on the heap anyways.


Sorry about the long post. Hopefully someone can shed some light.


Regards, Ahmed.


What is the difference between these two forms of list initialization for std::map?

I have tested the following two forms with clang and they are both accepted:



using IntMap = std::map<int, int>;

IntMap map1 {{
{1, 1},
{2, 2},
{3, 3},
{4, 4}
}};

IntMap map2 {
{1, 1},
{2, 2},
{3, 3},
{4, 4}
};


On Visual Studio 2013, the latter example fails to compile stating there is no constructor in map that takes 4 arguments.


I'm assuming both are actually valid. What is the difference between the two? Why doesn't the second example work on Visual Studio 2013?


Transforming trees in C++

I have an heterogeneous n-ary tree made by different kind of nodes, for example:



class Node { }

class Subnode1 : public Node
{

}

class Subnode2 : public Node
{
private:
unique_ptr<Subnode1> child;

public:
Subnode1* getChild() { return child.get(); }
}

class Subnode4 : public Subnode2 { }

class Subnode3 : public Node
{
private:
list<unique_ptr<Subnode2>> children;
public:
// getter
}

// etc


The structure could contain any amount of types of nodes and it will be extended in the future.


I implemented a way to visit the tree which allows me to customize what to do when each node is visited which is basically implemented in this way:



void genericVisit(Node* node) {
if (dynamic_cast<Subnode2>(node))
visit(static_cast<Subnode2*>(node));
// etc
}

virtual void visit(Subnode2* node) {
if (node->getChild())
genericVisit(node->getChild());
}

// etc


It works nicely to traverse the tree but now I have the requirement to be able to replace subtrees with other subtrees so I'm thinking about the best approach to follow without altering the structure too much.


The best solution would have been to let getter return directly unique_ptr<Subnode2>& so that I do the visit on the unique pointers and I'm able to change the content of the smart pointer while visiting it. This would work but unique_ptr is not polymorphic, and there is no way to dispatch the call to the most specialized method, eg:



void genericVisit(unique_ptr<Node>& node) { // NON WORKING CODE
if (dynamic_cast<unique_ptr<Subnode2>&>(node))
visit(static_cast<unique_ptr<Subnode2>&>(node));
// etc
}


So I was wondering which could be the best solution to the problem, minding that while traversing the tree, as long as I change the content of the current subtree without changing the reference to that node in the parent, (which would be allowed by using an unique_ptr) I don't see any problem.


How to initialize the dynamic array of chars with a string literal in C++?

I want to do the following:



std::unique_ptr<char[]> buffer = new char[ /* ... */ ] { "/tmp/file-XXXXXX" };


Obviously, it doesn't work because I haven't specified the size of a new array. What is an appropriate way to achieve my goal without counting symbols in a string literal?


Usage of std::array is also welcome.


Update #1: even if I put the size of array, it won't work either.


Can I cast a stream of bytes into a type from an MPL typelist whose index I don't know until runtime?

So, say I have:


A list of all the types:



typedef boost::mpl::list<T1, T2, T3, T4, T5>::type types;


A list of bytes of all objects serialised:



std::array<uint8_t, 100> bytes{0x...};


A list of offsets in bytes to each object in the array:



std::array<std::size_t, 10> offsets{0, 1, 2, 3, 5, 8, 10, 11, 16, 20};


And a list of index's to types for each object in the byte array:



// T1, T1, T1, T2, T3, T2, T1, T5, T4
std::array<std::size_t, 10> offset_types{0, 0, 0, 1, 2, 1, 0, 4, 3, 4};


So now say I wanted to get object N out of the byte array:



reinterpret_cast<
boost::mpl::at_c<
types,
offset_types[N] // <-- problem...
>::type
>(bytes[offsets[N]]);


Which obviously doesn't work because I can't get offset_types[N] in < ... > scope.


Is this possible?


C++ thread and mutex and condition variable

naymenshee find common multiple of 10-million numbers in the queue does not exceed 10,000 I killed 2 days to sort out but I just do not understand! please help me



#include <condition_variable>
#include <mutex>
#include <thread>
#include <iostream>
#include <queue>
#include <chrono>
#include <cmath>
#include <map>
#include <cstdlib>
#include <fstream>
#include <ctime>
using namespace std;

int main()
{
std::map <int, int> NOK;
map<int, int> snok;
std::queue<int> oche;
std::mutex m;
std::condition_variable cond_var;
bool done = false;
bool notified = false;
int ch=0;
int d=0;
int t=0;
int s[2000];
// int rnd=0;

std::thread filev([&]() {

//std::this_thread::sleep_for(std::chrono::seconds(1));
//std::unique_lock<std::mutex> lock(m);
ifstream in; // Поток in будем использовать для чтения
int ch;
in.open("/home/akrasikov/prog/output.txt");
while(!in.eof()){
if (oche.size()>9999){
std::this_thread::sleep_for(std::chrono::milliseconds(3));
std::unique_lock<std::mutex> lock(m);

} else {
in>>ch;
oche.push(ch);
}
//cout << ch << " ";
}
//rnd=rand()%100;


// oche.pop();
notified = true;
cond_var.notify_one();


done = true;
cond_var.notify_one();
});

std::thread nok([&]() {
std::unique_lock<std::mutex> lock(m);
//while (!done) {
// while (!notified) { // loop to avoid spurious wakeups
//cond_var.wait(lock);
//}
while (!oche.empty()) {
ch=oche.front();
oche.pop();
int j=2;
while (j < sqrt((double)ch)+1){

int s=0;
while(!(ch%j)){
s++;

ch/=j;
// std::cout << j << std::endl;
}
if (s > 0 && NOK[j] < s){
NOK[j] = s;

}
j++;

}
if (NOK[ch] == 0) NOK[ch]++;
// std::cout << v << std::endl;
}
long int su=1;
int temp=-1;
int step=0;
//int st=0;
int sa=1;
//int t=0;
std::cout << " NOK= ";
for (std::map<int, int>::iterator it=NOK.begin(); it!=NOK.end(); it++){
for (int i=0; i<it->second; i++){
su*=it->first;
sa=it->first;
//cout << "sa= " << sa << "\n";

if (temp<sa && sa >1){
// cout << "sa= " << sa << "\n";
// cout << "temp=" << temp<< "\n";
//st=step;
//cout<< temp << "^"<< step << " * " ;
temp=sa;
step=1;
//cout<< temp << "^"<< step << " * " ;
} else {
if(sa>1)
step++;
}
//s[i]=it->first;
//if (s[i]==2) d++;
//if (s[i]==3) t++;

//cout<< temp << "^"<< step << " * " ;

}

//if(t>0)
cout<< temp << "^"<< step << " * " ;
//t++;
}
//cout<< temp << "^"<< step << " * " ;
//std::cout << "NOK= 2^"<< d << " 3^" << t << std::endl;
std::cout << "su = " << su << '\n';
//oche.pop();

//}
notified = false;
});


filev.join();
nok.join();

}


This program does not work! how come? what's wrong? it just starts and hangs, but if you do not clean



if (oche.size()>9999){
std::this_thread::sleep_for(std::chrono::milliseconds(3));
std::unique_lock<std::mutex> lock(m);

} else {


and



while (!done) {
while (!notified) { // loop to avoid spurious wakeups
cond_var.wait(lock);
}


everything works help plz


Why can't I pass this class as a reference when returned from arithmetic operators?

If I have a simple class like this:



template<typename T>
class coord
{
public:

coord() : x(0), y(0)
{
}

coord(T X, T Y) : x(X), y(Y)
{
}

T x;
T y;

coord& operator-=(const coord& rhs)
{
(*this).x -= rhs.x;
(*this).y -= rhs.y;
return *this;
}

coord& operator+=(const coord& rhs)
{
(*this).x += rhs.x;
(*this).y += rhs.y;
return *this;
}
};


Along with the following operators (they're not friends because there's no private members to access).



template<typename T = int>
inline coord<T> operator-(coord<T> lhs, const coord<T>& rhs)
{
lhs -= rhs;
return lhs;
}

template<typename T = int>
inline coord<T> operator+(coord<T> lhs, const coord<T>& rhs)
{
lhs += rhs;
return lhs;
}


Elsewhere in my code I have another class A with a method that looks like this:



void A::SetVarC(coord<int>& c)
{
m_c = c;
}


(assume there's a getter for m_c as well)


When I try to invoke this method using the addition and subtraction operators I overloaded:



int x = 1;
int y = 1;

A* a = new A();

coord c1(1,2);

a->SetVarC(c1 - a->GetVarC() + coord<int>(x,y));


I get an error that there's no known conversion from coord<int> to coord<int>&. I can see that my subtraction and addition operators aren't returning references, but I thought that wouldn't matter. I am using C++11... are move semantics coming into play here?


How to implement a custom allocator to be used with std::map?

I'm looking for some pointers on how to implement a custom allocator to be used with a std::map. I'm interested on populating a map with millions of entries without having an allocation for each element in the container (which is the default for this container). The reason for this is to pass data to a third party library that is using a map to store samples of a chart (QCustomPlot) and I'm feeling the performance hit when plotting large time series.


Is it possible to do this with one allocation if the size of the std::map is known in advance?


Modern UnitTest++ replacement

I'm methodically upgrading my source code to get with the C++11 times, and one of the pieces that a lot of my code interacts with is UnitTest++.


I dedicate the latter half of every one of my implementation cpp files to unit tests, so they include many



TEST(testname) {
// test code
}


declarations.


Now, UnitTest++ is about 8 years old and it still compiles great, so I have no urgent need to replace it. However I have found that it is probably no longer being maintained (though its existing features certainly seem solid enough, this is a bad sign) as the website and sourceforge are down.


So even though my code works fine now, it may benefit me now to switch to a better system earlier rather than later, because it will reduce translation burden in the future.


I looked around a bit and there seem to be a few options available to me. Particularly interesting is libunittest and others like CATCH which is header-only.


My question is for folks who have maybe had experience with UnitTest++ in the past and other unit testing systems, what has worked well for you and if you have any recommendations. I am looking for something that is extremely portable and which has zero external dependencies beyond a C++98/03 or C++11 compiler (gcc, clang, msvc) and the standard libraries, and where being header-only is a plus but not necessary.


So I guess my preferences do tend to narrow down the options quite a bit. Even with UnitTest++ I enjoy its portability and self-containedness, but I have had to write a good ~100 or so lines worth of code to extend it to be flexible for me in two ways:



  • allow me to specify specific tests to run (whether it's choosing the tests by name, or by source file in which they're implemented, or the test suite name)

  • customize reporting behavior for tests such as timing, etc


How to pass variable arguments to Variadic template function in a right way C++

Hi I got a variadic templates in C++



int sum(int a, int b) { return a + b; }

template<typename Func, typename... Args>
auto MainCall(Func func, Args&&... args)-> typename std::result_of<Func(Args...)>::type
{
return func(std::forward<Args>(args)...);
}

template <typename... Args>
int call2(Args const&... args)
{
return MainCall(sum, args...); /* calling template function MainCall,
how to pass the variable arguments to
Maincall from here?
*/
}

int _tmain(int argc, _TCHAR* argv[])
{
cout << call2(4,5) << endl;
return 0;
}


Am I doing a right way of passing arguments? I get the compiler error like this

error C3520: 'args' : parameter pack must be expanded in this context

see reference to function template instantiation 'int call2(const int &,const int &)' being compiled


What is the correct way of passing variable arguments to the MainCall template?


Note: Parameters need to be always variable so that MainCall can take any function with any number of arguments.. Just for an example I have writen sum function here..


lundi 29 décembre 2014

How to iterate over the template list in variadic templates [duplicate]


This question already has an answer here:




I'm trying to write a generic function with the following idea :



template<typename... T>
void allocateArrays (int count, int N, void** &pointers) {
pointers = new void*[N];
for (int i = 0; i < N; ++i) {
pointers[i] = malloc((sizeof(T[i])) * count);
}
}


Means, I want to get the type of a particular T on every iteration and call the sizeof function over it. But I'm not able to get how to do it exactly.


Creating a tree using std::array

The code at the bottom generates the following compile-time error. The errors goes away if I use std::vector<Node> or std::array<unique_ptr<Node>, 3>. Can someone please explain what this is about?



In file included from main.cpp:1:0: /usr/include/c++/4.9/array: In instantiation of ‘struct std::array’: main.cpp:9:23:

required from here /usr/include/c++/4.9/array:97:56: error: ‘std::array<_Tp, _Nm>::_M_elems’ has incomplete type typename _AT_Type::_Type _M_elems; ^ main.cpp:3:7: error: forward declaration of ‘class Node’ class Node




#include <array>

class Node
{
public:
Node(Node* parent, int x) : parent_(parent), x_(x) {}
Node* parent_;
int x_;
std::array<Node, 3> children_; // ERROR
};

std::unordered_map::emplace behavior with only default constructor

I am trying to gain a better understanding of std::unordered_map::emplace, and I think I understand how copy and move constructors are being utilized if they exist. I have outlined the relevant descriptions for each different usages below. If anyone finds any issues with the descriptions, please let me know.


However, what I am mostly curious about is that, what happens when ONLY the default constructor is defined? It looks like the default constructor is only called ONCE, so how is it populating the FooBar member of the newly constructed element in the unordered_map? (I'd imagine the default constructor to be called at least twice). Also, if FooBar doesn't define copy and move constructors, are there any behavioral differences for the 3 cases below?


Note: I understand that this is a trivial example where deep copies aren't an issue, so copy/move semantics doesn't really yield any significant gain. I am just using this simplified example to get my point across.



struct FooBar
{
FooBar(int* pFoo, int* pBar)
{
m_pFoo = pFoo;
m_pBar = pBar;
printf("Foobar default constructor called\n");
};

FooBar(FooBar & rhs)
{
m_pBar = rhs.m_pBar;
m_pFoo = rhs.m_pFoo;
printf("Foobar copy constructor called\n");
};

FooBar(FooBar && rhs)
{
m_pBar = rhs.m_pBar;
m_pFoo = rhs.m_pFoo;
rhs.m_pBar = nullptr;
rhs.m_pFoo = nullptr;
printf("Foobar move constructor called\n");
};

int* m_pFoo;
int* m_pBar;
};


int _tmain(int argc, _TCHAR* argv[])
{
std::unordered_map<int, FooBar> map;

//template< class... Args >
//std::pair<iterator, bool> emplace(Args&&... args);

// 1.
// Description: A lvalue of foobar1 is temporarily created, initialized, copied (via copy constructor)
// to supply the in-place constructed element's FooBar member, and destroyed
// Output (if both copy and move constructor exist): Foobar default constructor called, Foobar copy constructor called
// Output (if both copy and move constructor don't exist): Foobar default constructor called
{
FooBar foobar1 = {(int*)0xDEADBEEF, (int*)0x01010101};
map.emplace(10, foobar1);
}

// 2.
// Description: A rvalue of bar1 is temporarily created, initialized, moved (via move constructor)
// to supply the in-place constructed element's FooBar member, and destroyed
// Output (if both copy and move constructor exist): Foobar default constructor called, Foobar move constructor called
// Output (if both copy and move constructor don't exist): Foobar default constructor called
map.emplace(20, FooBar{(int*)0xDEADBEEF,(int*)0x01010101});

// 3.
// Description: A lvalue of foobar1 is temporarily created and initialized. It is then
// explicitly converted to a rvalue (via std::move), moved (via move constructor) to supply
// the in-place constructed element's FooBar member, and destroyed
// Output (if both copy and move constructor exist): Foobar default constructor called, Foobar move constructor called
// Output (if both copy and move constructor don't exist): Foobar default constructor called
{
FooBar foobar2 = {(int*)0xDEADBEEF, (int*)0x01010101};
map.emplace(30, std::move(foobar2));
}

return 0;
}


Thanks.


c++11 thread bug in visual studio 2013?

I recently find that when I tried to use c++11's thread in visual studio 2013, it generate bigger object file and exe file in release mode than debug mode. Is this indicate that the obj file contains more information in release mode that debug mode? That's so weird. Moreover, in debug mode, I tried to debug the program step by step, but the break point and step can not be located as I set in the source file, this behavior is just like in the release mode in which the program does not exactly correspond to the source file due to optimization. So can someone explain this to me? Thank you.


bind binded function as argument

I have a class foo with a method bar which takes something callable (function-pointer/ functor). this callable something should be passed to another method doit as an binded element with a third method bar_cb method.



#include <functional>
#include <iostream>

class foo {
public:
template<typename T>
void bar(T&& t) {
std::cout << "bar\n";
doit(std::bind(&foo::template bar_cb<T>, this, std::forward<T>(t)));
}

template<typename T>
void doit(T&& t) {
std::cout << "doit\n";
t();
}

template<typename T>
void bar_cb(T&& t) {
std::cout << "bar_cb\n";
t();
}
};


void lala() {
std::cout << "lala\n";
}

class functor {
public:
void operator()() {
std::cout << "functor::operator()\n";
}
};


int main() {
foo f;
functor fn;
f.bar(fn);
f.bar(std::bind(lala)); // error

return 0;
}


This works fine for functors but not for binded functions as argument for foo::bar (lala in my example). Is it possible to pass an unknowable type to a method and bind it in this method as an argument to another (and if so how)?


I know I could wrap a functor (std::function for example) around the function but since I can call an unknowable type I think there is a way to also bind it (I think I'm just missing something simple).


Here an link to an example.


C++11: Difference between Test* test = new Test; and Test* test = new Test();

Under C++11, if 'Test' is an ordinary class, is there any difference between:



Test* test = new Test;
//and
Test* test = new Test();


Note: this is the same question Do the parentheses after the type name make a difference with new? asked again, because the old thread is before C++11, while I'd like to ask if there's a difference under c++11 stadard.


The accepted answer of that question says:



  • In C++1998 there are 2 types of initialization: zero and default In

  • C++2003 a 3rd type of initialization, value initialization was added.


I understand that C++11 only has 2 initialization, default and value. So i fancy the answer are a bit different?


Deadlocks related to scheduling

On the Oracle docs for multithreading they have this paragraph about deadlocks when trying to require a lock:



Because there is no guaranteed order in which locks are acquired, a problem in threaded programs is that a particular thread never acquires a lock, even though it seems that it should.


This usually happens when the thread that holds the lock releases it, lets a small amount of time pass, and then reacquires it. Because the lock was released, it might seem that the other thread should acquire the lock. But, because nothing blocks the thread holding the lock, it continues to run from the time it releases the lock until it reacquires the lock, and so no other thread is run.



Just to make sure I understood this, I tried to write this out in code (let me know if this is a correct interpretation):



#include <mutex>
#include <chrono>
#include <thread>
#include <iostream>

std::mutex m;

void f()
{
std::unique_lock<std::mutex> lock(m); // acquire the lock
std::cout << std::this_thread::get_id() << " now has the mutex\n";

lock.unlock(); // release the lock
std::this_thread::sleep_for(std::chrono::seconds(2)); // sleep for a while

lock.lock(); // reacquire the lock
std::cout << std::this_thread::get_id() << " has the mutex after sleep\n";
}

int main()
{
std::thread(f).join(); // thread A
std::thread(f).join(); // thread B
}


So what the quote above is saying is that the time during which the lock is released and the thread is sleeping (like the code above) is not sufficient to guarantee a thread waiting on the lock to acquire it? How does this relate to deadlocks?


How to declare non-initialized static std::array of self member, with private constructor?

Sorry if title is confusing, I couldn't find an easy way to write it in a simple sentence. Anyways, the issue I'm facing:



// header:
class SomeThing
{
private:
SomeThing() {} // <- so users of this class can't come up
// with non-initialized instances, but
// but the implementation can.
public:
SomeThing(blablabla ctor arguments);

static SomeThing getThatThing(blablabla arguments);

static void generateLookupTables();
private:

// declarations of lookup tables
static std::array<SomeThing, 64> lookup_table_0;
static SomeThing lookup_table_1[64];
};


The getThatThing function is meant to return an instance from a lookup table.



// in the implementation file - definitions of lookup tables

std::array<SomeThing, 64> SomeThing::lookup_table_0; // error

SomeThing Something::lookup_table_1[64]; // <- works fine


I just can't use a std::array of Something, unless I add a public ctor SomeThing() in the class. It works fine with old-style arrays, I can define the array, and fill it up in the SomeThing::generateLookupTables() function. Apparently the type std::array<SomeThing, 64> does not have a constructor. Any ideas on how to make it work, or maybe a better structure for this concept?


Storing lambdas as members confusion

I was reading Scott Meyer's Effective Modern C++ and hit the item in which he's suggesting usage of lambdas in place of std::function and std::bind. I understand his argument and his claim about drawbacks of std::function and I agreed with him.


As of today, I decided to switch to templates for storing lambdas (which do not need mutators). I do understand that type of every lambda is only known to the compiler and even two identical lambdas will have different types so how come the following code compiles and works just fine?



template<typename LambdaT>
class CaptureLambda
{
public:
CaptureLambda(const LambdaT& fn)
: mActionFn(fn) // initialize mActionFn to a user supplied lambda
{}

private:
LambdaT mActionFn{ []{} }; // initialize mActionFn to an empty lambda
};


My point of confusion is that, how come mActionFn is default initiated to an empty lambda with a different type inside member declarations but the constructor of the class is happily accepting another type of lambda in its arguments? are they castable to each other? if yes, why the following makes the compiler sad?



// Class stuff...

template<typename T>
void resetActionFn(const T& newFn) { // setter member
mActionFn = newFn;
}

// Class stuff...

I can no longer assign char[M][N] types into a std::vector on gcc 4.9

I was using gcc 4.8 until I upgraded Ubuntu, now I have gcc-4.9.1-16. Code which used to compile without warnings and run fine now no longer compiles.



static const unsigned WIDTH = 16;
static const unsigned VSCALE = 1;
static const unsigned HEIGHT = WIDTH / VSCALE;
static const unsigned FOOTER = 2;

typedef char Row [WIDTH + 1];
typedef Row World [HEIGHT - FOOTER];

std :: vector <World> m_levels;

World levels [] =
{
{
" ",
" ",
" ",
" ",
" ",
" ### ### ",
" ",
"1122112211221122",
" 33003300330033 ",
"1122112211221122",
" 33003300330033 ",
" ",
" ",
" "
},
{
" 44 ",
" 555 55 ",
" 66 66 ",
" 777 777 ",
" 66 66 ",
" 777 777 ",
" 66# #66 ",
" 777 # # 777 ",
" 66 # # 66 ",
" 777 # # 777 ",
" 66# #66 ",
" 555 55 ",
" 44 ",
" "
}
};

// The next line is line 68
m_levels .assign (std :: begin (levels), std :: end (levels));


The final line errors with



.../foo.cpp:68:62: required from here /usr/include/c++/4.9/bits/stl_algobase.h:373:4: error: static assertion failed: type is not assignable


.../foo.cpp:68:62: required from here /usr/include/c++/4.9/bits/stl_construct.h:75:7: error: parenthesized initializer in array new [-fpermissive]



The compile options have not changed, they are -W -Wall -Wextra -Werror -pedantic --std=c++0x as far as I can tell only gcc has changed.


Why does this code no longer compile?


static_cast with an explicit rvalue conversion operator

I am writing a simple wrapper class, and I want to provide explicit conversion operators to the wrapped type. The following code compiles fine with gcc



class wrap
{
double value;
public:
explicit wrap(double x) : value(x) {}
explicit operator double&&() && { return std::move(value); }
};

int main() {
wrap w(5);
double && x (std::move(w) ); //ok
double && y = static_cast<double&&>(std::move(w)); //clang reports an error here
}


But clang reports an error: cannot cast from lvalue of type 'typename std::remove_reference<wrap &>::type' (aka 'wrap') to rvalue reference type 'double &&'; types are not compatible.


As far as I know (see the latest draft, 5.2.9 §4) static_cast<T>(e) has the same semantic has T t(e), but clang does not refuse the latter.


Which compiler is right?


Force evaluation of constexpr static member

I have a problem when I want to check certain template-parameters for their validity using some helper struct and constepxr functions. As long as there is no reference to the static constexpr member I want to initialize the compiler decides not to evaluate the expression. The code I use is the following:



#include <cstddef>
#include <iostream>

#define CONSTEXPR static constexpr
using namespace std;

template<size_t ... Sizes>
struct _size_check_impl
{
static_assert(sizeof...(Sizes) != 0, "Dimension has to be at least 1");
CONSTEXPR size_t dimension = sizeof...(Sizes);
};

template<size_t ... Sizes>
constexpr size_t check_sizes()
{
return _size_check_impl<Sizes...>::dimension;
}

template<size_t ... Sizes>
struct Test
{
static constexpr size_t Final = check_sizes<Sizes...>();
};

int main()
{
Test<> a; // This shouldn't get through the static assert
Test<1, 2> b; // Passing
Test<2> c; // Passing
// cout << Test<>::Final; // With this it works just fine, bc Final is accessed
return 0;
}


Is there a way I can do this, some proxy dependecy that forces the compiler to evaluate the Final value if constexpr are evaluated? Is there another, clean way to check this property clean and quickly?


How to `std::bind()` a standard library algorithm?

The short version of my question is this: How can I use something like std::bind() with a standard library algorithm?


Since the short version is a bit devoid of details, here is a bit of an explanation: Assume I have the algorithms std::transform() and now I want to implement std::copy() (yes, I realize that there is std::cpopy() in the standard C++ library). Since I'm hideously lazy, I clearly want to use the existing implementation of std::transform(). I could, of course, do this:



struct identity {
template <typename T>
auto operator()(T&& value) const -> T&& { return std::forward<T>(value); }
};
template <typename InIt, typename OutIt>
auto copy(InIt begin, InIt end, OutIt to) -> OutIt {
return std::transform(begin, end, to, identity());
}


Somehow this implementation somewhat feels like a configuration of an algorithm. For example, it seems as if std::bind() should be able to do the job but simply using std::bind() doesn't work:



namespace P = std::placeholders;
auto copy = std::bind(std::transform, P::_1, P::_2, P::_3, identity());


The problem is that the compiler can't determine the appropriate template arguments from just the algorithm and it doesn't matter if there is an & or not. Is there something which can make an approach like using std::bind() work? Since this is looking forward, I'm happy with a solution working with anything which is already proposed for inclusion into the C++ standard. Also, to get away with my laziness I'm happy to do some work up front for later easier use. Think of it this way: in my role as a library implementer, I'll put things together once such that every library user can be lazy: I'm a busy implementer but a lazy user.


In case you want to have a ready-made test bed: here is a complete program.



#include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>
#include <utility>
#include <vector>

using namespace std::placeholders;

struct identity {
template <typename T>
T&& operator()(T&& value) const { return std::forward<T>(value); }
};


int main()
{
std::vector<int> source{ 0, 1, 2, 3, 4, 5, 6 };
std::vector<int> target;

#ifdef WORKS
std::transform(source.begin(), source.end(), std::back_inserter(target),
identity());
#else
// the next line doesn't work and needs to be replaced by some magic
auto copy = std::bind(&std::transform, _1, _2, _3, identity());
copy(source.begin(), source.end(), std::back_inserter(target));
#endif
std::copy(target.begin(), target.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
}

What is %:%: doing in this macro definition?

Consider the following code:



#include <iostream>
#define f(a,b) a%:%:b

int main()
{
int wtf = 0;
std::cout << f(wt,f) << '\n';
}

// output: 0


(live demo)


How is this possible? What magic is %:%:?!


Create type copies

How do you create type copies? For example, how do I create types Mass, Acceleration and Force which are not implicitly convertible to double(or any other numeric type), but otherwise have all the characteristics of a double. This would allow a compile-time input validity check for this function:



Force GetForceNeeded(Mass m, Acceleration a);


ensuring that GetForceNeeded can only be called with arguments of type Mass and Acceleration.


Of course, I could achieve this by manually creating a copy of the type:



class Force final
{
public:
//overload all operators
private:
double value;
};


but this is cumbersome. Is there a generic solution?


How do I alias a template specialization?

I have a type T that has a member function fn with a return type RT. I have a template that takes T and RT as parameters. I'd like to alias this template class so that my code isn't so ugly and hard to read. How would I accomplish that?



template <typename X, typename Y>
struct I
{};

struct T
{
int& fn(int);
};


So I want to alias this or something like this type so I can write a function like this:



template <typename C>
I< typename std::remove_reference<std::decltype(std::declval(C).fn(0))>::type, C> fn(C& c)
{
return I< typename std::remove_reference<std::decltype(std::declval(C).fn(0))>::type, C>();
}


But with less mess. I've not used std::decltype before, so I'm not even sure if I'm using it right as I was getting errors.


I was thinking about using a function like that and doing a decltype on it, but I was having some difficulty with it and I'd like it to look cleaner too.


Use std::swap between vectors or vector::swap?

Given two std::vector v1, v2.

I was wondering what are the benefits to use std::swap(v1, v2) over v1.swap(v2).


I have implemented a simple test code (I am not sure it is pertinent) regarding performance point of view :



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

#define N 100000

template<typename TimeT = std::chrono::microseconds>
struct Timer
{
template<typename F, typename ...Args>
static typename TimeT::rep exec(F func, Args&&... args)
{
auto start = std::chrono::steady_clock::now();
func(std::forward<Args>(args)...);
auto duration = std::chrono::duration_cast<TimeT>(std::chrono::steady_clock::now() - start);
return duration.count();
}
};

void test_std_swap(std::vector<double>& v1, std::vector<double>& v2)
{
for (int i = 0; i < N; i ++)
{
std::swap(v1,v2);
std::swap(v2,v1);
}
}

void test_swap_vector(std::vector<double>& v1, std::vector<double>& v2)
{
for (int i = 0; i < N; i ++)
{
v1.swap(v2);
v2.swap(v1);
}
}

int main()
{
std::vector<double> A(1000);
std::generate( A.begin(), A.end(), [&]() { return std::rand(); } );
std::vector<double> B(1000);
std::generate( B.begin(), B.end(), [&]() { return std::rand(); } );
std::cout << Timer<>::exec<void(std::vector<double>& v1, std::vector<double>& v2)>(test_std_swap, A, B) << std::endl;
std::cout << Timer<>::exec<void(std::vector<double>& v1, std::vector<double>& v2)>(test_swap_vector, A, B) << std::endl;
std::cout << Timer<>::exec<void(std::vector<double>& v1, std::vector<double>& v2)>(test_std_swap, A, B) << std::endl;
std::cout << Timer<>::exec<void(std::vector<double>& v1, std::vector<double>& v2)>(test_swap_vector, A, B) << std::endl;
}


According to outputs it seems that vector::swap seems faster without optimization -O0. Output is (in microseconds) :



20292
16246
16400
13898


And with -O3 there is no revelant difference.



752
752
752
760

Why do I get a compilation error with this declaration? [duplicate]


This question already has an answer here:




I can't understand why I get this error with the GCC compiler:



#include <string>
using namespace std;

void main()
{
string s();
s = "wtf";
return 0;
}

// output: error: non-object type 'std::string ()' is not assignable




Yes, yes, fine, I was after 30 Minutes or Less. Didn't go so well.


But since you're all keen to point out that I know what I'm talking about in reality, you should read up on the most vexing parse because this is not it!!


How to overload -> operator in C++ [duplicate]


As per the title, how to overload -> operator in C++?


I can't find any documentation.


cppreference glosses over it.


The Wikipedia page on overloading similarly glosses over it.


Operator overloading <-- this SO post again has a '->' shaped hole in it, although one comment gives a hint:



operator->() is actually extremely weird. It's not required to return a value_type* -- in fact, it can return another class type, provided that class type has an operator->(), which will then be called subsequently. This recursive calling of operator->()s proceeds until a value_type* return type occurs. Madness! :)



It appears that this particular operator is not straightforward to overload.


Could someone link to documentation, or (preferably) provide some here?


PS I recognisze this is an unusual overload, I have need of it in a Proxy pattern, here


How to match a sequence of whitespaces with c++11 regex


std::string str = "ahw \t\n";
std::regex re(R"((\s)*)");
std::smatch mr;
if (std::regex_search(str, mr, re))
{
std::cout << "match found: " << mr.size() << "\n";
for (size_t i = 0; i < mr.size(); ++i)
{
std::string strrep = mr.str(i);
int len = mr.length(i);
std::cout << "index: " << i << "len : " << len << " string: '" << strrep << "'\n";
}
}
std::string newStr = std::regex_replace(str, re, "");
std::cout << "new string: '" << newStr << "'\n";


result:


vc12_regex_result


What I expect: only 1 match, strrep should be ' \t\n', and len should be len(strrep) = 6. But both vc12 and gcc4.9.2 show the above result.


What's wrong with my understand? How could I match the whitespace sequence ' \t\n'?


Am i wrong or is this a Visual Studio 2013 regex bug?

I have a regex which is to remove extra vml tags from a html page.



std::string regstr = R"(<!\[if !vml\]>([\s\S]*?)<!\[endif\]>)";
std::regex regex(regstr, std::regex_constants::ECMAScript);
std::smatch mr;
std::string str = R"(</v:shape><![endif]--><![if !vml]>
<img width=234 height=383 src="http://file/C:\Users\jcyangzh\AppData\Local\Temp\msohtmlclip1\01\clip_image002.png" v:shapes="110x110">
<![endif]></span></span><span lang=EN-US><o:p></o:p></span></p>)";
if (std::regex_search(str, mr, regex)) {
std::cout << "match found: " << mr.size() << "\n";
for (size_t i = 0; i < mr.size(); ++i) {
std::string strrep = mr.str(i);
std::cout << "index: " << i << "\n string: " << strrep << "\n\n";
}
}


For GNU GCC Compiler 4.9.2(latest tdm-gcc windows port), the above code works. The regex I used does match.


gcc_regex_match_result


But for visual studio 2013 update 4 the regex does not work, std::regex_search return false.


If I replace the key pattern [\s\S] with (\s|\S), there will be 3 matches. vc_2013_update4_regex_match_result


My problem: Is [\s\S] a valid c++11 ecma regex, or is this a bug of VS2013 update4?


How to delete process image file?

I want to delete an executable file while it is executing itself on Windows. I don't think that'll do any harm on the process as the same can be done by executing '.exe' from USB and then removing it - which doesn't affect the process in anyway.


I tried the most simple way without a luck:



extern wchar_t *pExePath;

DeleteFileW(pExePath);


Then I tried using native API:



UNICODE_STRING name;

static wchar_t strdrvPrefis [] {L"\\??\\"};

static wchar_t strObjectName[MAX_PATH];

name.Length = (name.MaximumLength = wcslen(pExePath) * sizeof(wchar_t) + (sizeof(strdrvPrefis) - sizeof(wchar_t)));

name.Buffer = strObjectName;

OBJECT_ATTRIBUTES objFile{};

objFile.Length = sizeof(OBJECT_ATTRIBUTES);

objFile.ObjectName = &name;

wcscat(strObjectName, strdrvPrefis);

wcscat(strObjectName, pExePath);

NtDeleteFile(&objFile);


Which fails with ACCES_DENIED if I rember corectly.


Then I tried 'NtFsControlFile' but without success too:



HANDLE hFile;

IO_STATUS_BLOCK info;

NTSTATUS RetNt = NtOpenFile(&hFile, FILE_READ_DATA | FILE_WRITE_DATA, &objFile, &info, 0, FILE_NON_DIRECTORY_FILE | FILE_RANDOM_ACCESS | FILE_OPEN_REPARSE_POINT | FILE_NO_INTERMEDIATE_BUFFERING);

RetNt = NtFsControlFile(hFile, nullptr, nullptr, nullptr, &info, 0x000900A0 /*FSCTL_DELETE_OBJECT_ID*/, nullptr, 0, nullptr, 0);

NtClose(hFile);


Right now the above snippet will fail at 'NtOpenFile'. If I remove 'FILE_WRITE_DATA' from it's second argument then 'NtFsControlFile' will fail with 'STATUS_ACCESS_DENIED'.


Any ideas how to achieve this?


I'm using VC++ 2013.


Why does using std::forward on an rvalue reference cause destruction of the object being referenced?


#include <functional>
#include <memory>
#include <iostream>

struct A
{
~A() {std::cout << "~A()" << std::endl;}
};

void test(std::shared_ptr<A> ptr)
{
std::cout << (ptr ? "not empty" : "empty") << std::endl;
}

void forwarder(std::function<void(std::shared_ptr<A>)> f, std::shared_ptr<A>&& ptr)
{
f(std::forward<std::shared_ptr<A>>(ptr));
f(std::forward<std::shared_ptr<A>>(ptr));
}

void main()
{
forwarder([](std::shared_ptr<A> ptr){ test(ptr); }, std::make_shared<A>());
}


The problem is in the forwarder function. After the first call to test the shared_ptr is destructed - along with the A object, obviously. So in the second call to test the pointer is already empty. I don't understand why that happens. std::forward implementation is trivial.

So, I have 2 questions:

1. How does std::forward cause the destruction of the rvalue object being passed to it? Which bit of code does that?

2. How can this C++ design decision be explained? Seems counter-intuitive to me that ptr is not out of scope yet but is already dead.


How to overload -> operator in C++

I'm trying to wrap a Python PyObject* in an Object class. In Python, everything is a PyObject*. A list is a PyObject*, and each item in the list is itself a PyObject*. Which could even be another list. etc.


I'm trying to allow fooList[42] = barObj style syntax by means of a Proxy pattern (here).


Now that I have that working, I want to extend it. Object has a lot of methods, and currently fooList[42].myMethod() is going to first resolve fooList[42] into a Proxy instance, say tmpProxy, and then attempt tmpProxy.myMethod().


This means I would have to relay all Object's methods through Proxy (i.e. I would have to create the corresponding method in Proxy that relays), which is ugly.


I can't see any perfect solution (see the above linked answer), but I would be happy to use fooList[42]->myMethod() as a compromise, seeing as -> CAN be overloaded (as opposed to . Which cannot).


However, I can't find any documentation for overloading operator->.


My best guess is that it must return a pointer to some object (say pObj), and C++ will invoke pObj->whatever.


Below is my attempted implementation. However, I'm running into a 'taking the address of a temporary object of type Object' warning.


I have, within my Object class:



const Object operator[] (const Object& key) const {
return Object{ PyObject_GetItem( p, key.p ) };
}


NOTE that 'const Object&' runs into 'taking the address of a temporary object of type Object' warning.



class Proxy {
private:
const Object& container;
const Object& key;

public:
// at this moment we don't know whether it is 'c[k] = x' or 'x = c[k]'
Proxy( const Object& c, const Object& k ) : container{c}, key{k}
{ }

// Rvalue
// e.g. cout << myList[5] hits 'const Object operator[]'
operator Object() const {
return container[key];
}

// Lvalue
// e.g. (something = ) myList[5] = foo
const Proxy& operator= (const Object& rhs_ob) {
PyObject_SetItem( container.p, key.p, rhs_ob.p );
return *this; // allow daisy-chaining a = b = c etc, that's why we return const Object&
}

const Object* operator->() const { return &container[key]; }
// ^ ERROR: taking the address of a temporary object of type Object
};


The idea is to allow myList[5]->someMemberObj = ... style syntax.


myList[5] resolves as a Proxy instance, which is wrapping an Object (the sixth element of myList). Let's call it myItem.


Now I want someProxy->fooFunc() or someProxy->fooProperty to invoke myItem.fooFunc() or myItem.fooProperty respectively.


I'm running into a 'taking the address of a temporary object of type Object' warning.


c++ why */ in quoted string ends a multiline comment

I have the following piece of code:



/*
string x = "this is a */ test string"
*/


Question


Why */ in the string: "this is a */ test string ends the multi-line comment and thus making the code un-compilable?


Notes



  1. I know how to overcome that but I'm more interested in why was it defined that way?

  2. this issue is generated due to string translation. translating this string abcd with this translation mapping a->1, b->*, c->/, d->2 generates this string 1*/2 which lead to this issue (when the string is defined within multi-line comment).