samedi 31 janvier 2015

How to probe std::mute?

I have two threads. Both are talking to GPU. The first one is responsible for rendering the other one for loading stuff. When the first one is actually rendering and not doing other things the second one has to stop. They can run in parallel but that will introduce framerate spikes. So it's ok to make one loop in loading thread but no more. I implemented this behavior with std::mutex but i don't like it since the second thread is actually toggling mutex and could slow down rendering thread. How can it be implemented in cleaner way?



//Master thread
{
std::lock_guard<std::mutex> lg(gpuMutex);
// rendering
}

//Slave thread
while(true) {
gpuMutex.lock();
gpuMutex.unlock();
// loading
}

Are two calls to cout less efficient than one?

I have two questions:




  1. Is two calls to std::cout less efficient than one?




  2. If yes, does the compiler (usually) optimize it and generate equal assembly for the three cases shown below?




For example:



std::cout << "a" << "b";


or



std::cout << "ab";


or



std::cout << "a";
std::cout << "b";


I ask, because I think the last one is the most readable for a longer list of text to output.


Factory pattern using variadic template?

I have an abstract class



template <class T> struct A { /* virtual methods */ };


and several concrete derived classes with various constructors



// The constructor of B takes 1 input
template <class T>
struct B
: public A<T>
{
B() { /* default ctor */ }
B( T *input ) { /* initializer */ }

// .. implement virtual methods
}


// The constructor of C takes 2 inputs
template <class T>
struct C
: public A<T>
{
double some_member;

C() { /* default ctor */ }
C( T *input, double& value ) { /* initializer */ }

// .. implement virtual methods
}


I created a Factory that returns pointers to A, and I am trying to use variadic templates to forward inputs to the constructor of the selected derived class. It is working fine, but I had to duplicate the code for the cases with/without constructor inputs, and I am looking for a way to prevent code duplication (see below).



template <class T>
struct A_Factory
{
typedef std::shared_ptr<A> out_type;

// Version without constructor inputs
static out_type create( id_type id )
{
out_type out;
switch (id)
{
// .. select the derived class
case Type_B:
out.reset( new B() );
break;
}
return out;
}

// Version with constructor inputs
template <class... Args>
static out_type create( id_type id, Args&&... args )
{
out_type out;
switch (id)
{
// .. select the derived class
case Type_B:
out.reset( new B( std::forward<Args>(args)... ) );
break;
}
return out;
}
};


Very sorry for the long question. Any suggestion to make this shorter appreciated.


C++11 in Windows Phone 8.0 project

currently I have to port an existing mobile application which runs on Android and IOS to Windows 8. Unfortunately it is using a lot of C++11 Stuff, which is not supported by Windows Phone 8.0. The project itself was written with cocos2d-x 2.0. It contains a C# Part which loads a C++ library with the major part of the application. Also it includes modules from "Project Angle", which is a library to convert OpenGL calls into DirectX calls.


The first thing I tried was to upgrade the project to Windows Phone 8.1 using the 'reassign project' option from Visual Studio. I still had to remove a bit of C++11 Code, but now at least the project itself compiles. After compiling I got some linker errors for functions like 'getenv'. The angle libraries don't even compile and gives me errors like 'Cant find include file vccorlib.h' for every single source file. Since I'm completely new to Windows development, I don't know if something went wrong on upgrading the projects, or if I have to fix something within the projects. But I tried to upgrade an other project, which was already ported to WP8, and got the same errors.


Now I have to deceide if I have to fix the Windows Phone 8.1 version or if it's easier to remove C++11 Code for 8.0 (which means a few days of work and let my heart bleed)


I also found a compiler update for Visual Studio 2012, which has extended support for C++11, but it seems it's not compatible for Windows Phone.


I hope someone of you could give me a hint, what I have missed for WP 8.1 or has another idea. Thanks for your help!


Find Occurrences in Array

I Have to find the occurrences of every element in array. So far My code is this



void Occurrences()
{
int numers[10],count = 0,i;
for(i =0;i<10;i++)
{
cout<<"Enter Number";
cin>>numers[i];
}
for( i = 0;i<10;i++)
{
for(int j = 0;j<10;j++)
{
if(numers[i] == numers[j])
{
count++;
}
}
cout<<numers[i]<<" is Occur "<<count<<" Time in Array"<<endl;
count = 0;

}



}
int main()
{
Occurrences();
}


Output is coming multiply same numbers i.e if I entered six 1 and 4 2's. Output is 1 is occur 6 time in array. 1 is occur 6 time in array. 1 is occur 6 time in array. 1 is occur 6 time in array. 1 is occur 6 time in array. 1 is occur 6 time in array. 2 is occur 4 time in array. 2 is occur 4 time in array. 2 is occur 4 time in array. 2 is occur 4 time in array. But I want output like this 1 is occur 6 time in array. 2 is occur 4 time in array. How do I do this?


How to enable the _Generic keyword

I have this test source:



#include <stdio.h>

int main()
{
int x;

printf("x=%d\n", _Generic('x', int: 1, default: 0));
return 0;
}


Compiling with c++ 4.9.2 fails:



t.cpp: In function ‘int main()’:
t.cpp:7:33: error: expected primary-expression before ‘int’
printf("x=%d\n", _Generic('x', int: 1, default: 0));
^
t.cpp:7:41: error: expected primary-expression before ‘default’
printf("x=%d\n", _Generic('x', int: 1, default: 0));
^
t.cpp:7:51: error: ‘_Generic’ was not declared in this scope
printf("x=%d\n", _Generic('x', int: 1, default: 0));


The compiler arguments are:



c++ --std=c++11 t.cpp -o t


What am I doing wrong?


Check traits for all variadic template arguments

Background : I've created the following class C, whose constructor should take N variables of type B& :



class A;
class B
{
A* getA();
};

template<size_t N>
class C
{
public:
template<typename... Args>
inline C(Args&... args) :
member{args.getA()...}
{}
private:
std::array<A*, N> member;
};


Problem : my problem is how to constraint the variadic Args to be all of type B ?


My partial solution : I wanted to define a predicate like :



template <typename T, size_t N, typename... Args>
struct is_range_of :
std::true_type // if Args is N copies of T
std::false_type // otherwise
{};


And redefine my constructor accordingly :



template <typename... Args,
typename = typename std::enable_if<is_range_of_<B, N, Args...>::value>::type
>
inline C(Args&... args);


I've seen a possible solution on this post : http://ift.tt/1uMxNKa, which defines a generic check_all predicate :



template <template<typename> class Trait, typename... Args>
struct check_all :
std::false_type
{};

template <template<typename> class Trait>
struct check_all<Trait> :
std::true_type
{};

template <template<typename> class Trait, typename T, typename... Args>
struct check_all<Trait, T, Args...> :
std::integral_constant<bool, Trait<T>::value && check_all<Trait, Args...>::value>
{};


So, I could write something like :



template <typename T, size_t N, typename... Args>
struct is_range_of :
std::integral_constant<bool,
sizeof...(Args) == N &&
check_all<Trait, Args...>::value
>
{};


Question 1 : I don't know how to define the Trait, because I need somehow to bind std::is_same with B as first argument. Is there any means of using the generic check_all in my case, or is the current grammar of C++ incompatible ?


Question 2 : My constructor should also accept derived classes of B (through a reference to B), is it a problem for template argument deduction ? I am afraid that if I use a predicate like std::is_base_of, I will get a different instantiation of the constructor for each set of parameters, which could increase compiled code size...


c++: portable solution to cast and compare member-function pointers

Before I ask what I want to know, here's a little background: I'm wrapping a std::function in my own class Function, which stores some additional data along with the std::function object. Later on, I have a std::vector<Function<Signature>> that stores a whole bunch of Function's of the same signature (e.g. void(int)). These std::function's may represent normal free functions, functors, or member functions that have been bound to an object using std::bind.


At some later point, I want to traverse the std::vector, and check some properties of the Function objects. For example, I want to select every Function that is bound to a particular member-function (regardless of the object it will be called on). This means I have to find a way to store these member-function pointers, while discarding their exact type. In other words, I need to be able to store a pointer of type void (A::*)() and another pointer of type void (B::*)() in the same field.


I used to do this using a union to 'cast' the member-function-pointer to a void*, but then found out that member-function-pointers are implementation-defined and don't have the same size as pointers. Now I'm looking for a portable solution, and this is what I came up with:



class MemFunPtr
{
friend bool operator==(MemFunPtr const &lhs, MemFunPtr const &rhs);

enum { SIZE = sizeof(void(MemFunPtr::*)()) };
char buf[SIZE];

public:
template <typename T, typename R, typename ... Args>
MemFunPtr(R (T::*ptr)(Args ...))
{
union
{
R (T::*memfcn_)(Args ...);
char buf_[SIZE];
} caster;

caster.memfcn_ = ptr;
memcpy(buf, caster.buf_, SIZE);
}
};

bool operator==(MemFunPtr const &lhs, MemFunPtr const &rhs)
{
return memcmp(lhs.buf, rhs.buf, MemFunPtr::SIZE) == 0;
}


Now my question is, if this is portable. I would be even more happy with a more straightforward way of doing this. I looked in to std::mem_fn, but it seems that the type of these objects is unspecified (the examples on cppreference.com use auto), so I don't think this is where the solution lies.


Brace-initialization of an array of structs in c++11

Here is my code:



#include <string>

struct A
{
int a;
std::string sa;
};

int main()
{
A arr[3]{};
}


When I compile it with gcc 4.8.2 (on Ubuntu 14.04) with -std=gnu++11 option I get the following error:



example.cpp: In function ‘int main()’:
example.cpp:11:14: internal compiler error: in gimplify_init_constructor, at gimplify.c:4271
A arr[3]{};
^


Why does it throw an internal compiler error? Is it a compiler bug?


Default value for function argument which is pointer to member

I'm trying to implement decorator for functions using variadic templates. And try to minimize number of overloads since it reduce the size of a compiler error messages in case of template params deducion failure. I have implementation which works with any member of any class (works with delegate Ret (Ctx::*member)(Args...)) and one extra overload which do not take pointer to member function and just calls first version passing &Ctx::opeator(). I've tried to remove extra overload by adding default value for member pointer argument here. Here is the version which compiles:



template<
typename Decorator,
typename Ctx, typename R, typename... Args,
typename... CTorArgs
>
Decorator decorate(
CTorArgs&&...cargs,
const Ctx &obj, R (Ctx::*member)(Args...) const = &Ctx::operator()
) {
return Decorator(
std::function<R(Args...)>([&obj, member](Args... args){
return (obj.*member)(args...);
}),
std::forward(cargs)...
);
}


But it can't be called without explicit member function specification. Here is an example I'm playing with right now:



struct IntDecorator {
IntDecorator(std::function<std::string(std::string)> func):
m_func(func) {}

std::string operator() (int val) {
std::ostringstream oss;
oss << val;
return m_func(oss.str());
}
private:
std::function<std::string(std::string)> m_func;
};

struct PrefixAdder {
PrefixAdder(std::string prefix): m_prefix(prefix) {}
std::string addPrefix(std::string val) const {return m_prefix + val;}
std::string operator() (std::string val) const {return m_prefix + val;}
private:
std::string m_prefix;
};

int main(int, char**) {
PrefixAdder p("+++> ");
std::cout << decorate<IntDecorator>(p, &PrefixAdder::addPrefix)(123) << std::endl;
std::cout << decorate<IntDecorator>(p, &PrefixAdder::operator())(123) << std::endl;
std::cout << decorate<IntDecorator>(p)(123) << std::endl; // compilation error
}


compiler can't deduce type R (member function return type). The code works after adding extra overload which I try to elliminate or by specifying all template parameters which is even worse than extra overload:



template<typename Decorator, typename Ctx, typename... CTorArgs>
Decorator decorate(CTorArgs&&...cargs, const Ctx &obj) {
return decorate<Decorator>(cargs..., obj, &Ctx::operator());
}


Can I have automatic type dedution without additional version of decorate template? What is the problem to deduce types automatically here in C++11?


vendredi 30 janvier 2015

gdb catches segfault on loading symbols

Recently, I started having troubles debugging my product with GDB. I found the root of the problem, but not yet a workaround.


My code is written in C++11 with extensive use of meta programming. To catch and fix possible crashes, it is compiled with debug info, which is used for demangling on SIGSEGV handler.


Extending the project made some of the tuples grow pretty big.


I narrowed the problem down to: uncomment one type in one tuple, and catch a SegFault in gdb on loading symbols.


Googling this appeared a to be a tedious task. And debugging gdb with gdb haven't brought more insight either. The only thing I found - is a similar bug, but that tracker states it is fixed and confirmed fixed in my version of gdb (7.7.1)


I'm using Ubuntu 14.04 as a dev-box, Centos7 for production servers, and here is the output of "gdb --args gdb ":



xxx@xxx$ gdb --args gdb ./epayworker
GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2) 7.7.1
Copyright (C) 2014 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://ift.tt/KpOJT7;
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://ift.tt/xLrliR;.
Find the GDB manual and other documentation resources online at:
<http://ift.tt/1gENejF;.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from gdb...(no debugging symbols found)...done.
(gdb) run
Starting program: /usr/bin/gdb ./epayworker
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2) 7.7.1
Copyright (C) 2014 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://ift.tt/KpOJT7;
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://ift.tt/xLrliR;.
Find the GDB manual and other documentation resources online at:
<http://ift.tt/1gENejF;.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./epayworker...
Program received signal SIGSEGV, Segmentation fault.
0x0000000000719da1 in cplus_demangle_print_callback ()
(gdb) bt -25
#0 0x0000000000719da1 in cplus_demangle_print_callback ()
#1 0x0000000000719fb4 in ?? ()
#2 0x000000000071a0c7 in ?? ()
#3 0x000000000071a26e in cplus_demangle_v3 ()
#4 0x000000000070c3c6 in cplus_demangle ()
#5 0x000000000068fdbb in bfd_demangle ()
#6 0x000000000055f269 in symbol_set_names ()
#7 0x00000000005cb985 in prim_record_minimal_symbol_full ()
#8 0x00000000004f82ba in ?? ()
#9 0x00000000004f8b95 in ?? ()
#10 0x000000000056a8d9 in ?? ()
#11 0x000000000056a459 in ?? ()
#12 0x000000000056a9b4 in symbol_file_add ()
#13 0x000000000056aa15 in ?? ()
#14 0x00000000005921be in catch_command_errors_const ()
#15 0x0000000000594da5 in ?? ()
#16 0x000000000059205a in catch_errors ()
#17 0x0000000000595244 in gdb_main ()
#18 0x000000000045391e in main ()
(gdb)


I'm not really excited about changing compiler for the core of our production servers at this stage. And bugs creating limitations to architecture is also not the best thing.


So my questions are: am I missing some type of flag to overcome some internal limitation in gdb? or this is just a bug in gdb? or maybe I should not be afraid and migrate for newer compiler version?


Thanks, for any help with my confusion.


nesting enum classes for a console menu

I'd like to implement a console menu like this:



1) Add character
1.1) Create manually
1.2) Create randomly
2) See character
2.1) List of characters
2.2) Go back
3) Edit character
...
...
4) Exit


To not extend it to long, the idea is to create a main menu with different sub menus with different options. My idea is to use enum classes to manage them. Looking for information I have read that nesting several enum classes is not feasible. I would like to know any suggestion for this.


Semaphore not working C++

I am new to semaphore and trying to write a very basic example to get to learn it better. My code has three arrays:



b1[5]={1;2;3;4;5}
b2[5]={6;7;8;9;10}
x[10]


I have a function that takes b1 or b2 and update x to have it as follow:



x={0;1;2;3;4;5;6;7;8;9}


My code is the following:



#include <sys/types.h> /* Primitive System Data Types */
#include <errno.h> /* Errors */
#include <stdio.h> /* Input/Output */
#include <stdlib.h> /* General Utilities */
#include <thread> /* C++11 Threads */
#include <string.h> /* String handling */
#include <semaphore.h> /* Semaphore */
#include <Windows.h> /* windows */
using namespace std;

/* prototype for thread routine */
void handler(int x[], int b[], int start, int id);

/* global vars */
sem_t mutex;
vector<std::thread> threadList;

int main()
{
int i[2];
int x[10];
int b1[5];
int b2[5];
sem_init(&mutex, 0, 1); /* initialize mutex to 1 - binary semaphore */
/* second param = 0 - semaphore is local */
i[0] = 0;
i[1] = 1;

// Update the matrix
for (int j = 0; j < 5; j++)
{
b1[j] = j;
b2[j] = j+5;
}



threadList.push_back(std::thread(handler, x, b1, 0, 0));
threadList.push_back(std::thread(handler, x, b2, 5, 1));

// wait for all threads to finish
for (auto& threadID : threadList){
threadID.join();
}

sem_destroy(&mutex); /* destroy semaphore */

/* exit */
return 0;
} /* main() */

void handler(int x[], int b[], int start, int id)
{

for (int j = start; j < 5; j++)
{
x[j] = b[j];
}
printf("Thread %d: Waiting to print results...\n", id);
sem_wait(&mutex); /* down semaphore */
/* START CRITICAL REGION */
for (int j = start; j < 5; j++)
{
printf("x[%d] = %d\n", j , x[j]);
}
/* END CRITICAL REGION */
sem_post(&mutex); /* up semaphore */
}


The output of the code is the following:



Thread 0: Waiting to print results...
x[0] = 0
x[1] = 1
x[2] = 2
x[3] = 3
x[4] = 4
Thread 1: Waiting to print results...


However, I was expecting something as following



Thread 0: Waiting to print results...
x[0] = 0
x[1] = 1
x[2] = 2
x[3] = 3
x[4] = 4
Thread 1: Waiting to print results...
x[5] = 5
x[6] = 6
x[7] = 7
x[8] = 8
x[9] = 9


Any idea why the second thread does not enter the printing section of the code ?


Is it safe to use negative integers with size_t?

I just saw some C++ code like this. It was using a condition to decide whether to walk forward or backward through a std::vector. The compiler doesn't complain, but I thought size_t was unsigned. Is this dangerous?



vector<int> v { 1,2,3,4,5 };
bool rev = true;

size_t start, end, di;
if (rev) {
start = v.size()-1;
end = -1;
di = -1;
}
else {
start = 0;
end = v.size();
di = 1;
}

for (auto i=start; i!=end; i+=di) {
cout << v[i] << endl;
}

Removing the first specified type found from a nested pack

For example,



using NestedPack = Pack<long, char, double, Pack<long, int, short, int>, char, int>;


Then



RemoveFirstFoundFromNestedPack<int, NestedPack>::type


is supposed to give



Pack<long, char, double, Pack<long, short, int>, char, int>


First, I took care of the case of a non-nested pack:



template <typename T> struct Identity { using type = T; };

template <typename, typename, typename...> struct RemoveFirstFoundFromPackHelper;

template <typename RemoveMe, template<typename...> class P, typename... Types>
struct RemoveFirstFoundFromPackHelper<RemoveMe, P<>, Types...> {
using type = P<Types...>;
};

template <typename RemoveMe, template<typename...> class P, typename First, typename... Rest, typename... Types>
struct RemoveFirstFoundFromPackHelper<RemoveMe, P<First, Rest...>, Types...> : std::conditional<std::is_same<RemoveMe, First>::value,
Identity <P<Types..., Rest...>>,
RemoveFirstFoundFromPackHelper<RemoveMe, P<Rest...>, Types..., First>
>::type {};

template <typename, typename> struct RemoveFirstFoundFromPack;

template <typename RemoveMe, template<typename...> class P, typename... Types>
struct RemoveFirstFoundFromPack<RemoveMe, P<Types...>> : RemoveFirstFoundFromPackHelper<RemoveMe, P<Types...>> {};


This was tested to work correctly (using std::is_same). But I'm stuck with the nested case. This was my latest attempt, which gives incorrect results (though I couldn't trace why):



template <typename>
struct IsPack : std::false_type {};

template <template<typename...> class P, typename... Types>
struct IsPack<P<Types...>> : std::true_type {};

template <typename, typename, typename...> struct RemoveFirstFoundFromNestedPackHelper;

template <typename RemoveMe, template<typename...> class P, typename... Types>
struct RemoveFirstFoundFromNestedPackHelper<RemoveMe, P<>, Types...> {
using type = P<Types...>;
};

template <typename RemoveMe, template<typename...> class P, typename First, typename... Rest, typename... Types>
struct RemoveFirstFoundFromNestedPackHelper<RemoveMe, P<First, Rest...>, Types...> : std::conditional<std::is_same<RemoveMe, First>::value,
Identity <P<Types..., Rest...>>,
typename std::conditional<IsPack<First>::value,
RemoveFirstFoundFromNestedPackHelper<RemoveMe, P<Rest...>, Types..., RemoveFirstFoundFromNestedPackHelper<RemoveMe, First>>,
RemoveFirstFoundFromNestedPackHelper<RemoveMe, P<Rest...>, Types..., First>
>::type
>::type {};


I know there must be a better way than this.


Of course, once this problem is solved, then removing all instances of the specified type found from the nested pack should be easy (I've already done that for the non-nested case).


Is this recursive reference with tuples safe?

I'm experimenting and wrote this monster:



class my_tuple : public std::tuple < std::vector<my_tuple> > {};


And it compiles and actually works, it seems. And I find it dodgy because the following doesn't compile:



using my_other_tuple = std::tuple < std::vector<my_other_tuple> > ;


Ultimately, I'm trying to wrap my head around why my_tuple works and if there's any potential terrible consequences. I'm trying to learn what tuples are all about and what I can/am supposed to do with them. So if anyone would care to comment on that, give some nifty insights, I would appreciate it.


Windows 7 and VS 2013.


std::queue::size() can return a huge number after pop() of size() == 0

I have the link here where I push(x) 10 ints, then pop() 11 and the size is not 0, or an exception, but a tremedous number (probably == std::numeric_limit<size_type>::max()). I assume this is the consequence of the internal representation simply doing a size-- and not checking for an already empty() case. This seems like a bug in the stdc++ library.


http://ift.tt/1yVzVEz


Moving a smart pointer from one unordered_set from another


template<class T>
Class Node
{
//irrelavant functs
};
class A
{
unordered_set<unique_ptr<Node<T>>, myHash<Node<T>>, myEqual<Node<T>>> nodes
shared_ptr<A> child;

void moveToChild()
{
for(auto it = nodes.begin(); it < nodes.end(); ++it) {
if (some_cond) {
child->nodes.emplace(std::move(*it));
}
}
}
};


I have a class that holds bunch of nodes in unordered_set, and has a pointer to itself called child. When some arbitrary conditions satisfied, this class should move some (or all) of its pointers to Node objects to child's nodes container. But I'm not sure if it's possible since keys in unordered_sets are const.


I don't mind constructing a new smart pointer, but I can't afford to construct a new node every time I move it around or remove it from unordered_set. If what I'm trying to do is not possible with unique_ptrs, I was wondering if it's possible with shared_ptrs?


I have never implemented my own allocators for STL containers so not sure if I'm on the right track but I was thinking of writing a custom allocator for unordered_set that takes a bool, if it's true, it deletes the objet if it's false it doesn’t free the pointer but removes it from the container (again, not sure if I can make such a dramatic change to container's behavior)


So, is it possible to somehow move a smart pointer from one unordered_set to another without freeing it?


Note: Please don't pay attention to typos and syntax errors, it's a grossly simplified version of my code.


Pass generic template class as functor parameter

I want to improve the following code snippet:



THNNetIPInfoIter last = std::unique(fist, end, HNInfoIPComparator());


where currently HNInfoIPComparator() is implemented as following:



// equal comparator
class HNInfoIPComparator
{
public:
bool operator()(const THNNetIPInfo &a, const THNNetIPInfo &b);
bool operator()(const SDK::TIPAddressDescription &a, const SDK::TIPAddressDescription &b);
bool operator()(const THNNetIPInfo &a, const SDK::TIPAddressDescription &b);
bool operator()(const SDK::TIPAddressDescription &a, const THNNetIPInfo &b);
};


The reason for this comparator definition is that it might be used with another STL algorithms, like std::set_difference and should handle case when ranges has different types.


The problem is that I have to write huge amount of very similar comparators and it is easy to be entangled with which comparator to use.


I want to write the following snippet:



template<typename SDKClass, typename IDLClass>
class equal {
public:
bool operator()(const IDLClass &a, const IDLClass &b) {
if (strcmp(a.ipaddr.in(), b.ipaddr.in())) {
return false;
}
return true;
}

bool operator()(const SDKClass &a, const SDKClass &b) {
if (strcmp(a.ip_address().c_str(), b.ip_address().c_str())) {
return false;
}
return true;
}

bool operator()(const IDLClass &a, const SDKClass &b) {
if (strcmp(a.ipaddr.in(), b.ip_address().c_str())) {
return false;
}
return true;
}

bool operator()(const SDKClass &a, const IDLClass &b) {
if (strcmp(a.ip_address().c_str(), b.ipaddr.in())) {
return false;
}
return true;
}
};


So HNInfoIPComparator() would be generated depending on types passed as its arguments inside std::unique function.


Therefore I want to pass to std::unique templated functor (class). Is it possible to do that and how?


Also I want to handle case when functor contains some internal data, which are used for comparisons


Most important code samples:



// Automatically generated structure from IDL specification
// Basically simple structure
struct THNNetIPInfo
{
typedef THNNetIPInfo_var _var_type;
typedef THNNetIPInfo_out _out_type;

static void _tao_any_destructor (void *);
::TAO::String_Manager ipaddr;
::TAO::String_Manager netmask;
};

// THNNetIPInfoIter - class external iterator
// which was written manually
typedef Util::CorbaSeqIter<THNNetIPInfoList, THNNetIPInfo> THNNetIPInfoIter;

// THNNetIPInfoList - also automatically generated class
// from IDL specification, list of THNNetIPInfo elements
THNNetIPInfoList list(...);
THNNetIPInfoIter first(&list, 0);
THNNetIPInfoIter end(&list, list.length());

Thread is not a member of std

Hello I am trying to compile my native c++ code, but I get this error.


I have configured the android.mk like this :



LOCAL_CFLAGS += -std=c++11 -pthread


What else should I do ?


Viewing a raw pointer as a range in range-based for-loop

How can I make a raw pointer behave like a range, for a for-range loop syntax.



double five = 5;
double* dptr = &five;
for(int& d : dptr) std::cout << d << std::endl;// will not execute if the pointer is null


Motivation:


It is now vox populi that an boost::optional (future std::optional) value can be viewed as a range and therefore used in a for range loop http://ift.tt/1HswM4U.


When I rewrote my own simplified version of it:



namespace boost {
template <class Optional>
decltype(auto) begin(Optional& opt) noexcept{
return opt?&*opt:nullptr;
}

template <class Optional>
decltype(auto) end(Optional& opt) noexcept{
return opt?std::next(&*opt):nullptr;
}
}


Used as



boost::optional<int> opt = 3;
for (int& x : opt) std::cout << x << std::endl;


While looking that code I imagined that it could be generalized to raw (nullable) pointers as well.



double five = 5;
double* dptr = &five;
for(int& d : dptr) std::cout << d << std::endl;


instead of the usual if(dptr) std::cout << *dptr << std::endl;. Which is fine but I wanted to achieve the other syntax above.


Attempts


First I tried to make the above Optional version of begin and end work for pointers but I couldn't. So I decided to be explicit in the types and remove all templates:



namespace std{ // excuse me, this for experimenting only
double* begin(double* opt){
return opt?&*opt:nullptr;
}
double* end(double* opt){
return opt?std::next(&*opt):nullptr;
}
}


Almost there, it works for



for(double* ptr = std::begin(dptr); ptr != std::end(dptr); ++ptr)
std::cout << *ptr << std::endl;


But it doesn't work for the supposedly equivalent for-range loop:



for(double& d : dptr) std::cout << d << std::endl;


Two compilers tell me: error: invalid range expression of type 'double *'; no viable 'begin' function available


What is going on? Is there a compiler magic that forbids the ranged-loop to to work for pointers. Am I making a wrong assumption about the ranged-loop syntax?


Ironically, in the standard there is an overload for std::begin(T(&arr)[N]) and this is very close to it.


Microsoft Visual Studio std::tuple Bug?

The code at the following location behaves as expected.


http://ift.tt/1Lrk7yE



auto x = parse<int, int, float>(buf);


The line above expects the buffer to be in the same order of evaluation. However, on Microsoft Visual Studio 2013 : Update 4 (Latest Production Version) this results in inverse evaluation of the tuple and gives out garbage.


Is this a MSVC bug or have I misunderstood.


Compact and Simple std::tuple inversion

I am new to meta programming. I have looked at other questions that are similar but none of them do what I really want.


Here is my attempt at inversing a std::tuple. The main issue i have is inverting the data in the input tuple.


The logic to inverse the indices is not palatable and I could not proceed from this stage.


The code so far:



//===========================================================!
// type inversion of a tuple

template < typename Tuple, typename T >
struct tuple_push;

template < typename T, typename ... Args >
struct tuple_push<std::tuple<Args...>, T>
{
typedef std::tuple<Args..., T> type;
};

template < typename Tuple >
struct tuple_reverse;

template < typename T, typename ... Args >
struct tuple_reverse<std::tuple<T, Args...>>
{
typedef typename tuple_push<typename tuple_reverse<std::tuple<Args...>>::type, T>::type type;
};

template < >
struct tuple_reverse<std::tuple<>>
{
typedef std::tuple<> type;
};
//===========================================================!


template <typename First, typename ...Tails>
auto inverse(std::tuple<First, Tails...> & data)
-> decltype(tuple_reverse<std::tuple<First,Tails...>>::type)
{
using reverse_tup = tuple_reverse<std::tuple<First, Tails...>>::type;
static_assert(false, "Confused!")
return reverse_tup();
}


Looking forward to a compact and simple solution.


Does C++11, 14 or 17 provide a way to get just the arguments out of a decltype()?

This question is very similar to: "Extract just the argument type list from decltype(someFunction)". I'm not sure the answers there work for what I'm intending though. I'd like to be able to create a template function that deduces the type of its runtime arguments based on the type of a function pointer template argument (whistles).


For an example use case, let's say I want to instrument straight C POSIX file I/O using a shim library loaded with LD_PRELOAD. I could write separate wrappers for fopen, fread, fwrite, fclose... If all of those wrappers do similar stuff though, wouldn't it be nice if I could define a template that captures the common behavior?


Partial example NOT using templates that demonstrates how much boilerplate is involved:



extern "C" {

FILE *(*real_fopen)(const char *, const char *) = NULL;
FILE *fopen(const char *path, const char *mode)
{
FILE *returned_file;

if (real_fopen == NULL) {
real_fopen = ((FILE *)(const char *, const char *))dlsym("fopen", RTLD_NEXT);
}

... do pre-call instrumentation ...
returned_file = real_fopen(path, mode);
... do post-call instrumentation ...

return returned_file;
}

int *(*real_fclose)(FILE *) = NULL;
int *fopen(const char *path, const char *mode)
{
int retval;

if (real_fclose == NULL) {
real_fclose = ((int)(FILE *))dlsym("fclose", RTLD_NEXT);
}

... do pre-call instrumentation ...
retval = real_fclose(path, mode);
... do post-call instrumentation ...

return retval;
}

... additional definitions following the same general idea ...

}


We can save some code using a variadic template function:



template <typename func_ptr_type, func_ptr_type real_func_ptr,
const char *dl_name, typename... Args>
std::result_of<func_type> wrap_func(Args... args)
{
std::result_of<func_type> retval;
if (real_func_ptr == NULL) {
real_func_ptr = (func_ptr_type)dlsym(dl_name, RTLD_NEXT);
}

... do pre-call instrumentation ...
retval = real_func_ptr(args...);
... do post-call instrumentation ...

return retval;
}

FILE *(*real_fopen)(const char *, const char *) = NULL;
FILE *fopen(const char *path, const char *mode)
{
return wrap_func<decltype(real_fopen), real_fopen, "fopen", const char *, const char *>(path, mode);
}

int (*real_fclose)(FILE *) = NULL;
int fclose(FILE *fp)
{
return wrap_func<decltype(real_fclose), real_fclose, "fclose", FILE *>(fp);
}


There's gotta be some way we can avoid passing all of those redundant types in the list of template parameters though. What I would like to do that I haven't found valid syntax for yet (presumes the existence of something I'll call std::arguments_of that's sort of like the opposite of std::result_of):



template <typename func_ptr_type, func_ptr_type real_func_ptr,
const char *dl_name, std::arguments_of(func_ptr_type)>
std::result_of<func_type> wrap_func(std::arguments_of(func_ptr_type)... args)
{
std::result_of<func_type> retval;
if (real_func_ptr == NULL) {
real_func_ptr = (func_ptr_type)dlsym(dl_name, RTLD_NEXT);
}

... do pre-call instrumentation ...
retval = real_func_ptr(args...);
... do post-call instrumentation ...

return retval;
}

FILE *(*real_fopen)(const char *, const char *) = NULL;
FILE *fopen(const char *path, const char *mode)
{
return wrap_func<decltype(real_fopen), real_fopen, "fopen">(path, mode);
}

int (*real_fclose)(FILE *) = NULL;
int fclose(FILE *fp)
{
return wrap_func<decltype(real_fclose), real_fclose, "fclose">(fp);
}


Is there a valid way to do this in C++11, 14 or 17? How, or if not, why not?


Optimizing string creation

I have the following mock up code of a class which uses an attribute to set a filename:



#include <iostream>
#include <iomanip>
#include <sstream>

class Test {
public:
Test() { id_ = 1; }
/* Code which modifies ID */

void save() {
std::string filename ("file_");
filename += getID();
std::cout << "Saving into: " << filename <<'\n';
}

private:
const std::string getID() {
std::ostringstream oss;
oss << std::setw(4) << std::setfill('0') << id_;
return oss.str();
}

int id_;
};

int main () {
Test t;
t.save();
}


My concern is about the getID method. At first sight it seems pretty inefficient since I am creating the ostringstream and its corresponding string to return. My questions:


1) Since it returns const std::string is the compiler (GCC in my case) able to optimize it?


2) Is there any way to improve the performance of the code? Maybe move semantics or something like that?


Thank you!


Is it a bad idea to replace C-style array with std::valarray?

I'm working with a code base that is poorly written and has a lot of memory leaks.


It uses a lot of structs that contains raw pointers, which are mostly used as dynamic arrays.


Although the structs are often passed between functions, the allocation and deallocation of those pointers are placed at random places and cannot be easily tracked/reasoned/understood.


I changed some of them to classes and those pointers to be RAIIed by the classes themselves. They works well and don't look very ugly except that I banned copy-construct and copy-assignment of those classes simply because I don't want to spend time implementing them.


Now I'm thinking, am I re-inventing the wheel? Why don't I replace C-style array with std:array or std::valarray?


I would prefer std::valarray because it uses heap memory and RAIIed. And std::array is not (yet) available in my development environment.


Is there anything that I need to be aware of before I start?


One I can think of is that there might not be an easy way to convert std::valarray or std::array back to C-style arrays, and part of our code does uses pointer arithmetic and need data to be presented as plain C-style arrays.


Anything else?


Modifying a function to use SSE intrinsics

I am trying to calculate the approximate value of the radical: sqrt(i + sqrt(i + sqrt(i + ...))) using SSE in order to get a speedup from vectorization (I also read that the SIMD square-root function runs approximately 4.7x faster than the innate FPU square-root function). However, I am having problems getting the same functionality in the vectorized version; I am getting the incorrect value and I'm not sure


My original function is this:



template <typename T>
T CalculateRadical( T tValue, T tEps = std::numeric_limits<T>::epsilon() )
{
static std::unordered_map<T,T> setResults;

auto it = setResults.find( tValue );
if( it != setResults.end() )
{
return it->second;
}

T tPrev = std::sqrt(tValue + std::sqrt(tValue)), tCurr = std::sqrt(tValue + tPrev);

// Keep iterating until we get convergence:
while( std::abs( tPrev - tCurr ) > tEps )
{
tPrev = tCurr;
tCurr = std::sqrt(tValue + tPrev);
}

setResults.insert( std::make_pair( tValue, tCurr ) );
return tCurr;
}


And the SIMD equivalent (when this template function is instantiated with T = float and given tEps = 0.0005f) I have written is:



// SSE intrinsics hard-coded function:
__m128 CalculateRadicals( __m128 values )
{
static std::unordered_map<float, __m128> setResults;

// Store our epsilon as a vector for quick comparison:
__declspec(align(16)) float flEps[4] = { 0.0005f, 0.0005f, 0.0005f, 0.0005f };
__m128 eps = _mm_load_ps( flEps );

union U {
__m128 vec;
float flArray[4];
};

U u;
u.vec = values;

float flFirstVal = u.flArray[0];
auto it = setResults.find( flFirstVal );
if( it != setResults.end( ) )
{
return it->second;
}

__m128 prev = _mm_sqrt_ps( _mm_add_ps( values, _mm_sqrt_ps( values ) ) );
__m128 curr = _mm_sqrt_ps( _mm_add_ps( values, prev ) );

while( _mm_movemask_ps( _mm_cmplt_ps( _mm_sub_ps( curr, prev ), eps ) ) != 0xF )
{
prev = curr;
curr = _mm_sqrt_ps( _mm_add_ps( values, prev ) );
}

setResults.insert( std::make_pair( flFirstVal, curr ) );
return curr;
}


I am calling the function in a loop using the following code:



long long N;
std::cin >> N;

float flExpectation = 0.0f;
long long iMultipleOf4 = (N / 4LL) * 4LL;
for( long long i = iMultipleOf4; i > 0LL; i -= 4LL )
{
__declspec(align(16)) float flArray[4] = { static_cast<float>(i - 3), static_cast<float>(i - 2), static_cast<float>(i - 1), static_cast<float>(i) };
__m128 arg = _mm_load_ps( flArray );
__m128 vec = CalculateRadicals( arg );

float flSum = Sum( vec );
flExpectation += flSum;
}

for( long long i = iMultipleOf4; i < N; ++i )
{
flExpectation += CalculateRadical( static_cast<float>(i), 0.0005f );
}

flExpectation /= N;


I get the following outputs for input 5:



With SSE version: 2.20873
With FPU verison: 1.69647


Where does the discrepancy come from, what am I doing wrong in the SIMD equivalent?


Overload function for rvalues and lvalues

I am writing a library that uses shared pointers to build a complex structure of nodes. Since there can be cycles in the structure, and to avoid memory leakes, I decided to adopt the following strategy when building the structure: whenever I am passed a temporary object, I use a shared_ptr (to get the ownership); whenever I am passed a lvalue, I use a weak_ptr. According to my analysis and the way the library interface is designed, this should avoid cycles altogether.


However, I am having problems in using function overloading to understand when the parameter is a rvalue or a lvalue. Here is a very simplified example of the error I get:



#include <iostream>
#include <memory>

using namespace std;

class MyClass {
public:
int a;
// this class contains some pointers to the node structure
};

MyClass fun(MyClass &&x, MyClass &&y)
{
// should produce an object that has ownership of the two others
}

MyClass fun(MyClass x, MyClass y)
{
// should not take ownership, but just copy the pointer
}

int main()
{
MyClass x, y;

fun(x, y);
fun(MyClass(), MyClass());
}


When compiling with g++ 4.8.2 I get the following error:



example.cpp: In function ‘int main()’:
example.cpp:29:29: error: call of overloaded ‘fun(MyClass, MyClass)’ is ambiguous
fun(MyClass(), MyClass());
^
example.cpp:29:29: note: candidates are:
example.cpp:12:9: note: MyClass fun(MyClass&&, MyClass&&)
MyClass fun(MyClass &&x, MyClass &&y)
^
example.cpp:18:9: note: MyClass fun(MyClass, MyClass)
MyClass fun(MyClass x, MyClass y)
^


So, apparently the compiler cannot distinguish between the two calls. I thought the rvalue function has precedence over the pass-by-value function, but evidently I was wrong.


Also: I cannot declare the function to take const references, because I want just to take ownership and then later modify the object at will, so the reference should not be constant.


Any ideas on how I may solve this problem?


Extract range of elements from char array into string

I want to extract a range of elements from the beginning of a char array and put them into a string. The range may be less than or equal to the number of elements.


This is what I have come up with.



// buffer is a std::array<char, 128>

std::string message;

for (int i = 0; i < numberToExtract; ++i)
{
message += buffer.at(i);
}


Is there a better way to do this?


I've been looking at something like std::string's iterator constructor. E.g. std::string(buffer.begin(), buffer.end()) but I don't want all the elements.


Thanks.


How to store an argument to std::function , so that it can be used when called

I have been reading up on, how to perform a std::bind on a regular function. And store the free function or member function into a std::function. However, if I try to use a placeholder for one argument and an actual value for the other argument; I am not able to make a call(causes compilation error) to the std::function


So I tried the following code:



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

int g(int n1, int n2)
{
return n1+n2;
}


int main()
{
using namespace std::placeholders; // for _1, _2, _3...

std::function<int(int,int)> f3 = std::bind(&g, std::placeholders::_1, 4);
std::cout << f3(1) << '\n';

//this works just fine
auto f4 = std::bind(&g, std::placeholders::_1, 4);
std::cout << f4(1) << '\n';
}


I get the following error g++ 4.7



prog.cpp: In function 'int main()':
prog.cpp:17:22: error: no match for call to '(std::function<int(int, int)>) (int)'
std::cout << f3(1) << '\n';
^
In file included from /usr/include/c++/4.9/memory:79:0,
from prog.cpp:3:
/usr/include/c++/4.9/functional:2142:11: note: candidate is:
class function<_Res(_ArgTypes...)>
^
/usr/include/c++/4.9/functional:2434:5: note: _Res std::function<_Res(_ArgTypes ...)>::operator()(_ArgTypes ...) const [with _Res = int; _ArgTypes = {int, int}]
function<_Res(_ArgTypes...)>::
^
/usr/include/c++/4.9/functional:2434:5: note: candidate expects 2 arguments, 1 provided

Rational comparison of bits

I have a number of type int. It lies within [0,255]. That is, includes 8 bits. I need to check often say:


2(int) = 00000010(Binary)




1. The bit 6 and bit 7 must be equal to 0 and 1 respectively.
And I check it like this:



if ((!(informationOctet_ & (1 << 6))) && (informationOctet_ & (1 << 7)))
{
...
}


But it is not very readable, whether it is possible - to do something "beautiful"? I can not use the std::bitset, my head says it's a waste of resources and you can not do without it.


jeudi 29 janvier 2015

Do vector.emplace_back() and vector.push_back() do the same thing?

So I was trying to add integers onto the back of my vector and mistakenly thought push_back() added the new data onto the front of the vector (aka vector[0]). I did a test in Xcode and tested push_back() against emplace_back() and got the same results. I thought they were different, but this makes me think that maybe they do the same thing. If this is so, why does vector have the different methods?


Here's my code in case I was doing:



#include <vector>
#include <iostream>

using namespace std ;

int main(int argc, const char * argv[])
{
// for push_back
vector<int> push;
push.push_back(1);
push.push_back(2);
push.push_back(3);
push.push_back(4);
push.push_back(5);
push.push_back(6);
//display push_back
for (int i = 0; i < push.size(); i++) {
cout << "push[" << i << "]: " << push[i] << endl;
}
// distance between the two funcitons
cout << endl << endl;

vector<int> emplace;
emplace.emplace_back(1);
emplace.emplace_back(2);
emplace.emplace_back(3);
emplace.emplace_back(4);
emplace.emplace_back(5);
emplace.emplace_back(6);

//display emplace_back
for (int i = 0; i < emplace.size(); i++) {
cout << "emplace[" << i << "]: " << emplace[i] << endl;
}
return 0;
}


The return was:



push[0]: 1
push[1]: 2
push[2]: 3
push[3]: 4
push[4]: 5
push[5]: 6


emplace[0]: 1
emplace[1]: 2
emplace[2]: 3
emplace[3]: 4
emplace[4]: 5
emplace[5]: 6


I know this is a super easy question, but I just want to make sure I am not doing something stupidly wrong and misunderstanding the abilities of the vector class.


What does "except that a default constructed array is not empty" mean?

In N3337, I'm reading §23.3.2.1/3 it states:



An array satisfies all of the requirements of a container and of a reversible container (23.2), except that a default constructed array object is not empty and that swap does not have constant complexity.



In §23.2.1, Table 96 Container Requirements, it shows a default constructed object X u; where the post condition is u.empty(). Presumably then, the following:



std::array<int, 0> a;


should result with a.empty() outputting 1, which it does. So what does "empty" mean here?


c++ program crashing because of if statment

My c++ program is crashing i think because of an if statement. I am using MinGW compiler and am given no errors. I have no idea as to why i am getting the error. The if statement in my generate function looks fine to me. Im comparing a string with an instance of a vector string.


here is the cpp code:



#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstdlib>
#include <ctime>
#include "Insultgenerator_0hl14.h"

using namespace std;


FileException::FileException(const string& m) : message(m){}

string& FileException::what(){ return message;}

NumInsultsOutOfBounds::NumInsultsOutOfBounds(const string& m) : message(m){}

string& NumInsultsOutOfBounds::what(){ return message;}

InsultGenerator::InsultGenerator(const InsultGenerator& ) {};
InsultGenerator::InsultGenerator(){};

void InsultGenerator::initialize() {
int cols(0);

srand ( time(NULL));
string words ;

string filename("InsultsSource.txt");
ifstream filetoread(filename.c_str());

if(filetoread.fail()){
throw FileException("File not read.");
}
while(filetoread >> words){

if(cols==0){
colA.push_back(words);
cols++;
} else if(cols==1){
colB.push_back(words);
cols++;
}else{
colC.push_back(words);
cols= cols -2;
}


}


//for (int i=0;i<50;i++){
// cout << " "<< colA[i];
//}
}






string InsultGenerator::talkToMe() const{
string Thou = "Thou";

string a= Thou + " " + colA[(rand()%50)] + " " + colB[rand()%50] + " " + colC[rand()%50] +"!" ;

//cout << a << endl;

return a;
};//end talkToMe

vector<string> InsultGenerator::generate(const int num){

if (num<0){
throw NumInsultsOutOfBounds("You must be insulted at least once");
} else if (num >10000 ){
throw NumInsultsOutOfBounds("You are being insulted too many times!");
}

vector<string> insultList;
string list;

for(int i=0; i<num;i++ ){
list = talkToMe();

if(list != insultList[i]){
//insultList.push_back(list);
//cout << insultList[i]<< endl;
}
}



return insultList;
};//end generate

//int InsultGenerator::generateAndSave(const string filename, const int n) const{

//};//end generateAndSave

int main(){
InsultGenerator ig;
ig.initialize();
ig.talkToMe();
ig.generate(10);


}


Here is the header file :



#ifndef INSULTGENERATOR_0HL14_H_
#define INSULTGENERATOR_0HL14_H_

#include <string>
#include <vector>

using namespace std;

class InsultGenerator{
public:
InsultGenerator();
InsultGenerator(const InsultGenerator&);
void initialize() ;
string talkToMe() const;
vector<string> generate(const int) ;
int generateAndSave (const string, const int) const;

private:
vector<string> colA;
vector<string> colB;
vector<string> colC;
};

class FileException{
public:
FileException(const string&);
string& what();
private:
string message;
};

class NumInsultsOutOfBounds{
public:
NumInsultsOutOfBounds(const string &);
string& what();
private:
string message;
};

#endif

Why is this move allowed?

A vector when it does a resize will attempt to use move semantics to move the objects from the old array to the new one. But if the templated object in the vector does not support a no throw noexcept move constructor then it will revert to using copy construction so that the strong exception guarantee is preserved.


But when I try this:



#include <vector>

class X
{
public:
// Needs default constructor
X() {}

// Copy operations disabled.
X(X const&) = delete;
X& operator=(X const&) = delete;

X(X&&) // throwable move constructor
{}
X& operator=(X&&) // throwable move assignment.
{return *this;}
};

int main()
{
// Vector of Size zero
std::vector<X> data;

// Vector of Size ten.
// Since the move constructor can potentially throw
// We have to copy elements when we do a resize
//
// But X has a disabled copy semantics
// Thus I would expect a compile time error here.
data.resize(10);
}


This compiles without error or warning:



> g++ --version
Configured with: --prefix=/Applications/http://ift.tt/1d5DwEL --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 6.0 (clang-600.0.56) (based on LLVM 3.5svn)
Target: x86_64-apple-darwin14.0.0
Thread model: posix
> g++ -std=c++11 test.cpp
>

constexpr static member vs variable

I stumbled upon some C++11 code that looks like this:



// some_file.h
namespace blah {
class X {
public:
constexpr const static std::initializer_list<uint64> SOME_LIST =
{1,2,3};
};
}

// some_file.cpp
#include "some_file.h"
namespace blah {
constexpr const X::SOME_LIST;
}


Which compiles fine. I assume the definition in the cpp file is used to avoid symbol duplication in each file that includes the header (please correct me if I'm wrong).


I then tried the following:



// my_file.h
namespace bleh {
constexpr const static char SOME_CONSTANT[] = "yay";
}

// my_file.cpp
#include "my_file.h"
namespace bleh {
// if I add this or any other variation, compilation breaks!
//constexpr const static char SOME_CONSTANT[];
}


The code above does not work if I add an explicit definition in the .cpp file. So I am wondering: is there symbol duplication in the second case? If so, is there a way to define the variable without an enclosing class?


Is there a way to simulate upcasting by reference

So, I have something along the lines of these structs:



struct Generic {}
struct Specific : Generic {}


At some point I have the the need to downcast, ie:



Specific s = (Specific) GetGenericData();


This is a problem because I get error messages stating that no user-defined cast was available.


I can change the code to be:



Specific s = (*(Specific *)&GetGenericData())


or using reinterpret_cast, it would be:



Specific s = *reinterpret_cast<Specific *>(&GetGenericData());


But, is there a way to make this cleaner? Perhaps using a macro or template?


I looked at this post C++ covariant templates, and I think it has some similarities, but not sure how to rewrite it for my case. I really don't want to define things as SmartPtr. I would rather keep things as the objects they are.


Access violation using a C++ function from a DLL

I have a game engine written in C++ which I'm porting to Windows (from Mac). It uses C++11 and OpenGL, and for all intents and purposes, it runs!


I'm using a DLL for my game engine which is linked implicitly to the game .exe at runtime. The problem is, when I try to use a utility class from the DLL, FileSystem, to find a resource file (a texture, but I don't think it's important), I get this error:


First-chance exception at 0x00007FF9CF988830 (PocoFoundation64.dll) in TestEquinox.exe: 0xC0000005: Access violation reading location 0x000000136A4FF000.


The problem comes when I call this method of my FileSystem class from the DLL (it's designed to take a filename/partial path and it looks in various places to find the full path):



Poco::Path FileSystem::Get(const std::string &filename) {
std::vector<Poco::Path> paths = {
filename,
ResourceFolder() / filename //<<<<< ERROR HERE
};

for (const Poco::Path &path : paths) {
try {
if (Poco::File(path).exists()) {
return path;
}
} catch (...) { }
}

Logger("FileSystem", std::cerr) << "Could not find file '" << filename << "'!";
return {};
}


Visual Studio shows the error as being at the call of ResourceFolder(), another method from the same class, also in the DLL. This appears so:



Poco::Path FileSystem::ResourceFolder() {
Poco::Path userData;

//--SNIP-- (other OS's #ifdef'd here)
// GAME->StartupPath is a std::string containing the exe's parent folder
userData = (Poco::Path(GAME->StartupPath).parent() / "Resources").makeDirectory();
//--SNIP-- (and here)

try {
if (!Poco::File(userData).exists()) {
Poco::File(userData).createDirectories();
}
} catch (...) {}

return userData;
}


From the looks of it, it's to do with Poco's data types not being instantiated properly? I've built it from source with all the same compiler settings (64-bit, multi-byte character set, VS2013), so I don't see how it could be a name mangling/data layout issue.


One more thing to note - I copied the entire FileSystem class from the DLL to a class local to my game project, called FileSystem2. Calling FileSystem2::Get with the same parameters worked correctly and without crashing, despite being the same code.


Hoping someone can point me in the right direction?!


why didn't my g++ and gcc version get upgraded?

I am on a Mac. I updated my OSx to Yosemite. I updated my xcode to version 6. I downloaded the command line tools.


And still, whenever I type in g++ --version, I get:



# g++ --version
couldn't understand kern.osversion `14.1.0'
i686-apple-darwin11-llvm-g++-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)
Copyright (C) 2007 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.


meaning, I am still using the old version of g++ and gcc.


Why wasn't it upgraded? I am interested in using c++0x in Eclipse, and for that I need a newer g++/gcc compiler.


Object does not name a type?

I have a chunk of code that keeps failing on me no matter how much I thin it down. The code in question is:



#include <iostream>
class Tile;
class Tile{
public:
void PRINTME();
};

void Tile::PRINTME() { std::cout << "Blergh"; }

Tile Wall;
Wall.PRINTME();


It displays the following error message:



(...)\MapTiles.h|11|error: 'Wall' does not name a type|


I might be relatively new to C++ programming, but a couple of hours of digging around Stackexchange and tutorials on classes tells me that the above snippet should run.


Multiple other such problems here have been solved using forward declarations, but in this case it is trying to read the object "Wall" as a class. As the class was previously quite a bit larger, I trimmed it considerably yet it still fails to work decently. I based this example off the Tutorialspoint tutorial on C++ classes and member functions.


I'm using MinGw that comes with Code::Blocks 13.12, on a Windows 7 (64bit) machine with the compiler flag -std=c++11 ticked.


how does member declaration with assignment relate to ctors?

Sorry - I'm sure I'm just not finding any answers because I don't know the nomenclature!



class Foo
{
public:
Foo() { } // default ctor
explicit Foo(int a) _a(a) { } // semi-explicit - but what is _b's value??
protected:
int _a = 9; // HOW DOES THIS RELATE TO EACH OF THE CTORS?!
int _b = 3; // HOW DOES THIS RELATE TO EACH OF THE CTORS?!
};


By explicitly specifying a default ctor w/o specifying _a or _b, do the declared assignments happen (_a = 9, _b = 3) or do those only happen if I don't create a default ctor (or I declare as Foo() = default;)?


How to correctly serialise thread access to a flag controlling a loop

I have a function, f1, that contains a simple loop, which is controlled via a boolean flag. The flag is not written to inside f1.


I have another function that clears the flag.


The two functions are called on different threads.


If I lock the mutex before entering the loop in f1, then f2 will not be able to acquire it in order to clear the flag.


If I don't lock the mutex before entering the loop in f1, then the flag is unprotected. Does that matter, given that the function only reads it?


My question is do I need to protect the flag before entering the loop in f1, given that it is only read? If so, how?


Do I even need the mutex if the flag is only written to in one place?


Am I missing something fundamental?


TIA



class X
{
public:
X() :
m_thread(),
m_isDone(false),
m_mutex()
{
m_thread = std::unique_ptr<std::thread>(new std::thread( [=]{ run(); } ));
}

~X()
{
// tell the thread to exit
m_isDone = true;

// wait for the thread to terminate
m_thread->join();
}

void f1()
{
// locking the mutex will prevent f2 from clearing the flag
std::lock_guard<std::mutex> lock(m_mutex);

while (!m_isDone)
{
// do some stuff
}
}

void f2()
{
// lock the mutex
std::lock_guard<std::mutex> lock(m_mutex);
m_isDone = true;
}

private:
std::unique_ptr<std::thread> m_thread;
bool m_isDone;
mutable std::mutex m_mutex;
};

Destructor never call

I don't understand why the destructor of ListELement is never call.

I use the class Base as counter, ListELement derive from Base to use the counter.


The Program:



#include <iostream>
#include <random>
#include <functional>

using namespace std;

class Base{
protected:
static int count;
};


template <class T>
class ListElement: public Base{

public:
ListElement(const T& value): next(NULL), data(value) { count++;}
~ListElement() { cout<<"dead:"<<count<<endl;}

//Setter
void SetData(const T& value) { data=value; }
void SetNext(ListElement* elem) { next = elem; }
//Getter
const T& GetData() const { return data; }
ListElement* GetNext() const { return next; }

private:
T data;
ListElement* next;
};

int Base::count = 0;

int main(){
random_device rd;
default_random_engine generator(rd());
uniform_int_distribution<int> distribution(1,100);
auto dice = bind(distribution, generator);

int nListSize = 1;
ListElement<int>* nMyList = new ListElement<int>(999);

ListElement<int>* temp = nMyList;//nMyList is the first element
for(int i=0; i<10; ++i) {
ListElement<int>* k = new ListElement<int>(dice()); //New element
temp->SetNext(k);
temp = temp->GetNext();
nListSize++;
}

temp=nMyList;
for(int i=0; i<nListSize; ++i){
cout<<"Value["<<i<<"]: "<<temp->GetData()<<endl;
temp = temp->GetNext();
}

return 0;
}


This is my output:



Value[0]: 999
Value[1]: 61
Value[2]: 14
Value[3]: 96
Value[4]: 51
Value[5]: 15
Value[6]: 37
Value[7]: 83
Value[8]: 1
Value[9]: 42
Value[10]: 95


If I type echo &? the console return my 0 so everything should be fine.


notify_all_at_thread_exit doesn't exist in Cygwin GCC

When I try to build the following simple test program in 32-bit Cygwin with GCC version 4.9.2, I get an error saying:



error: ‘notify_all_at_thread_exit’ is not a member of ‘std’


This makes me think that this specific method hasn't been ported to Cygwin. Does anyone know if I am either doing something wrong or if I can determine that this indeed is missing from Cygwin?


Build line:



/usr/bin/c++.exe -std=gnu++11 -o NotifyAllAtThreadExitTest.cc.o -c NotifyAllAtThreadExitTest.cc


Code snippet:



#include <mutex>
#include <thread>
#include <condition_variable>

std::mutex m;
std::condition_variable cv;

bool ready = false;

void thread_func()
{
std::unique_lock<std::mutex> lk(m);
ready = true;
std::notify_all_at_thread_exit(cv, std::move(lk));
}

int test()
{
std::thread t(thread_func);
t.detach();

std::unique_lock<std::mutex> lk(m);
while(!ready) {
cv.wait(lk);
}
}

Copying addresses of objects containing an atomic member?

Lets say I have a struct AtomicElement:



struct AtomicElement{
std::atomic<int32_t> a;
};


and I have another class, Object, which contains a reference to one of the above AtomicElement objects:



struct Object{
AtomicElement& ae;
};


Now elsewhere I have a vector of these AtomicElement objects and I would like to update Object::ae to point to different vector elements:



std::vector<AtomicElement> aeVector(AtomicElement());
Object obj;
.
.
//Obtain the address to the new element
AtomicElement& raw_ae = aeVector[i];
.
.
//Change to point to the new element
obj.ae = raw_ae; //Cannot get this part to compile.


What am I doing wrong?


My AtomicElement is only 32 bits, should I just be using by value?


I want to do this in the most efficient way possible, with as little copying as possible.


How to copy a list of numbers from a string to a C++ vector

I have a string like:



string line="6,148,72,35,0,33.6,0.627,50,1";


and I would like to copy the numbers within it to the respective elements of a std::vector. I would like to use std::vector.assign() or std::copy().


So I wrote:



string line="6,148,72,35,0,33.6,0.627,50,1";
vector<double> row;
istringstream iss { line };
row.assign(istream_iterator<double>(iss), istream_iterator<double>());


but the result is that assign() only copies the first number from the string to the vector, i.e. I get



row={6}


while I would like to get



row={6,148,72,35,0,33.6,0.627,50,1}


Same thing if I use std::copy instead, like in:



string line="6,148,72,35,0,33.6,0.627,50,1";
vector<double> row;
istringstream iss { line };
copy(istream_iterator<double>(iss), istream_iterator<double>(), back_inserter(row));


It looks like copy from the string ends after reading the first number, and I don't know why. Any idea how to use assign() or copy() to copy every number from the string into the vector?


Where machine instructions of a program stored during runtime?

So far as I know, whenever we run any program, the machine instructions of the program is loaded in RAM. Again, there are two regions of memory: stack and heap.


My question is: Which region of memory the machine instruction stored in? stack or heap?


I learnt that the following program gives a runtime error though there is no variable declared inside the function. The reason behind this is the overflow of stack. Then should I assume that the machines instructions of the function is stored in stack?





int func()
{
return func();
}



threaded matrix multiplication

I'm working on a threaded implementation of matrix multiplication to work with my custom Matrix class, and I'm running into some issues with speedup.


Setting up and calling the operation looks like this:



Matrix<double> left(2,2);
left[0][0] = 1; left[0][1] = 2;
left[1][0] = 3; left[1][1] = 4;

Matrix<double> right(2,2);
right[0][0] = 1; right[0][1] = 0;
right[1][0] = 0; right[1][1] = 1;

Matrix<double> result = left * right;


And here's a simplified version of my class with the implementations necessary to see how the operation is working. I included constructors, copy constructor, assignment operator, and destructor for thoroughness, the last two functions are mainly what I'm focusing on. Also, I'm transposing the right multiplicand to utilize spatial locality, so each location in the output matrix is a dot product of a row of the left multiplicand and a row of the right multiplicand, as compared to a row of the left multiplicand and a column of the right multiplican. Here's the code:



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

template <class type>
class Matrix {

public:
// Default Constructor
Matrix() { this->create(); }
// Custom Constructor
Matrix(int r, int c) { this->create(r,c); }
// Copy Constructor
Matrix(const Matrix<type> &m) { this->copy(m); }
// Assignment Operator
Matrix<type> operator=(const Matrix<type> &m);
// Destructor
~Matrix() { this->destroy(); }

// Accessor Functions
int getRows() const { return rows; }
int getCols() const { return cols; }
type* operator[](int i) const { return contents[i]; }

// Matrix Operations
Matrix<type> transpose() const;

// Matrix Multiplication
friend Matrix<type> operator*(const Matrix<type> &m1, const Matrix<type> &m2)
{ Matrix<type> call; return call.multiply(m1,m2); }

private:
// Private Member Functions
void create();
void create(int r, int c);
void copy(const Matrix<type> &m);
void destroy();

// Operator Overloading Functions
Matrix<type> multiply(const Matrix<type> &m1, const Matrix<type> &m2);

// Private Member Variables
int rows;
int cols;
type** contents;

};


// Default Constructor
template <class type>
void Matrix<type>::create() {
rows = 0;
cols = 0;
contents = NULL;
}


// Custom Constructor
template <class type>
void Matrix<type>::create(int r, int c) {
// Set Integer Values
rows = r;
cols = c;

// Allocate Two-Dimensional Data
contents = new type*[r];
for (int i = 0; i < r; i++) {
contents[i] = new type[c];
}

}


// Copy Constructor
template <class type>
void Matrix<type>::copy(const Matrix &m) {
// Create New Matrix From Existing One
this->rows = m.getRows();
this->cols = m.getCols();

// Allocate Two-Dimensional Data
this->contents = new type*[m.getRows()];
for (int i = 0; i < m.getRows(); i++) {
this->contents[i] = new type[m.getCols()];
}

// Copy Over Data
for (int i = 0; i < m.getRows(); i++) {
for (int j = 0; j < m.getCols(); j++) {
(*this)[i][j] = m[i][j];
}
}

}


// Assignment Operator
template <class type>
Matrix<type> Matrix<type>::operator=(const Matrix<type> &m) {
// Overwrite Existing Matrix with Another
// (Allowing for Self-Assignment)
if (this != &m) {
this->destroy();
this->copy(m);
}

return *this;

}


// Destructor
template <class type>
void Matrix<type>::destroy() {
// Frees Allocated Memory
for (int i = 0; i < rows; i++) {
delete[] contents[i];
}
delete[] contents;

}


// Matrix Transpose
template <class type>
Matrix<type> Matrix<type>::transpose() const {

Matrix<type> tran(cols,rows);

for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
tran[j][i] = contents[i][j];
}
}

return tran;

}


// Threaded Matrix Multiplication
template <class type>
void matrixParallel(const Matrix<type>* a, const Matrix<type>* b, int numThreads, int currentThread, Matrix<type>* c) {

for (int i = currentThread; i < a->getRows(); i+=numThreads) {
for (int j = 0; j < b->getRows(); j++) {
type result = 0;
for (int k = 0; k < a->getCols(); k++) {
result += ((*a)[i][k]*(*b)[j][k]);
}
(*c)[i][j] = result;
}
}

}


// Matrix Multiplication
template <class type>
Matrix<type> Matrix<type>::multiply(const Matrix<type> &m1, const Matrix<type> &m2) {
if (m1.getCols() != m2.getRows()) {
cout << "Error: Cannot Multiply Matrices of Dimensions ";
cout << "(" << m1.getRows() << "x" << m1.getCols() << ")*";
cout << "(" << m2.getRows() << "x" << m2.getCols() << ")" << endl;
cout << " (Must be in the form (MxN)*(NxP)" << endl;
return Matrix<type>();
}


// Parallel Method
Matrix<type> m2t = m2.transpose();
Matrix<type> multiply(m1.getRows(), m2.getCols());

int numCPU = thread::hardware_concurrency();
thread* threads = new thread[numCPU];

const Matrix<type>* m1Pointer = &m1;
const Matrix<type>* m2tPointer = &m2t;
Matrix<type>* multiplyPointer = &multiply;

for (int i = 0; i < numCPU; i++) {
threads[i] = thread(matrixParallel<type>, m1Pointer, m2tPointer, numCPU, i, multiplyPointer);
}

for (int i = 0; i < numCPU; i++) {
threads[i].join();
}

delete[] threads;

return multiply;

}


(note, compiling in Cygwin with compiler option -std=c++11)


My friend implementation of operator* is a bit of a workaround, but I found that my two choices with using operators on templated classes were to use a series of forward declarations (that I couldn't get to work, and didn't really like the format of), or to implement the entire operation in the first declaration of the operator; I ended up doing the second in a cleaner way by using a dummy call object and calling another function that would perform the desired operation while still templated under the same type.


I'm not understanding why I'm not seeing a nearly linear speed-up with this approach, as each thread only does a fraction of the work depending on the number of cores available. Here's some benchmark data I've performed on varying sized matrices with this operation:



Single Thread
==========================================

5 Variables
------------------------------------------
100x5 * 5x5: 0.000157889 seconds
1000x5 * 5x5: 0.0010768 seconds
10000x5 * 5x5: 0.010099 seconds
100000x5 * 5x5: 0.112081 seconds
1000000x5 * 5x5: 1.04285 seconds

10 Variables
------------------------------------------
100x10 * 10x10: 0.000224202 seconds
1000x10 * 10x10: 0.00217571 seconds
10000x10 * 10x10: 0.0201944 seconds
100000x10 * 10x10: 0.203912 seconds
1000000x10 * 10x10: 2.04127 seconds

15 Variables
------------------------------------------
100x15 * 15x15: 0.000408143 seconds
1000x15 * 15x15: 0.00398906 seconds
10000x15 * 15x15: 0.0379782 seconds
100000x15 * 15x15: 0.381156 seconds
1000000x15 * 15x15: 3.81325 seconds

20 Variables
------------------------------------------
100x20 * 20x20: 0.000640239 seconds
1000x20 * 20x20: 0.00620069 seconds
10000x20 * 20x20: 0.060218 seconds
100000x20 * 20x20: 0.602554 seconds
1000000x20 * 20x20: 6.00925 seconds


2 Threads
==========================================

5 Variables
------------------------------------------
100x5 * 5x5: 0.000444063 seconds
1000x5 * 5x5: 0.00119759 seconds
10000x5 * 5x5: 0.00975319 seconds
100000x5 * 5x5: 0.09157 seconds
1000000x5 * 5x5: 0.965666 seconds

10 Variables
------------------------------------------
100x10 * 10x10: 0.000593268 seconds
1000x10 * 10x10: 0.00187927 seconds
10000x10 * 10x10: 0.0154861 seconds
100000x10 * 10x10: 0.161186 seconds
1000000x10 * 10x10: 1.5725 seconds

15 Variables
------------------------------------------
100x15 * 15x15: 0.000651292 seconds
1000x15 * 15x15: 0.00425471 seconds
10000x15 * 15x15: 0.0233983 seconds
100000x15 * 15x15: 0.232411 seconds
1000000x15 * 15x15: 2.43293 seconds

20 Variables
------------------------------------------
100x20 * 20x20: 0.000771287 seconds
1000x20 * 20x20: 0.0045547 seconds
10000x20 * 20x20: 0.0342536 seconds
100000x20 * 20x20: 0.381612 seconds
1000000x20 * 20x20: 3.79707 seconds


4 Threads
==========================================

5 Variables
------------------------------------------
100x5 * 5x5: 0.000690369 seconds
1000x5 * 5x5: 0.00120864 seconds
10000x5 * 5x5: 0.00994858 seconds
100000x5 * 5x5: 0.102673 seconds
1000000x5 * 5x5: 0.907731 seconds

10 Variables
------------------------------------------
100x10 * 10x10: 0.000896809 seconds
1000x10 * 10x10: 0.00287674 seconds
10000x10 * 10x10: 0.0177846 seconds
100000x10 * 10x10: 0.161331 seconds
1000000x10 * 10x10: 1.46384 seconds

15 Variables
------------------------------------------
100x15 * 15x15: 0.00100457 seconds
1000x15 * 15x15: 0.00366381 seconds
10000x15 * 15x15: 0.0291613 seconds
100000x15 * 15x15: 0.237525 seconds
1000000x15 * 15x15: 2.23676 seconds

20 Variables
------------------------------------------
100x20 * 20x20: 0.000928781 seconds
1000x20 * 20x20: 0.00486535 seconds
10000x20 * 20x20: 0.0421105 seconds
100000x20 * 20x20: 0.354478 seconds
1000000x20 * 20x20: 3.22576 seconds


Can anyone provide any insight as to what may be causing this? Any comments would be greatly appreciated.


qt - cannot get lambda to work

I have the following function in which, I want to prune my std::set<QString> words from words longer/shorter than main_word more than 4 characters.



void Cluster::prune(QString main_word)
{
words.erase(std::remove_if(words.begin(),
words.end(),
[=](QString w){return std::abs(main_word.length() - w.length()) > 4;}),
words.end());
}


I get the following error while building:



d:\qt\tools\mingw48_32\lib\gcc\i686-w64-mingw32\4.8.0\include\c++\bits\stl_algo.h:1176: błąd: passing 'const QString' as 'this' argument of 'QString& QString::operator=(const QString&)' discards qualifiers [-fpermissive]
*__result = _GLIBCXX_MOVE(*__first);
^


I'm a bit confused - what am I doing wrong with this lambda?


Polymorphism in template parameter [duplicate]


This question already has an answer here:




I have the following structure:


Two possible algorithms, one inherits the other, whose template parameter is a self defined container class.



template <class C>
class AlgBase {
protected:
C c;
};

template <class C>
class AlgDerived : public AlgBase<C> {};


The container class is templated as well, and the parameters are also related by inheritance:



class TParamBase {};
class TParamDerived : public TParamBase {};

template <class T> // T is TParamBase or TParamDerived
class Container {
protected:
T t_;
};


Now, in my main, I want to do the following:



typedef Container<TParamBase> ContainerBase;
typedef Container<TParamDerived> ContainerDerived;

int main (int argc, const char ** argv)
{
vector<AlgBase<ContainerBase>* > algs;
algs.push_back(new AlgBase<ContainerBase>);
algs.push_back(new AlgDerived<ContainerBase>);
algs.push_back(new AlgDerived<ContainerDerived>);
}


The first two push_back work since they use ContainerBase. The third fails because the use of ContainerDerived. The error is:



error: no matching function for call to ‘std::vector<AlgBase<Container<TParamBase> >*>::push_back(AlgDerived<Container<TParamDerived> >*)’
algs.push_back(new AlgDerived<ContainerDerived>);
^
main.cpp:34:52: note: candidates are:
In file included from /usr/include/c++/4.9/vector:64:0,
from main.cpp:3:
/usr/include/c++/4.9/bits/stl_vector.h:913:7: note: void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = AlgBase<Container<TParamBase> >*; _Alloc = std::allocator<AlgBase<Container<TParamBase> >*>; std::vector<_Tp, _Alloc>::value_type = AlgBase<Container<TParamBase> >*]
push_back(const value_type& __x)
^
/usr/include/c++/4.9/bits/stl_vector.h:913:7: note: no known conversion for argument 1 from ‘AlgDerived<Container<TParamDerived> >*’ to ‘AlgBase<Container<TParamBase> >* const&’
/usr/include/c++/4.9/bits/stl_vector.h:931:7: note: void std::vector<_Tp, _Alloc>::push_back(std::vector<_Tp, _Alloc>::value_type&&) [with _Tp = AlgBase<Container<TParamBase> >*; _Alloc = std::allocator<AlgBase<Container<TParamBase> >*>; std::vector<_Tp, _Alloc>::value_type = AlgBase<Container<TParamBase> >*]
push_back(value_type&& __x)
^
/usr/include/c++/4.9/bits/stl_vector.h:931:7: note: no known conversion for argument 1 from ‘AlgDerived<Container<TParamDerived> >*’ to ‘AlgBase<Container<TParamBase> >*&&’


The only solution I have in mind is to forget about TParamBase and TParamDerived and only use one class, but this is a bit inefficient since I will be creating and allocating elements not used.


Is there any other solution to make the third push_back work?


Thank you!