samedi 30 avril 2016

How to detect if operator[] applicable to Type?

I would like to write function template like

template< typename T >
void foo( T& obj ){
    obj[0] = xxxxxx;
}

where T must have operator[] applicable.
T may be array of any type, std::vector, std::array, or any other type. So, I cannot use T as superclass of all of them. I think it should be something like in std::type_traits style.

Saving and loading std::chrono::time_point to file

I am trying to simply save and reload the current time in a file. For example:

std::ifstream ifs(solar_system_cache_file,
        std::ios::in | std::ios::binary);

if (!ifs.is_open()) {
    return false;
}

std::chrono::system_clock::time_point cache_valid_time;
ifs >> cache_valid_time;

if (std::chrono::system_clock::now() < cache_valid_time) {
    std::cout << "Cache is VALID." << std::endl;
    return true;
}
ifs.close();

and

std::ofstream ofs(solar_system_cache_file,
        std::ios::out | std::ios::binary);

if (!ofs.is_open())
    return;

ofs << std::chrono::system_clock::now() + 12h;
ofs.close();

This sort of thing isn't complicated, but I've been looking around for hours and I cannot find relevant info. There are some example on how to cast using duration_cast<long, std::milli>, but std::chrono is extremely convoluted and hard to navigate (and digest).

In a nutshell, I believe I need to cast the current time to long (or some similar large type) and save that. When deserializing the time, I just have to cast it back to a time_point. It sounds easy enough, but I am unable to do so.

Finally, simply piping the time in fstream gives the usual invalid operands to binary expression error.

Any help is appreciated, or links to good tutorials/guides. Thank you

Variadic template class constructor with lvalues and rvalues

I'm building a machine learning library trying to get the most from the built-in features of C++, particulary C++11. I have a variety of classes that performs modification of the input, called Transformations. Now I want to build a pipeline of them, chaining them one after the other (and eventually having at the end of the chain a machine learning algorithm like a classifer or a regressor).

I think that a class with variadic template parameters is the perfect match for this use case. The thing is that I want to accept both rvalues and lvalues in the constructor.

In the case of an rvalue I want to move it, and in the case of an lvalue I want to keep a reference to it(although I'm still not 100% sure of this, because it could be a reference binded to some scope, and returning the pipeline as result of a function would blow up; but for the purporses of this library this could just be documented).

This would be the class:

template <class... Ts>
class Pipeline {
};

template <class T, class... Ts>
class Pipeline<T, Ts...> {
public:
    Pipeline(T?? transformation, Ts ??... following) : Pipeline<Ts...>(following...), _transformation(???) {}
...
}

I don't know if _transformation should be a reference or not, whether to std::move in the initialization list and what should be the types T and Ts in the constructor.

Edit: In the case of an lvalue, it should be non-const, because the pipeline can modify the transformation.

warning: 'auto' type specifier is a C++11 extension [-Wc++11-extensions]

I'm using Qt5 with Clang on Debian Jessie. To experiment with generic lambdas, in the .pro file there is:

CONFIG += c++14

And after building I got:

warning: 'auto' type specifier is a C++11 extension [-Wc++11-extensions]

To get rid of this obvious message I did:

QMAKE_CXXFLAGS += -Wc++11-extensions

But I keep getting the obvious message. Why? How to hide it?

Cython build can't find C++11 STL files - but only when called from setup.py

When I compile my code from setup.py, it can't find the C++11 include file <array> - but C++11 compiler features do work.

When I paste the same command line that setup.py generates into my shell, it all compiles perfectly well(!)

Code demonstrating this behavior can be seen here and is also pasted below.


Terminal session:

$ python setup.py build_ext
running build_ext
building 'simple' extension
creating build
creating build/temp.macosx-10.6-intel-3.4
/usr/bin/clang -fno-strict-aliasing -Werror=declaration-after-statement -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -arch i386 -arch x86_64 -g -Isrc -I/Library/Frameworks/Python.framework/Versions/3.4/include/python3.4m -c simple.cpp -o build/temp.macosx-10.6-intel-3.4/simple.o -Wno-unused-function -std=c++11
In file included from simple.cpp:289:
./simple.h:2:10: fatal error: 'array' file not found
#include <array>
         ^
1 error generated.
error: command '/usr/bin/clang' failed with exit status 1

$ /usr/bin/clang -fno-strict-aliasing -Werror=declaration-after-statement -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -arch i386 -arch x86_64 -g -Isrc -I/Library/Frameworks/Python.framework/Versions/3.4/include/python3.4m -c simple.cpp -o build/temp.macosx-10.6-intel-3.4/simple.o -Wno-unused-function -std=c++11

# no error!

$  /usr/bin/clang --version
Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)
Target: x86_64-apple-darwin13.4.0
Thread model: posix


setup.py:

#!/usr/bin/env python3

import platform, distutils.core, distutils.extension, Cython.Build

EXTENSION = distutils.extension.Extension(
    name='simple',
    sources=['simple.pyx'],
    extra_compile_args=['-Wno-unused-function', '-std=c++11'],
    language='c++',
    )

EXT_MODULES=Cython.Build.cythonize(
    [EXTENSION],
    language='c++',
    )

distutils.core.setup(
    name='simple',
    ext_modules=EXT_MODULES,
    )


simple.pyx:

cdef extern from "simple.h" namespace "fcolor4":
    struct Simple:
        int x


simple.h:

int foo() {
    auto x = 1;   // works, so must be C++11
    return x;
}

#include <string>  // works, so must find some STL.
#include <array>   // fails!

Added new library but still eclipse cannot find it

I've been trying to use libtins library in my c++ project,but I'm unable to run it. I compiled libtins from source in /usr/local/lib. In eclipse,in my project, I added in project >> properties >> cross G++ Compiler >> Includes the path of the header of the lib. Then in ... >> Cross G++ Linker >> Libraries I added in the -l field /usr/local/lib/libtins.so and in the -L field /usr/local/lib Then I modified the /etc/ld.so.conf file adding /usr/local/lib and running then ldconfig as sudo to refresh the cache but when I run it still say Building target:

 PacketSniffer
Invoking: Cross G++ Linker
g++ -L/usr/local/lib -o "PacketSniffer"  ./src/PacketSniffer.o   -l/usr/local/lib/libtins.so
/usr/bin/ld: cannot find -l/usr/local/lib/libtins.so
collect2: error: ld returned 1 exit status
make: *** [PacketSniffer] Error 1
makefile:45: recipe for target 'PacketSniffer' failed

Did i miss something?

Is there a difference between Debug and Release Mode in terms of memory allocation while using c++ in VS 2015

I am running this memory leakage code and I need to know if there is difference in memory allocation

int main() {
    while (true) {
        int* i = new int;
    }
return 0;
}

wrong pointer type c++

I'm getting the error:

error: request for member 'tm_sec' in 'timeinfo', which is of pointer type 'tm*' (maybe you meant to use '->' ?)

And my code is:

time_t rawtime;
struct tm * timeinfo;
time (&rawtime);
timeinfo = localtime (&rawtime);
int counter = 0;
std::string currentTime = asctime(timeinfo);

timeinfo.tm_sec = timeSeconds;

std::string timeSecondsString = std::to_string(timeSeconds);
std::string counterString = std::to_string(counter);
const char* timeChar = timeSecondsString.c_str();
const char* counterChar = counterString.c_str();

while(timeinfo.tm_sec = timeSeconds)
{
  counter = counter + 1;
}

if(timeinfo.tm_sec != timeSeconds)
{

   SDL_SetWindowTitle(gWindow, counterChar);
  counter = 0;
}

How would I go about fixing this? Also if I don't need any of the lines of code it would be nice to know.

How to use template parameter class on virtual methods?

I know that is not possible to use template on virtual method, because the compile there is no way to know how to implement all possibilities, but what I need is to use template on a restricted way, like that:

template<typename T, size_t N>
class MatBase {
 public:
  static constexpr size_t order = N;

  using value_type = T;

  MatBase() = default;
  virtual ~MatBase() = default;

  template<class Fn = T(T)>
  virtual void Map(Fn&& fn) = 0;

  template<class Fn = T(T,T)>
  virtual T Reduce(Fn&& fn) = 0;
};

It means, Fn uses the template declared on class, so I think it is possible to compiler infer all possible types. Are there way to do something like that C++?

How to avoid duplicate values in maps using c++

I am trying to write a program in cpp using maps...

My goal is to avoid the same values repeated in maps..

if the key is same ,we can use maps to avoid the duplicates keys.To allow duplicate keys ,we use multimaps

Incase if the value is same,how we can avoid ?

The program which i have written allows duplicate values

typedef std::map<int, std::string> MyMap;
int main()
{
        MyMap map;
        MyMap::iterator mpIter;

        int key;
        string value;
        int count;

        for(count = 0; count < 3;count++)
        {

                cin >> key;
                cin >> value;

                std::pair<MyMap::iterator, bool> res = map.insert(std::make_pair(key,value));


        }

       for (mpIter=map.begin(); mpIter != map.end(); ++mpIter)
         cout  << " "  << (*mpIter).second << endl;
}

Is it the best practice to use built in sort()function rather than merge sort whose complexity is always nlogn

worst case complexity of quick sort is n^2 and best n logn and heap sort and merge sort complexity is n logn both worst,best and average case.But heap sort is not stable in everywhere.Instead merge is stable.So merge is best.But built in sort() function is n logn and implementing this, is more easier than merge sort while save time and energy.Is there any case where merge sort is apllied rather than this.

#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
    int a[2000];
    int n=2000;
    for(int i=0;i<2000;i++)
    {
        a[i]=rand()%3000;//taking elements randomly less than 3000
    }
    sort(a,a+n);//sort elements .is it best practice instead use of merge sort always

}

C++ Addition within a Macro Function Argument

I have this snippet of C++ code from an exam. We are just suppose to write out what the output of the program is, I assumed the output would be '20', but the output is '10'. Why is this?

#define func(x) (x*x)-x

int i=3;

int main() {
    cout  << func(i+2) << endl;
}

If I put the i+2 in brackets like so:

cout  << func( (i+2) ) << endl; 

The output is '20' as assumed it would be.

How does C++ process this code that makes it return 10 not 20?

Can C++11 PRNG be used to produce repeatable results?

I'm working on a test suite for my package, and as part of the tests I would like to run my algorithm on a block of data. However, it occured to me that instead of hardcoding a particular block of data, I could use an algorithm to generate it. I'm wondering if the C++11 <random> facilities would be appropriate for this purpose.

From what I understand, the C++11 random number engines are required to implement specific algorithms. Therefore, given the same seed they should produce the same sequence of random integers in the range defined by the algorithm parameters.

However, as far as distributions are concerned, the standard specifies that:

The algorithms for producing each of the specified distributions are implementation-defined.

(26.5.8.1 Random number distribution class templates / In general)

Which — unless I'm mistaken — means that the output of a distribution is pretty much undefined. And from what I've tested, the distributions in GNU libstdc++ and LLVM project's libc++ produce different results given the same random engines.

The question would therefore be: what would be the most correct way of producing pseudo-random data that would be completely repeatable across different platforms?

VS2015 error C2976

VisualStudio can not compile this code (error C2976)

but GCC and Clang can compile this code

why???

#include <iostream>
#include <map>

template <typename... ARGS>
void Func(const std::map<ARGS...>& m)
{
    //...
}

template <typename T>
void Func(const T& t)
{
    //...
}

int main()
{
    std::map<int, double> m;
    Func(m);    // error C2976: 'std::map': too few template arguments
    Func(123);  // OK
    return 0;
}

How to iterate over values when std::vector::data is given

I have a function that returns in the following format:

 const value_type* data() const { return data_.data(); } 

At the place from the call is placed. I am trying to iterate over the values. But unable to figure as how to get an iterator when pointer to the first element in the array used internally by the vector is given.

Calling side:

for (auto y:X.data()) std::cout << y << " " <<std::endl;

But getting an

error: invalid range expression of type 'const int *'; no viable 'begin' function available

Connecting three different objects

I asked a similar question a couple of hours ago about connecting two elements of a vector. Now, I would like to make my question more general. Let's assume that we have two objects of the type double namely double d1, d2. We want the third object (double d3) to obtain the value of d1+d2, such that if we change d1 or d2, then d3 automatically obtains the new value of d1+d2. How can we do it in C++?

Thanks.

XCode unable to compile Poco project, undefined symbols

I've been looking for a proper HTTP parser in C++ and today I found that Poco has support for both parsing HTTP requests, setting up a server and also setting up a HTTPS server along with other cool features and I'm eager to start using it.

I've got a problem with compiling a small example though, the project is setup as a stdc++11 project, I've set the header and library search path to /usr/local/include and /usr/local/lib and have linked the libraries themselves in the Other Linker Flags in this order "-lPocoNet -lPocoUtil -lPocoFoundation -lPocoXML -lPocoJSON" the order of which doesn't seem to matter.

The code itself doesn't throw any errors within XCode, it's just when I try to compile it I get these reference errors, I've fixed 38 others of them by adding the libraries to the Other Linker Flags option but these two errors won't go away.

The error I'm getting is the following

Ld /Users/zezioen/Library/Developer/Xcode/DerivedData/NitroServer-gpnzdaqmezqcauegsmrabobsxotk/Build/Products/Debug/NitroServer normal x86_64
cd /Users/zezioen/stack/Projecten/CPP/NitroServer
export MACOSX_DEPLOYMENT_TARGET=10.11
/Applications/http://ift.tt/17KlLIW -arch x86_64 -isysroot /Applications/http://ift.tt/1jCtz97 -L/Users/zezioen/Library/Developer/Xcode/DerivedData/NitroServer-gpnzdaqmezqcauegsmrabobsxotk/Build/Products/Debug -L/Users/zezioen/stack/Projecten/CPP/NitroServer/lib -L/usr/local/lib -F/Users/zezioen/Library/Developer/Xcode/DerivedData/NitroServer-gpnzdaqmezqcauegsmrabobsxotk/Build/Products/Debug -F/Users/zezioen/stack/Projecten/CPP/NitroServer/lib -filelist /Users/zezioen/Library/Developer/Xcode/DerivedData/NitroServer-gpnzdaqmezqcauegsmrabobsxotk/Build/Intermediates/NitroServer.build/Debug/NitroServer.build/Objects-normal/x86_64/NitroServer.LinkFileList -mmacosx-version-min=10.11 -Xlinker -no_deduplicate -lPocoNet -lPocoUtil -lPocoFoundation -lPocoXML -lPocoJSON -stdlib=libstdc++ -Xlinker -dependency_info -Xlinker /Users/zezioen/Library/Developer/Xcode/DerivedData/NitroServer-gpnzdaqmezqcauegsmrabobsxotk/Build/Intermediates/NitroServer.build/Debug/NitroServer.build/Objects-normal/x86_64/NitroServer_dependency_info.dat -o /Users/zezioen/Library/Developer/Xcode/DerivedData/NitroServer-gpnzdaqmezqcauegsmrabobsxotk/Build/Products/Debug/NitroServer

Undefined symbols for architecture x86_64:
  "Poco::Net::HTTPMessage::setContentType(std::string const&)", referenced from:
      MyRequestHandler::handleRequest(Poco::Net::HTTPServerRequest&, Poco::Net::HTTPServerResponse&) in main.o
  "Poco::Util::Application::handleOption(std::string const&, std::string const&)", referenced from:
      vtable for MyServerApp in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

What do I have to do in order to get the project to build?

C++ Template Variadic - Call a member function once for every template argument

I have an EntityComponent-System and there's one component which should call functions on various other components. For this example here I've chosen a simple combination of the results of a boolean function.

The ResultCombinerComponent has variadic template arguments and for each of these arguments it should call a function, in the order that the template arguments are given. The order is very important.

Afterwards the results of the function calls are combined.

In the code below I just replaced the parts that I don't know how to achieve with psuedo-C++

template<typename... Args>
class ResultCombinerComponent
{
    template<typename T> 
    bool calcSingleResult()
    {
        return getComponent<T>()->calcResult();
    }

    bool calcResult()
    {
        bool result = true;
        for (int i = 0; i < sizeof...(Args); i++)  // doesn't work
        {
            if (!calcSingleResult<Args(i)>()  // doesn't work
            {
                result = false;
                break;
            }
        }
        return result;
    }

}


class A
{ 
    bool calcResult();
}
class B
{ 
    bool calcResult();
}
class C
{ 
    bool calcResult();
}

Singelton Object for nullptr

I would like to be able to create a singleton object for a nullptr in C++, like scala has. More specific I would like to create a singelton of a class, which is a subclass of every other C++ class, so I can return this object instead of nullptr from methods of every return type. Is there a way I can achieve this in C++? I dont want to know if this is a bad design or something like this. I don't realy want to use this in a project, I am just wondering if you can make such a thing in C++.

How to connect two elements of a vector?

I would like to know if there is a way in C++ to connect two elements of a vector for example std::vector such that if one is changed, the other changes automatically. If not is there any other way to do so?

Thanks.

facing error in output for different test cases

Problem

Alexey is playing with an array, A, of n integers. His friend, Ivan, asks him to calculate the sum of the maximum values for all subsegments of A. More formally, he wants Alexey to find F(A)=∑(l=1 to n)∑(r=l to n) max(l≤x≤r)A[x].

Alexey solved Ivan's challenge faster than expected, so Ivan decides to add another layer of difficulty by having Alexey answer m queries. The ith query contains subsegment [Li,Ri] and he must calculate the sum of maximum values on all subsegments inside subsegment [Li,Ri][Li,Ri].

More formally, for each query ii, Alexey must calculate the following function:

F(A,Li,Ri)=∑(l=Li to Ri) ∑(r=l to Ri) max(l≤x≤r)A[x].

Can you help Alexey solve this problem?

Input Format

The first line contains 2 space-separated positive integers, n (the length of array A) and m (number of queries), respectively. The second line contains n space-separated integers, a0,a1,…,an−1 describing each element aj (where 0≤j

Constraints 1≤n,m≤135000 −10^9≤ai≤10^9 1≤Li≤Ri≤n

Output Format For each query ii (where 0 ≤ i < m ), print its answer on a new line.

I tried to solve this but not passing all the test cases. Help me to find the error.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

long max(long *a,long x,long y){
    long m =a[x];
    for(long i=x+1;i<=y;i++){
        if(m<a[i])
            m=a[i];
    }
        return m;
}

void find(long a[] , long l[][2] ,long n,long m){
    for(long i=0;i<m;i++){
        long sum=0;
        for(long x=l[i][0];x<=l[i][1];x++){
            for(long y=x;y<=l[i][1];y++){
                 long m = max(a,x,y);
                 sum+=m;
            }
        }
        cout<<sum<<endl;

    }

}

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    try{
        long n, m;
        cin>>n>>m;
        if(n>135000||m>135000||n<1||m<1){
            throw 10;
        }
        long a[n];
        long l[m][2];
        for(long i=0;i<n;i++){
            cin>>a[i];
            if(a[i]>pow(10,9)||a[i]<pow(10,-9)){
                throw 10;
            }    
        }
        for(long j=0;j<m;j++)
            for(long k=0;k<2;k++){
            cin>>l[j][k];
            if(l[j][k]>n||l[j][k]<1){
                throw 10;
            }
            l[j][k]--;
        }
        find(a,l,n,m);
    }catch(...){
        cout<<"Constraint violated";
    }
    return 0;
}

Importing animation keytracks into Maya

I have a human bipedal animation file format that I would like to programmatically read into Maya using the C++ API.

The animation file format is similar to that of the Open Asset Importer's per-node animation structure.

For every joint, there is a series of up to 60 3D vector keys (to describe the translation of the joint) and 60 quaternion keys (to describe the rotation of the joint). Every joint is guaranteed to have the same number of keys (or no keys at all).

The length (time in seconds) of the animation can be specified or changed (so that you can set the 60 keys to happen over 2 seconds for a 30 FPS animation, for example).

The translations and rotations of the joints propagates down the skeleton tree every frame, producing the animation.

Here's a sample. Additional remarks about the data structure are added by the logging facility. I have truncated the keys for brevity.

Bone Bip01
    Parent null
    60 Position Keys
    0 0.000000 4.903561 99.240829 -0.000000
    1 0.033333 4.541568 99.346550 -2.809127
    2 0.066667 4.182590 99.490318 -5.616183
    ... (truncated)
    57 1.366667 5.049816 99.042770 -116.122604
    58 1.400000 4.902135 99.241692 -118.754120
    59 1.400000 4.902135 99.241692 -118.754120

    60 Rotation Keys
    0 0.000000 -0.045869 0.777062 0.063631 0.624470
    1 0.033333 -0.043855 0.775018 0.061495 0.627400
    2 0.066667 -0.038545 0.769311 0.055818 0.635212
    ... (truncated)
    57 1.366667 -0.048372 0.777612 0.065493 0.623402
    58 1.400000 -0.045869 0.777062 0.063631 0.624470
    59 1.400000 -0.045869 0.777062 0.063631 0.624470

Bone Bip01_Spine
    Parent Bip01
    60 Position Keys
    ...
    60 Rotation Keys
    ...

In C++, the data structure I currently have corresponds to this:

std::unordered_map<string, std::vector<Vector3>> TranslationKeyTrack is used to map a set of translation vectors to the corresponding bone.

std::unordered_map<string, std::vector<Quaternion>> RotationKeyTrack is used to map a set of rotation quaternions to the corresponding bone.

Additional notes: There are some bones that do not move relative to its parent bone; these bones have no keys at all (but has an entry with 0 keys). There are also some bones that have only rotation, or only position keys. The skeleton data is stored in a separate file that I can already read into Maya using MFnIkJoint.

The bones specified in the animation file is 1:1 to the bones in that skeleton data.

Now I would like to import this animation data into Maya. However, I do not understand Maya's way of accepting animation data through its C++ API.

In particular, the MFnAnimCurve function set addKeyFrame or addKey accepts only a single floating point value tied to a time key, while I have a list of vectors and quaternions. MFnAnimCurve also accepts 'tangents'; after reading the documentation, I am still unsure of how to convert the data I have into these tangents.

My question is: How do I convert the data I have into something Maya understands?

I understand better with examples, so some sample code will be helpful.

vendredi 29 avril 2016

issue in deleting last element of vector in a loop

In the below code if I try to remove any element except last one the code works fine . But if I try to delete last element it throws run time error . Not sure why ?

#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
    vector<string> s;
    s.push_back("Jacob");
    s.push_back("Jamal");
    s.push_back("Joseph");
    s.push_back("Janardan");
    vector<string>::iterator it;

    for(it = s.begin(); it != s.end() ; it++)
        cout<<*it<<endl;

    for(it = s.begin(); it != s.end() ; it++)
        if(*it == "Janardan")
           s.erase(it);  

    for(it = s.begin(); it != s.end() ; it++)
        cout<<*it<<endl;

    return 0;
}

C++11 print current system time (including milliseconds)

I wish to print the current time (based on say std::chrono::system_clock) whilst including milliseconds, e.g. 12:32:45.287. I can do it without milliseconds, with:

std::time_t time = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
char buffer[sizeof("HH:MM:SS")];
if (std::strftime(buffer, sizeof(buffer), "%H:%M:%S", std::localtime(&time)) == 0)
    std::cout << "Error formating time" << std::endl;
else std::cout << buffer << std::endl;

It would also be good if I could get an integer number of milliseconds. (I can get seconds with std::localtime(&time)->tm_sec)

Using RTTI hash with a template function

I understand that templates are compile-time, and typeinfo-related are runtime, but I'm wondering if I can achieve my particular task.

I have a factory method using templates to create objects of a particular type; I also have a preloader (reading data from disk), which determines what type of object is to be created, but doesn't actually create it - that's the responsibility of the creator, and is executed on demand.

void Creator::Spawn(Preloader* pl)
{
    std::unordered_map<size_t, std::type_index>   hashmap;

    // assume ObjectType is simply a wrapper around a hash
    hashmap[ObjectType<Type1>::GetType().Hash()] = typeid(Type1);
    hashmap[ObjectType<Type2>::GetType().Hash()] = typeid(Type2);

    for ( auto& const i : pl->GetPreloadInfo() )
    {
        size_t  hash = i->type_hash.Hash();

        // similar-to-desired usage
        FactoryCreate<hashmap[hash]>();
    }
}

Is there any way to achieve this? Obviously I can do manual checks for each, like below, but it's nasty at best.

        // poor, manual implementation
        if ( hash == ObjectType<Type1>::GetType().Hash() )
            FactoryCreate<Type1>();
        else if ( hash == ObjectType<Type2>::GetType().Hash() )
            FactoryCreate<Type2>();

Everything I've tried so far has hit the runtime vs compile-time differences, though I'm definitely not aware of all the newest C++11 tricks that may assist (C++14 not usable).

Partially related question here: Use data type (class type) as key in a map

Adding the two integers but one declared as an "int" and other as "auto"?

I am trying to find the sum of all the elements in an array, and declaring my initial accumulator variable sum as 0 using auto.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main(){
    int n;
    auto sum {0};
    cin >> n;
    vector<int> arr(n);
    for(int arr_i = 0;arr_i < n;arr_i++){
        cin >> arr[arr_i];
        sum=sum+arr[arr_i];
     }
     cout<<sum;
     return 0;
}

It is giving me a compilation error. I want to know what is wrong with this.

Cocos2d-x multidimensional array of Node *

Cocos2d-x 3.10

I need to create a 5x5 node matrix (array). So:

Node *n[5][5];
for (int x = 0; x < 5; x++) {
    for (int y = 0; y < 5; y++) {
        n[x][y] = Node::create();
        n[x][y]->setTag(0);
    }
}

void replaceMatrix() {
    Node *u[5][5];
    for (int x = 0; x < 5; x++) {
        for (int y = 0; y < 5; y++) {
            u[x][y] = Node::create();
            u[x][y]->setTag(0);
        }
    }
    **n = **u;
}

At some point during game play I need to replace this matrix with another (from a function call). My question is; how do I manage memory here? Simply replacing **n = **u won't release or free the nodes. I could call n[x][y]->release(); but is that all I need to do? Or, do I need to also free **n in some way?

I'm coming from heavy Java and C# skills and I use to do a lot of ObjC (pre ARC) programming in the day. I understand Cocos2d-x implements the Retain/Release model. I think my confusion comes from using Cocos2d-x Objects with a std C++ 2D array.

Accessing a vector iterator by index?

Recently I came across this code in my codebase (Simplified for here, of course)

auto toDelete = std::make_shared<std::string>("FooBar");
std::vector<decltype(toDelete)> myVec{toDelete};
auto iter = std::find_if(std::begin(myVec), std::end(myVec), 
   [](const decltype(toDelete) _next)
   {
      return *_next == "FooBar";
   });

if (iter != std::end(myVec))
{
   std::shared_ptr<std::string> deletedString = iter[0];
   std::cout << *deletedString;
   myVec.erase(iter);
}

Online Example

Now, I noticed that here we are accessing an iterator by indexing!

std::shared_ptr<std::string> deletedString = iter[0];

I've never seen anyone access an iterator by indexing before, so all I can guess at is that the iterator gets treated like a pointer, and then we access the first element pointed to at the pointer. So is that code actually equivalent to:

std::shared_ptr<std::string> deletedString = *iter;

Or is it Undefined Behavior?

Problems with boost library and c++11

I am trying to learn how boost filesystem work, but I can't get through some compilation problems

#include <boost/filesystem.hpp>
#include <iostream>

using namespace boost::filesystem;

int main()
{
  path p = current_path();
  directory_iterator it{p};
  while (it != directory_iterator{})
    std::cout << *it++ << '\n';
}

this is how I try to compile. My g++ version is 4.7

g++ -std=c++11 filesystem.cc -lboost_filesystem  -o filesystem 

After this I get thousands of errors. For example

In file included from /usr/include/boost/filesystem/path.hpp:23:0,
                 from /usr/include/boost/filesystem/operations.hpp:17,
                 from /usr/include/boost/filesystem.hpp:16,
                 from filesystem.cc:1:
/usr/include/boost/throw_exception.hpp: In instantiation of ‘void boost::throw_exception(const E&) [with E = boost::filesystem::basic_filesystem_error<boost::filesystem::basic_path<std::basic_string<char>, boost::filesystem::path_traits> >]’:
/usr/include/boost/filesystem/operations.hpp:280:9:   required from ‘typename boost::enable_if<boost::filesystem::is_basic_path<Path>, boost::filesystem::file_status>::type boost::filesystem::symlink_status(const Path&) [with Path = boost::filesystem::basic_path<std::basic_string<char>, boost::filesystem::path_traits>; typename boost::enable_if<boost::filesystem::is_basic_path<Path>, boost::filesystem::file_status>::type = boost::filesystem::file_status]’

Analyzing The Steps of code

So I know the output of the code is 8 2 but could someone show me how the value of i and j change after each step please.

Here is the link for the code: http://cpp.sh/84bk4

Explain pair function in C++

I encountered this code

#define pii pair<int, int>
#define pip pair<int, pii>

...

vector< pip > graph;
graph[i] = pip( c, pii(u,v));

When I try

graph[i] = pair<c,pair<u,v>>;

I get an error message

error: 'c' cannot appear in a constant-expression 
error: 'i' cannot appear in a constant-expression
error: 'j' cannot appear in a constant-expression

Why are these two expressions not equal?

Move semantic for thrust::device_vector

I am trying to simplify some code that make improper use of std::shared_ptr for handling objects returned by methods.

To do so, I want to rely on std::move, but I am afraid of the fact that thrust does not seem to handle the move construction properly. I wrote a small piece of code that intend to demonstrate this fact.

Could you tell me if the return value of this code is the one that we should expect from a proper implementation of move construction in thrust::device_vector ?

#include <thrust/device_vector.h>
#include <thrust/fill.h>

#include <iostream>
#include <cstdlib>
#include <vector>
#include <string>
#include <utility>
#include <algorithm>

class Foo
{
public:
    Foo() : m_v(1,5555)
    {
        std::cout <<"This is the normal constructor with addr "<<
        thrust::raw_pointer_cast( m_v.data() )<<std::endl;
    }
    virtual ~Foo()=default;

    //Copy constructor
    Foo( const Foo& other) : m_v(other.m_v)
    {
        std::cout <<"This is the copy constructor with addr "<<
        thrust::raw_pointer_cast( m_v.data() )<<std::endl;
    }
    //Move constructor
    Foo( Foo&& other) : m_v(std::move(other.m_v))
    {
        std::cout <<"This is the move constructor with addr "<<
        thrust::raw_pointer_cast( m_v.data() )<<std::endl;
    }
    //Move assignment
    Foo& operator=(Foo&& other)
    {
        m_v = std::move(other.m_v);
        std::cout <<"This is the move assignment operator with addr "<<
            thrust::raw_pointer_cast( m_v.data() )<<std::endl;
        return *this;
    }
    //Assignment operator
    Foo& operator=(const Foo& other)
    {
        m_v = other.m_v;
        std::cout <<"This is the assignment operator with addr "<<
        thrust::raw_pointer_cast( m_v.data() )<<std::endl;
            return *this;
    }
    void fillWithVal( int val )
    {
        thrust::fill(m_v.begin(), m_v.end(), val);
    }
    void printValue() const
    {
        std::for_each(m_v.cbegin(), m_v.cend(), [](int in){std::cout<<in<<std::endl;});
    }
protected:
    thrust::device_vector<int> m_v;
};

Foo GetFoo()
{
    Foo f;
    f.fillWithVal( 255 );
    return std::move(f);
}

//Compile using nvcc -std=c++11 ./main.cu -o ./test
//eventually with -fno-elide-constructors
int main()
{
    std::cout <<"test 0 "<<std::endl;
    Foo f = GetFoo();
    f.printValue();

    return EXIT_SUCCESS;
}

The return value is:

test 0 
This is the normal constructor with addr 0xd06c00000
This is the move constructor with addr 0xd06c00200
255

Why do I get two different addresses ? It looks like there is a new allocation of device_vector, and that the pointer to the raw data is not the same anymore.

I tested a very similar code of pure c++11 host code that make use of std::vector (not shown here) and I got the same value printed out for the raw pointer.

Thank you in advance for your help

Iterator-reducer pattern for functions that may or may not return a value

The following function applies a functor on each element and reduces the return value:

template <class FCT, class RED>
RED::TYPE forAllElements(FCT functor, RED reducer){
  for(/* all elem in elements */){
    reducer(functor(elem));
  }
  return reducer.value;
}

Now, sometimes I might wish to just call the functor on all elements, and not reduce anything. Basically, I would then like to have something like:

class FunctorThatReturnsNothing{
  void operator() (Elem e){
    // do something, return nothing...
  }
}

class DummyReducer{
  using TYPE = void; // ??? something like that ???

  template <class FCT>
  void operator() (/* ??? what here */){
    // do nothing...
  }
}

forAllElements(FunctorThatReturnsNothing(), DummyReducer());

But that won't compile since I have reducer(functor(elem)) where the non-existent return value of a void function is taken as an argument.

Is there a way to make it work for void functors without duplicating forAllElements for a void and a non-void case?

(For people suspecting an XY-Problem: I basically know different approaches for iterating and reducing and I think that the presented callback approach is appropriate for my case. I just wonder how I can avoid to have duplicate code for the "return value + reducing" and the "just callback" case.)

What is the difference between constand and constant reference argument

I have seen many people set their function argument as:

function(const myType &myObj)

I do not understand why they use & after the type?

It seems const is enough to stop the constructor from being called.

So, I wrote the following code and I see no advantage in the result. Can someone explain that?

#include <iostream>
using namespace std;

class myclass
{
public:

    myclass()
    {
        cout<<"constructor is called\n";
    }

    int field;
};

void func1(myclass a)
{
    cout<<"func1: "<<a.field<<"\n";
}


void func2(const myclass a)
{
    cout<<"func2: "<<a.field<<"\n";
}


void func3(const myclass &a)
{
    cout<<"func3: "<<a.field<<"\n";
}

int main ()
{
    myclass obj;
    obj.field=3;
    cout<<"----------------\n";
    func1(obj);
    cout<<"----------------\n";
    func2(obj);
    cout<<"----------------\n";
    func3(obj);
    cout<<"----------------\n";
    return 0;
}

Result:

constructor is called
----------------
func1: 3
----------------
func2: 3
----------------
func3: 3
----------------

Hash for boost::tuple containing std::vector

I have this code:

template <typename ReturnType, typename... Args>
function<ReturnType(Args...)> memoize(const function<ReturnType(Args...)>& func)
{
    using noRef = boost::tuple<typename std::remove_reference<Args>::type...>;
    ...
    static unordered_map<noRef, ReturnType> cache;
    auto result = cache.emplace(
        noRef{ boost::make_tuple(args ...) }, ReturnType{});
    if (result.second) { //ALWAYS TRUE WITH vector!
    ...

And I defined these 2 specializations for computing the hash of boost::tuple and std::vector:

namespace boost {
    namespace tuples {

        namespace detail {

            template <class Tuple, size_t Index = length<Tuple>::value - 1>
            struct HashValueImpl
            {
                static void apply(size_t& seed, Tuple const& tuple)
                {
                    HashValueImpl<Tuple, Index - 1>::apply(seed, tuple);
                    boost::hash_combine(seed, tuple.get<Index>());
                }
            };

            template <class Tuple>
            struct HashValueImpl<Tuple, 0>
            {
                static void apply(size_t& seed, Tuple const& tuple)
                {
                    boost::hash_combine(seed, tuple.get<0>());
                }
            };
        } // namespace detail

        template <class Tuple>
        size_t hash_value(Tuple const& tuple)
        {
            size_t seed = 0;
            detail::HashValueImpl<Tuple>::apply(seed, tuple);
            return seed;
        }

    }
}

namespace std {
    template <typename T> struct hash<std::vector<T>>
    {
        size_t operator()(const std::vector<T>  & v) const
        {
            size_t seed = 0;
            for (auto it = v.begin(); it != v.end(); it++)
                boost::hash_combine(seed, *it);
            return seed;
            /* your code here, e.g. "return hash<int>()(x.value);" */
        }
    };
}

This is the first time that I try to write a custom hash, but (as you can see from the comment) even if I use always the same vector<T> then there is always a successful insertion while it works fine if I use always the same double,double for example.

Why this happens?

How to initialize an array from a vector ? (How to cast a pointer to array ?) [duplicate]

This question already has an answer here:

I am trying to build a std::array from the data of a std::vector. I have currently done this :

#include <vector>
#include <array>

int main(void)
{
    std::vector<int>    vec1;
    std::array<int, 5>  arr{static_cast<int [5]>(vec.data())};

    (void)arr;
    return 0;
}

but gcc does not accept this cast :

error: invalid static_cast from type ‘int*’ to type ‘int [5]’

I thought an array could be used as a pointer so why cannot we do this cast ?

How do you static_assert the values in a parameter pack of a variadic template?

I'm creating a variadic template.
Let's say I have something like this:

template<typename T, T ... Numbers>
class Sequence final {

    // Unpack parameter pack into a constexpr array
    constexpr static T count = sizeof...(Numbers);        
    constexpr static T numbers[count] = { Numbers... };

    // ...
}

Instances of this class can be instantiated like:

Sequence<uint32_t, 1, 2, 3, 42, 25> seq;

I'd like to make sure at compile time using a static_assert that the numbers parameter pack only contains specific numbers. For the sake of this example, let's say I only want to allow 0 or 1.

So I'd like to do something like:

for (size_t i = 0; i < count; i++) {
    static_assert(numbers[i] == 1 || numbers[i] == 0, "Only ones and zeroes are allowed.");
}

But obviously, static_assert doesn't work with a for loop. I'm pretty sure there must be some sort of syntax for this but I haven't been able to figure it out.

C++11 vector

I notice that vector is much slower than bool array when running the following code.

int main() 
{
    int count = 0;
    int n = 1500000;
    // slower with c++ vector<bool>
    /*vector<bool> isPrime;
    isPrime.reserve(n-1);
    isPrime.assign(n-1, true);
    */
    // faster with bool array 
    bool* isPrime = new bool[n-1];

    for (int i = 0; i < n; ++i)
        isPrime[i] = true;


    for (int i = 2; i< n; ++i) {
        if (isPrime[i])
            count++;
        for (int j =2; i*j < n; ++j )
            isPrime[i*j] = false;
    }

    cout <<  count << endl;
    return 0;
}

Is there some way that I can do to make vector<bool> faster ? Btw, both std::vector::push_back and std::vector::emplace_back are even slower than std::vector::assign.

jeudi 28 avril 2016

Why does std::vector::emplace call destructor without any copy constructor called?

I am storing objects inside a std::vector, and I want to avoid calling destructor as much as possible.
I replaced copy constructor and assignments by move ones:

class Object
{
    Object(const Object&) = delete;
    Object(Object&&);
    Object& operator=(const Object&) = delete;
    Object& operator=(Object&&);
    [...]
};

I am initializing it like this:

std::vector<Object>   container;

container.reserve(42) // Reserve a lot in order to be sure it won't be a problem

Then, I add two elements with emplace_back (the constructor takes one int parameter):

container.emplace_back(1);
container.emplace_back(3);

Until there, everything is fine. But then I want to insert an element before the last one with emplace:

auto it = container.end();

it--; // Last position.
it--; // Before last position.
container.emplace(it, 2);

But here a destructor is called.

I tried to locate why with Valgrind, it appears emplace function calls _M_insert_aux that call my destructor.

How could I avoid that?

google API client library based C++ build error about sample source

I have to Explain the step by step .When i was to build error.

http://ift.tt/12aLcRc

133 ./prepare_dependencies.py

134 ls

135 mkdir build

136 cd build/

137 ../external_dependencies/install/bin/cmake ..

138 make

First i have to fallowing this Error.

/home/david/workspace/src/google-api-cpp-client/src/googleapis/client/data/jsoncpp_data.cc: In member function ‘virtual googleapis::util::Status googleapis::client::JsonCppData::LoadFromJsonReader(googleapis::client::DataReader)’: /home/david/workspace/src/google-api-cpp-client/src/googleapis/client/data/jsoncpp_data.cc:64:46: error: ‘class Json::Reader’ has no member named ‘getFormattedErrorMessages’ return StatusInvalidArgument(json_reader.getFormattedErrorMessages());

^
make[2]: ** [src/googleapis/client/CMakeFiles/googleapis_jsoncpp.dir/data/jsoncpp_data.cc.o] 
make[1]: *** [src/googleapis/client/CMakeFiles/googleapis_jsoncpp.dir/all] 2
make: *** [all] 2

I was correct the bad word ‘getFormattedErrorMessages- >‘getFormatedErrorMessages

140 ls

141 cd ..

142 ls

143 vi CMakeLists.txt

144 vi /home/david/workspace/src/google-api-cpp-client/src/googleapis/client/data/jsoncpp_data.cc

145 cd build/

146 make

[ 87%] Building CXX object src/samples/CMakeFiles/calendar_sample.dir/calendar_sample_main.cc.o
Linking CXX executable ../../bin/calendar_sample
/usr/bin/ld: cannot find -lgoogle_calendar_api
collect2: error: ld returned 1 exit status
make[2]: *** [bin/calendar_sample] 1
make[1]: *** [src/samples/CMakeFiles/calendar_sample.dir/all] 2
make: *** [all] 2
Second I was Correct the CMakefile in root dir.

    OFF -> option(googleapis_build_service_apis "Build specialized service APIs." ON)
    OFF -> option(BUILD_SHARED_LIBS "Build shared libraries (DLLs)." ON)

    and Service_api/Cmakefile.txt
    if(${dir} MATCHES "^([^/])//CMakeLists.txt")
    -> if(${dir} MATCHES "^([^/])/CMakeLists.txt")

CMakeFiles/calendar_sample.dir/calendar_sample_main.cc.o: In function googleapis::Display(std::string const&, google_calendar_api::Event const&)': calendar_sample_main.cc:(.text+0x8ef): undefined reference togoogle_calendar_api::Event::get_start() const' calendar_sample_main.cc:(.text+0x924): undefined reference to google_calendar_api::Event::get_start() const' calendar_sample_main.cc:(.text+0x9bb): undefined reference togoogle_calendar_api::Event::get_end() const'

calendar_sample_main.cc:(.text+0x9f0): undefined reference to google_calendar_api::Event::get_end() const' CMakeFiles/calendar_sample.dir/calendar_sample_main.cc.o: In functiongoogleapis::CalendarSample::Startup(int, char*)': calendar_sample_main.cc:(.text+0xd6e): undefined reference to `googleapis::client::OAuth2AuthorizationFlow::MakeFlowFromClientSecretsPath(std::string const&, googleapis::client::HttpTransport, googleapis::util::Status)'

  CMakeFiles/calendar_sample.dir/calendar_sample_main.cc.o: In function googleapis::CalendarSample::Run()': calendar_sample_main.cc:(.text+0x2659): undefined reference togoogle_calendar_api::Event::mutable_start()'
    calendar_sample_main.cc:(.text+0x26dc): undefined reference to google_calendar_api::Event::mutable_end()' calendar_sample_main.cc:(.text+0x28ba): undefined reference togoogle_calendar_api::Event::mutable_start()'
    calendar_sample_main.cc:(.text+0x293d): undefined reference to google_calendar_api::Event::mutable_end()' calendar_sample_main.cc:(.text+0x2b2f): undefined reference togoogle_calendar_api::Event::mutable_start()'
    calendar_sample_main.cc:(.text+0x2bc4): undefined reference to google_calendar_api::Event::mutable_end()' CMakeFiles/calendar_sample.dir/calendar_sample_main.cc.o: In functionvoid googleapis::DisplayList(std::string const&, std::string const&, google_calendar_api::CalendarList const&)':
    calendar_sample_main.cc:(.text.ZN10googleapis11DisplayListIN19google_calendar_api12CalendarListENS1_17CalendarListEntryEEEvRKSsS5_RKT[ZN10googleapis11DisplayListIN19google_calendar_api12CalendarListENS1_17CalendarListEntryEEEvRKSsS5_RKT]+0xda): undefined reference to google_calendar_api::CalendarList::get_items() const' CMakeFiles/calendar_sample.dir/calendar_sample_main.cc.o: In functionvoid googleapis::DisplayList(std::string const&, std::string const&, google_calendar_api::Events const&)':
    calendar_sample_main.cc:(.text.ZN10googleapis11DisplayListIN19google_calendar_api6EventsENS1_5EventEEEvRKSsS5_RKT[ZN10googleapis11DisplayListIN19google_calendar_api6EventsENS1_5EventEEEvRKSsS5_RKT]+0xda): undefined reference to `google_calendar_api::Events::get_items() const'
    collect2: error: ld returned 1 exit status
    make[2]: ** [bin/calendar_sample] 1
    make[1]: *** [src/samples/CMakeFiles/calendar_sample.dir/all] 2
    make: *** [all] 2

So i can`t build to success . Plz Anyone help me ~

why does the standard let me free-store allocate classes without constructors?

If you have a class without a destructor:

struct A {
    ~A() = delete;
};

The standard does not let me "locally" allocate an instance of that class:

int main()
{
    A a; //error
}

But it seems like it is ok if I allocate that on free-store:

int main()
{
    a *p = new A();
}

As long as I dont call delete on that pointer:

int main()
{
    a *p = new A();
    delete p; //error
}

So my question is, why does the standard let me have a class without a destructor if I allocate it on free-store? I would guess there are some use cases for that? But what exactly?

How can I properly re-write c++11 lamda experssion without lamda expr

I have a following code:

class Variant
{
public:
    void init();
}

void Variant::init()
{
    int var 1;
    vector list;
    vector list2;

    tbb::parallel_for(tbb::blocked_range<std::size_t>(0, list.size(), ClrSize),
    [this, &var1, &list,&list2](const tbb::blocked_range<std::size_t> &range)
    {
        /*some code here*/
    }

I thought about implementing operator()(const tbb::blocked_range &range)

class Variant
{
public:
    void operator()(const tbb::blocked_range<std::size_t> &range)
    {
        /*some code here*/
    }
    void init();
}

void Variant::init()
{
    int var 1;
    vector list;
    vector list2;

    tbb::parallel_for(tbb::blocked_range<std::size_t>(0, list.size(), ClrSize), this);
}

but it doesn't solve capture list problem.

How I can re-write lamda expression? What can I do with var1, list, list2 arguments?

Thanks

C++, any queue-lock style mutexes?

I'm currently working with a system where the input is event driven but the output needs to be ordered so the first request will be the first response. The reason for this systems design is that the requests work on semi-large datasets and will take a while to process. So it'll take 10 requests and create a thread for each, process the data and then lock at a SendResponse type function.

What would be the easiest way to go about implementing some queue for the mutex at the SendResponse function?

My first thought was to make a queue of thread id's; check if the current thread is the front entry in SendResponse and sleep if it's not. But there's surely a better way?

move semantics inside assignment operator - side effects, destruction

Forcing Move Semantics

So in a sense, we have drifted into the netherworld of non-deterministic destruction here: a variable has been assigned to, but the object formerly held by that variable is still out there somewhere. That's fine as long as the destruction of that object does not have any side effects that are visible to the outside world. But sometimes destructors do have such side effects. An example would be the release of a lock inside a destructor. Therefore, any part of an object's destruction that has side effects should be performed explicitly in the rvalue reference overload of the copy assignment operator:

X& X::operator=(X&& rhs)
{

  // Perform a cleanup that takes care of at least those parts of the
  // destructor that have side effects. Be sure to leave the object
  // in a destructible and assignable state.

  // Move semantics: exchange content between this and rhs

  return *this;
}

I get that l-value's original object normally is destructed - eventually - in a NON-assignment situation.

But, in an assignment operator, why would you want the same behavior?

How does respecifying a inherited virtual method allow it to disambiguate correctly?

I was doing some fun stuff with googlemock and decided to split my classes into pure virtual classes and concrete implementations to avoid needing to special casing for my mocks. However, the compiler started complaining that:

error: undefined reference to 'vtable for <ConcreteClass>'

I managed to reproduce the issue with the following:

simple.h:

namespace simple {

class InterfaceA {
 public:
  virtual ~InterfaceA() {}

  virtual int MethodOne() const = 0;
};

class InterfaceB : public InterfaceA {
 public:
  ~InterfaceB() override {}

  virtual int MethodTwo() const = 0;
};

class ImplA : public InterfaceA {
 public:
  ImplA(int to_return);
  ~ImplA() override {}

  int MethodOne() const override;

 private:
  int to_return_;
};

class ImplB : public InterfaceB, public ImplA {
 public:
  ImplB();
  ~ImplB() override {}

  // int MethodOne() const override;
  int MethodTwo() const override;
};
}  // namespace simple

simple.cc

#include "simple.h"

namespace simple {

ImplA::ImplA(int to_return) : to_return_(to_return) {}
int ImplA::MethodOne() const { return to_return_; }

ImplB::ImplB() : ImplA(5) {}
// int ImplB::MethodOne() const { return ImplA::MethodOne(); }
int ImplB::MethodTwo() const { return 2; }
}  // namespace simple

The issue was the bits I have commented out; once I added those things into the files, the compiler and my tests were happy. So intuitively this makes sense, as now there are concrete methods defined for the virtual ones, and the compiler previously doesn't/can't guess which super class methods I wanted.

My question is twofold:

  1. How does the specification of ImplA::MethodOne() allow it to be called as it isn't a static variable?
  2. Is there an implicit ImplA pointer somewhere in the ImplB object at creation time that allows it to call a method on ImplA despite not being a static method?

Implementing a Multi task executioner using Boost Coroutines

I'm searching for a way to use Boost Stackfull Coroutines as a multitask executioner in one single core, instead of using threads. I'm accustomed to develop Python code using the asyncio module and I would like to replicate the same behaviour using Boost Coroutines (Boost.Coroutine2 if possible).

My search at Google returned some old Boost documentation, explaining how I could do it using the Boost.Coroutine lib. For some reason that I not aware of, the current Boost.Coroutine documentation is not equal and does not contain any information that could relate to the old one.

Is there a way for me to use Boost.Coroutines in the same way I use the Python asynchronous Coroutines?

Latter part of code somehow affecting former

I have this program:

#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <sstream>
#include <algorithm>

int main(int argc, const char * argv[]) {
    std::vector<int> task_scores;
    int n;
    std::cin >> n;
    for(int i = 0; i < n; i++) {
        int sc;
        std::cin >> sc;
        task_scores.push_back(sc);
    }
    std::map<std::string, std::vector<size_t>> student_solutions;
    std::string command = "";
    while(true) {
        std::vector<std::string> tok_com;
        getline(std::cin, command);
        std::stringstream strstream(command);
        std::string token = "";
        while (getline(strstream, token, ' ')) {
            std::cout << token;
            tok_com.push_back(token);
        }
        if (tok_com[0] == "SOLVED") {
            std::string name = tok_com[1];
            int task = std::stoi(tok_com[2]);
            if(std::find(student_solutions[name].begin(), student_solutions[name].end(), task) !=
               student_solutions[name].end()) {
                student_solutions[name].push_back(task);
            }
        }
    }
    return 0;
}

If you comment out if clause, then code works just fine. But if you don't, the code stops with EXC_BAD_ACCESS when trying to cout the token. How can this happen?

c++11 uniform initialization doesn't work with "g++ -std=c++0x"

I have a class that declares this public method:

virtual std::vector<float> operator()(const std::vector<float>& = {});

which uses uniform initialization (here just {}), a feature from c++11. This doesn't give me any problem when compiling with clang++ -std=c++11. But when I use g++ -std=c++0x I get this:

error: expected primary-expression before '{' token

Isn't the -std=c++0x option supposed bring me c++11 support?

The compiler doesn't give me any error when declaring the method using standard c++ like this:

virtual std::vector<float> operator()(const std::vector<float>& = std::vector<float>());

I am using g++ 4.6 on Ubuntu 12.04

How to write a dispatch function using libprocess library in c++

#include <iostream>
#include <sstream>
#include <process/defer.hpp>
#include <process/dispatch.hpp>
#include <process/future.hpp>
#include <process/http.hpp>
#include <process/process.hpp>

using namespace std;
using namespace process;
using namespace process::http;
using std::string;

class SimpleProcess : public process::Process<SimpleProcess>
{
public:
  Future<Nothing> doSomething(const std::string msg)
  {
    std::cout << "Wrapping message: " << msg << std::endl;
    return Nothing();
  }
  Future<int> calc(int lhs, int rhs)
  {
    return Promise<int>(lhs + rhs).future();
  }
private:
  Promise<int> p;
};

int main(int argc, char **argv)
{
  SimpleProcess simpleProcess;
  Promise<int> p;
  process::PID<SimpleProcess> pid = process::spawn(&simpleProcess);
  process::dispatch(pid, &SimpleProcess::doSomething, "test test test");
  process::dispatch(pid, &SimpleProcess::calc, 99, 101)
  .then([+ , &p](int i , int j) {
    p.set( i + j);
    return p.future();
  });
return 0;

Get answers from broadcast

I'm implementing a WSDiscovery service using Poco::Net::DatagramSocket. This is the code:

string OnvifCamera::_sendFullProbe_for_Discovery() const noexcept
{
    Poco::Net::DatagramSocket ss(Poco::Net::IPAddress::IPv4);
    Poco::Net::SocketAddress sa(global.getDiscoveryIP(), global.getDiscoveryPort()); //IP "239.255.255.250", port 3702
    try
    {
        auto msg = _createXML_for_FullProbe();//is the XML probe x discovery
        ss.sendTo(msg.data(), msg.size(), sa);
    }
    catch (const Poco::IOException& ex)
    {
        cerr<<"\nException: "<<ex.what()<<", "<<ex.displayText()<<endl;
        return string();
    }
    ss.setBroadcast(true);

    char buffer[4096];
    int n = ss.receiveBytes(buffer, sizeof(buffer));
    cout<<"Got "<<n<<" bytes"<<endl;
    ss.close();
    return string(buffer);
}

Every device (IP Onvif camera), will answer with his XML data. The problem is that if I have more cameras, I can get only 1 camera's answer. How can I get ALL the answers?

Thank you Cristiano

In C++ std:: streams, after a failure, how to get a failure reason? Required: threadsafe and common to Windows and Linux (or at least Msvc/Gcc)

Sorry for weird title. Limited to 150 chars so couldn't use proper sentences.

So let's say I've done the following to find out that something went wrong with my file stream:

std::ofstream ofs;
do_stuff_with(ofs);
// streams don't throw on error because C++
// so we have to check for failure manually
if(!ofs){
    auto fail_code = errno; // threadsafe on Win/Linux
    // but what goes here?
}

1) strerror: Not threadsafe

2) strerror_s: Not in GCC? Or is it?

3) strerror_r: Not in Msvc? Or is it?

4) #ifdef/#define/etc: yuck, but may be the only choice

I did do some searching but I didn't find a "this will definitely work in a sensible yet slightly platform-dependent way" answer...

Have a template parameter that can be pointer or value

Suppose I have something like:

template <class T>
void do_something(T t){
  pass_it_somewhere(t);
  t->do_something();
}

Now it would be useful that T is allowed to be a pointer or a value. Function do_something(...) can basically handle pointers and values, except for the t->do_something(). For pointers, I would need a -> and for values, I would need a . to access members.

Is there a way to make T accept pointers and values?

TMP C++ and parameter packs

template<std::size_t... Is>
void unlock_(std::index_sequence<Is...>) {

    iter(std::get<Is>(tuple)...);
}

Let's consider above example. I cannot understand iter(std::get<Is>(tuple)...);. I know that ... is expanding "operator". So it should be applied to parameter pack ( in sense arguments) or template paremeter packs. And I can imagine what is std::index_sequence<Is...>. Because Is is template parameter pack it should be just 1, 2, 3, 4, ... ( for example) . In that case out parameter is specific because it is not type. It is size_t.

But here: std::get<Is>(tuple)...); std::get(tuple) doesn't return parameter/template pack so I cannot context of usage.

P.S. Is it possible to see how the code looks after meta-programming? Similiary to after preprocessing?

Thanks in advance.

Is it possible to check a condition on a derived class where the base class only in known?

I would like to be able to check whether a certain condition is true or not on an object of some Derived type, which in the local context is only known through its Base type.

The condition to be checked needs the Derived type.

One possible way of doing this is the following.

Define the classes

class Base {
//...  
public:
  using Condition = std::function<bool(const Base*)>;
  bool check(const Condition&);
}

class Derived : public Base {
//...
public:
  int index() const { return index;}
private:
  int index;
}

and suppose we have a Derived-aware context, where I can encapsulate the the Derived-specific condition in a lambda function. We can then dispatch the Condition functor to the context where it is going to be needed:

 //context where Derived class is known

 int idx = 1;

 auto derivedCondition = [idx](const Base* obj) {
    Derived* derivedObj = dynamic_cast<const Derived*>(obj); 
    if (derivedObj)        
      return (derivedObj->index() == idx);
    return false;
 };

 // dispatch condition to an external context where it will be used, this context is not aware of Derived
 useConditionElsewhere(derivedCondition);

with

 void useConditionElsewhere(Condition condition) {

    //context where only base class is known
    Base* baseObj;
    //...

    bool checked = baseObj->check(condition);
    //..
 }

The above achieves what I need.

My question is: is it possible to do this without casting?

When move constructor will get called in C++11?

I am not able to understand why why move constructor is not getting called while move assignment is able to while if I use move function in Line X , it used to call the move constructor . Can anybody tell what will be the way or syntax to call the move constructor .

#include <iostream>
#include <cstring>
#include <algorithm>
#include <memory>
using namespace std;
class String
{
    char *s;
    int len;
    public:
    String():s(nullptr),len(0){ cout<<"Default "; }
    String(char *p)
    {
        if(p)
        {
            len = strlen(p);
            s = new char[len];
            strcpy(s,p);
        }
        else
        {
            s = nullptr;
            len = 0;
        }
        cout<<"Raw ";
    }
    String(String &p)
    {
        if(p.s)
        {
            len = strlen(p.s);
            s = new char[len];
            strcpy(s,p.s);
        }
        else
        {
            s = nullptr;
            len = 0;
        }
        cout<<"Copy ";
    }
    String & operator = (const String & p)
    {
        if(this != &p)
        {
            delete []s;
            s = nullptr;
            len = 0;
            if(p.len)
            {
                len = p.len;
                s = new char[len];
                strcpy(s,p.s);
            }
        }
        cout<<"Assignment ";
        return *this;
    }
    String( String && p):s(nullptr),len(0)    // move constructor 
    {
        len = p.len;
        s = p.s;
        p.s = nullptr;
        p.len = 0;
        cout<<"Move Copy ";
    }
    String & operator = (String && p)       // move assignment
    {
        if(this != &p)
        {
            delete []s;
            len = 0;
            s = nullptr;
            if(p.len)
            {
                len = p.len;
                s = p.s;
                p.s = nullptr;
                p.len = 0;
            }
        }
        cout<<"Move Assignment ";
        return *this;
    }
    ~String() { delete []s; cout<<"Destructor \n"; }
    void show() { cout<<s<<endl; }
};
int main()
{
   String s1("Something ");
   String s2(s1);
   s1.show();
   s2.show();
   String s4(String("Nothing "));       // Line X
   s4.show();
   String s5;
   s5 = String(s2);
   s5.show();
   return 0;
}

OUTPUT:

Raw Copy Something Something Raw Nothing Default Copy Move Assignment Destructor Something Destructor Destructor Destructor Destructor

Is it possible to use VIM in large C++11 projects?

I am fluent with vim's keys and use it a lot, especially for automated edits.

But is that possible to set up vim for working with large C++11 codebase with a lot of macros and templates? Can it parse all the 10000 sourcefiles, build (and dynamically rebuild) a complete "index of everything" and autocomplete anything almost as Eclipse does?

Please suggest the best known manual / plugins for using vim in large modern (C++11) projects?

Is std::make_unique SFINAE-friendly?

I'm doing some template-meta-programming and I would like to implement a generic cloning function that selects a method of cloning depending on the validity of expressions via SFINAE (Substitution Failure Is Not An Error).

On this reference website it says that

The function

make_unique<T>( std::forward<Args>(args)... )

is equivalent to:

unique_ptr<T>(new T(std::forward<Args>(args)...))

Does this mean that the following code

template <typename T>
auto my_clone( const T & t ) -> decltype( std::make_unique<T>(t) )
{
    return std::make_unique<T>(t);
}

should be completely equivalent to

template <typename T>
auto my_clone( const T & t ) -> decltype( std::unique_ptr<T>( new T(t) ) )
{
    return std::unique_ptr<T>( new T(t) );
}

even when I have other overloads of the function my_clone? In other words: is std::make_unique() SFINAE-friendly?

If T is not copy constructible, then the latter code would not participate in overload resolution due to SFINAE.

Here's a small example that fails to compile on GCC 5.3 with C++14 turned on:

#include <memory>

// It does **not** work with this snippet:
template <typename T>
auto my_clone( const T & t ) -> decltype( std::make_unique<T>( t ) )
{
    return std::make_unique<T>( t );
}

/* // But it works with this snippet instead:
template <typename T>
auto my_clone( const T & t ) -> decltype( std::unique_ptr<T>( new T(t) ) )
{
    return std::unique_ptr<T>( new T(t) );
}*/

// This is another overload for testing purposes.
template <typename T>
auto my_clone( const T & t ) -> decltype(t.clone())
{
    return t.clone();
}  

class X
{
public:
    X() = default;

    auto clone() const
    {
        return std::unique_ptr<X>( new X(*this) );
    }

private:
    X( const X & ) = default;
}; 

int main()
{
    // The following line produces the compiler error: 
    // "call to 'my_clone' is ambiguous"
    const auto x_ptr = my_clone( X() ); 
}

GNU g++ 4.9.2 Compilation Error for a find function call

I have StringVec defined as :

typedef std::vector<string> StringVec;

Variable colnames is defined as:

StringVec colnames;

And I have a function as below:

int colIndex(const string &cn) const {
        StringVec::iterator i1;
        i1 = find(colnames.begin(),colnames.end(),cn);
        return(i1 == colnames.end() ? -1 : (i1 - colnames.begin()));
}

When I try to compile with GNU g++ 4.9.2 (C++11), it complains:

error: no matching function for call to 'find(std::vector<std::basic_string<char> >::const_iterator, std::vector<std::basic_string<char> >::const_iterator, const string&)'
 i1 = find(colnames.begin(),colnames.end(),cn);

Even std::find couldn't solve this. Another clue is given by compiler:

note:   template argument deduction/substitution failed:
note:   '__gnu_cxx::__normal_iterator<const std::basic_string<char>*, std::vector<std::basic_string<char> > >' is not derived from 'std::istreambuf_iterator<_CharT>'
  i1 = std::find(colnames.begin(),colnames.end(),cn);

Any clue?

Passing an array of Child objects to a function that accepts Parent*

I am working on an embedded platform with limited capabilities, so vectors/STL are not available.

This may be a trivial problem, but I do not have much experience in C++ (only C and C#, which may make me blind to an obvious c++ way to do it).

Consider the following example:

class Parent {
};

class Child : public Parent {
};

void Test(Parent* parents, uint8_t parentCount) {
    // Accessing parent[x] is problematic when 'parents' contains a derived type
}

int main() {
    // This is OK
    Parent parents[3];
    Test(parents, 3);

    // This causes problems
    Child children[3];
    Test(children, 3);

    return 0;
}

Obviously it is problematic to iterate over parents in Test(), if a pointer to an array of derived classes is provided, because the memory footprint of Parent is assumed during the iteration.

The only solution I see is to pass an array of pointers of type Parent (*Parent** parents*), but that seems cumbersome. Is there some C++ mechanism I am not aware of, like passing the array as a reference or something?

Static dispatching to correct member method with hierarchies of aggregate types

I have written a small in-house framework which does something akin to:

Group<ObjectA1, ObjectA2> groupA(data);
Group<ObjectB> groupB(data);

// Compiles, as desired:
groupA.get<ObjectA1>();
groupA.get<ObjectA2>();
groupB.get<ObjectB>();

// Compilation errors (static asserts), as desired:
groupA.get<ObjectB>();
groupB.get<ObjectA1>();
groupB.get<ObjectA2>();

However, I'm struggling to extend it with the following abilities:

// ...continued...

using GroupA = Group<ObjectA1, ObjectA2>;
using GroupB = Group<ObjectB>;
AggregateGroup<GroupA, GroupB> group(groupA, groupB);

// Compiles, as desired
group.get<ObjectA1>();
group.get<ObjectA2>();
group.get<ObjectB>();

// Compilation error, as desired:
group.get<ObjectC>();

This can be generalized to groups consisting of other groups. Runtime solutions are easy, but I'm at a loss on how to do this at compile time.

Question: How can we create hierarchies of aggregate types that statically dispatch to the correct member?

PS: If a minimal version of my current implementation is required, please indicate so and I will update the question accordingly.

Does Windows std::thread uses internally PPL?

Is the implementation of Visual Studio 2015's std::thread internally based on PPL's task system?

The background of my question is, does it make sense to use std::thread for several tasks, because they are already executed balanced on the common threadpool, or is it better to execute the tasks via PPL tasks?

According to (Which std::async implementations use thread pools?) this seems to be, but since the question is rather old I would like to get an "official" answer.

C++ typedef and templates syntax?

I was reading this tutorial on variadic templates, but in below code:

 template<int index, class C>
struct container_index {

  // points to the "next" container type 
  typedef typename container_index<
    index-1,
    typename C::base_container
  >::container_type container_type;

  // points to the next T-type 
  typedef typename container_index<
    index-1,
    typename C::base_container
  >::type type;
};

these typedefs seems redundant but it compiles well. The problem is simply I dont understand why they are like this and I didnt find a tutorial explaining this case. Could someone give some explanation? Why the typedef name is repeated:

"::container_type container_type;"

 "::type type;"

It couldn't be just like that:

typedef typename container_index<
        index-1,
        typename C::base_container
      >  type;

Many thanks.

Appending a string literal with a compile time generated integer

I'm trying to generate a string during compile-time that contains a constant string and a couple calculated integers.

This string is to be used in GCC's attribute((section(""))) directive.

The purpose of the whole thing is to put a few variables in an ELF file, each with a unique section name.

I used to do this by compiling each object file with -DSOME_SYMBOL= to differentiate between object files, and COUNTER to differentiate between variables inside of a single object file. (We use this because of a requirement from our logging solution)

So the resulting code would be used using something like this:

#define SOME_MACRO(msg) {\
    static const char *messageBuffer __section__((section(".msg" ## #SOME_SYMBOL ## #__COUNTER__))) = {msg};\
} // Approximation

SOME_MACRO("This is a string");

This solution works great, but it requires support from the build-system (calculating the CRC and injecting it as a GCC -D flag), and it became a bit of an overhead when we moved from Makefile to SCons.

So I searched for another solution, and found this compile time CRC solution, but I got a bit lost when trying to figure out how to append it to the string.

After a bit more searching, I found the following answer, which explains how to convert an integer to a string using template metaprogramming, but I still couldn't figure out how to append the strings (again, during compile time).

I'd love to find a solution for this problem.

Bcrypt installtion issue on windows 10

Node version - v5.10.0

npm version - 3.8.5

I am trying to install bcrypt on sails package but it is showing following error.

C:\Users\ashish\Desktop\Project\myproj\myproj\node_modules\bcrypt>if not defined npm_config_node_gyp (node "C:\Users\ashish\AppData\Roaming\npm\node_modules\npm\bin\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild )  else (node "" rebuild )
Building the projects in this solution one at a time. To enable parallel build, please add the "/m" switch.
  blowfish.cc
  bcrypt.cc
  bcrypt_node.cc
C:\Users\ashish\Desktop\Project\myproj\myproj\node_modules\nan\nan.h(41): fatal error C1189: #error :  This version
 of node/NAN/v8 requires a C++11 compiler [C:\Users\ashish\Desktop\Project\myproj\myproj\node_modules\bcrypt\build\
bcrypt_lib.vcxproj]
..\src\bcrypt.cc(232): warning C4267: '=' : conversion from 'size_t' to 'unsigned char', possible loss of data [C:\User
s\ashish\Desktop\Project\myproj\myproj\node_modules\bcrypt\build\bcrypt_lib.vcxproj]
gyp ERR! build error
gyp ERR! stack Error: `C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onExit (C:\Users\ashish\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\lib\build.js:276:23)
gyp ERR! stack     at emitTwo (events.js:100:13)
gyp ERR! stack     at ChildProcess.emit (events.js:185:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:204:12)
gyp ERR! System Windows_NT 10.0.10240
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\ashish\\AppData\\Roaming\\npm\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Users\ashish\Desktop\Project\myproj\myproj\node_modules\bcrypt
gyp ERR! node -v v5.10.0
gyp ERR! node-gyp -v v3.3.1
gyp ERR! not ok
npm ERR! Windows_NT 10.0.10240
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\ashish\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js" "install" "bcrypt" "--save"
npm ERR! node v5.10.0
npm ERR! npm  v3.8.5
npm ERR! code ELIFECYCLE

npm ERR! bcrypt@0.8.6 install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the bcrypt@0.8.6 install script 'node-gyp rebuild'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the bcrypt package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node-gyp rebuild
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs bcrypt
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls bcrypt
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     C:\Users\ashish\Desktop\Project\myproj\myproj\npm-debug.log

what to install for resolving c++11 compiler.

I tried to install it from http://ift.tt/1SuFNP0 but didn't able to resolve it.

strange behaviour of using statements in g++

Consider following program:

namespace s1 {
 int m;
}
namespace s2 {
    using s1::m;
}
int main() {
    using s1::m;
    using s2::m;
}

It compiles fine without any errors on clang (See live demo here) & MSVC++ 2015 (See live demo here) but fails in compilation on g++ 5.3.0. (See live demo here). It gives following error message:

prog.cc: In function 'int main()':
prog.cc:9:12: error: redeclaration of 'int s1::m'
  using s2::m;
            ^
prog.cc:2:6: note: previous declaration 'int s1::m'
  int m;

So, the question here is which compiler is right here according to standard? Is g++ incorrect here & is it g++'s bug ?

copy constructor does initialize primitive data types

#include <iostream>

using namespace std;

class Foo
{
public:
        int a;
};
int main()
{
        Foo f;
        Foo f1(f);
        cout<<f.a;
        return 0;
}

Here f.a prints garbage value but when we add f1.a then both f.a and f1.a is initialized with 0.

#include <iostream>

using namespace std;

class Foo
{
public:
        int a;
};
int main()
{
        Foo f;
        Foo f1(f);
        cout<<f.a<<f.b;
        return 0;
}

Please help me to understand what is the reason behind this.

C++ vector: get item by index and at()

I have a vector<A*> v; A* ptr = nullptr; I wanna know what is the difference between ptr=v.at(0); and ptr=v[0]; thanks!

using sprintf with std::string in c++

I am using sprintf function in C++ 11, in the following way:

std::string toString()
{

    std::string output;
    uint32_t strSize=512;
    do
    {
        output.reserve(strSize);
        int ret = sprintf(output.c_str(), "Type=%u Version=%u ContentType=%u contentFormatVersion=%u magic=%04x Seg=%u",
            INDEX_RECORD_TYPE_SERIALIZATION_HEADER,
            FORAMT_VERSION,
            contentType,
            contentFormatVersion,
            magic,
            segmentId);

            strSize *= 2;
        } while (ret < 0);
        return output;

    }   

Is there any better way to do this, than to check every time if the reserved space was enough? For future possibility of adding more things.

Operator overloading C++ reference or value

I've seen many tutorials and tried to find the answer on stackoverflow but with no success. What I'm not sure is, is there some praxis when to return by value or by reference, when overloading operator?

For ex.

Class &operator+(){
  Class obj;
  ...
  return obj;
}

or the same thing but by value

Class operator+(){
  Class obj;
  ...
  return obj;
}

And yeah I'd like to mention, I've noticed that in almost 90% of cases when returning the same object(*this), is being reference on the same object returned. Could someone explain why is that so, as well? Thanks!

mercredi 27 avril 2016

Adding a space to a linked list

I have been banging my head against a wall for the past few days figuring out how to add a space to the output after reading a file. The code reads from a file and outputs to the console "Ilikecomputers", when it should be printing out "I like computers". Any tips on how to add the space?

Thanks

The code is below

#include <iostream>
#include <list>
#include <ctype.h>
#include <fstream>

using namespace std;

void printList(const list<char> &myList);
void fillList(list<char> &myList);
void changeCase(list <char> &myList);

void printList(const list<char> &myList)
{
   list<char>::const_iterator itr;
   cout << "\nAfter Conversion: " << endl;
   for (itr = myList.begin(); itr != myList.end(); itr++ ) {
   cout <<*itr;
}
cout << '\n';
}

void fillList(list<char> &myList)
{
ifstream file("test.txt");
    string print;
    while(file >> print){
    for (int i = 0; i<print.length(); i++) {
    myList.push_back(print[i]);
  }
 }
}

int main ()
{
  list<char> myList;

  cout << "Before Conversion: " << endl;
  ifstream file("test.txt");
  string print;
  while(file >> print){    
  cout << print << " ";
 }

  fillList(myList);
  printList(myList);

 return 0;
}

std::move with std::make_pair

Is there any difference between:

std::map <int,std::pair<T,T>> m;
T t1,t2;
m.emplace(1,std::make_pair(t1,t2));

and:

std::map <int,std::pair<T,T>> m;
T t1,t2;
m.emplace(1,std::move(std::make_pair(t1,t2)));

Is the std::move redunddent here? Will std::map::emplace and perfect forwarding take care of allocating the std::pair directly in the std::map?

Efficiently instert tuple into container through move

I'm a move semantics beginner. Is this code:

template <typename... Args>
void foo(const Args & ... args){
    map<tuple<Args...>, int> cache;
    auto result = cache.emplace(move(make_tuple(args ...)),1);
    //...
    }

More efficient than:

template <typename... Args>
void foo(const Args & ... args){
    map<tuple<Args...>, int> cache;
    tuple<Args...> t(args...);
    auto result = cache.insert(make_pair(t,1));
    //...
    }

Especially if args contains some big object?

Same question but with std::vector (so no need for make_pair or make_tuple)

Converting possible lvalue reference template to lvalue

What I'm trying to achieve is something like this:

template<typename T>
void foo(T t) {
    TWithoutReferenceType t1 = Magic(t); //some magic here
}

TWithoutReference is the same type of T but without reference, so for example:

Magic(int i) -> int i
Magic(int& i) -> int i
Magic(int&& i) -> int i 

I don't know if this is possible for rvalue references or what it could mean in practice though.

Sequentially consistent memory and atomic registers

Sequential Consistency (for data race free programs, SC-DRF) is the strongest shared memory consistency model provided by modern programming languages (e.g., Java or C++11).

In ''Art of Multiprocessor Programming'' the authors (M. Herlihy and N. Shavit) use notion of atomic register in most of the theorems throughout the book.

Is it correct to say that volatile references in Java and atomics with std::memory_order seq_cst in C++ are (indistinguishable from) atomic registers? Is it possible to observe difference between linearizable registers and atomics in C++ if its memory model guarantees sequential consistency on whole space of memory locations marked as std::atomic?

Axis separating algorithm for concave polygon splitted into convex ones

I'm trying to build a solid collision system but I'm blocked when I want to get the impacted edge.

So far I have: - Split my polygon if concave into triangles. - Merge back the triangles while forming a convex polygon.

So my object's body is defined by a vector of convex polygons.

I implemented the axis separating algorithm and it works well.

Now I would like to get the impacted edge but I can't manage to find a way to retrieve it.

I read that article: http://ift.tt/1LIl2fX

I understand(theoretically, I didn't test it) how to get the intersecting face between two polygons but how can I manage to retrieve the intersecting face of two bodies composed of multiple polygons ?

If anyone have ressources about that problem, I will be happy to read it. Thank you in advance.

Creating a graph data structure in C++ error

I am trying to create a graph data structure and I have a couple questions. First, why am I getting this error?

In file included from main.cpp:2:0:
graph.h: In instantiation of ‘void graph<T>::addVertex(const T&) [with T = int]’:
main.cpp:8:17:   required from here
graph.h:72:5: error: ‘int graph<int>::vertex::data’ is private
   T data;   //vertex stores data of any type
     ^
graph.h:103:52: error: within this context
     std::cout << "Just created vertex with data: " << x.data << std::endl;
                                                    ^
graph.h: In instantiation of ‘graph<T>::vertex::vertex(const T&) [with T = int]’:
graph.h:102:18:   required from ‘void graph<T>::addVertex(const T&) [with T = int]’
main.cpp:8:17:   required from here
graph.h:72:5: warning: ‘graph<int>::vertex::data’ will be initialized after [-Wreorder]
   T data;   //vertex stores data of any type
     ^
graph.h:57:8: warning:   ‘bool graph<int>::vertex::visited’ [-Wreorder]
   bool visited;  //used for paths. True if vertex has been visited
        ^
graph.h:60:6: warning:   when initialized here [-Wreorder]
      vertex(const T& d = T{}): data(d), visited(false){}

Basically I am creating a graph class and declaring/ using a vertex and edge class in it. Here is the code for that:

      class vertex{
           public:
                bool visited;           //used for paths. True if vertex has been visited

                //vertex constructor
                vertex(const T& d = T{}): data(d), visited(false){}
                //vertex move constructor
                vertex(T&& d): data(std::move(d)), visited(false){}
                //returns data in vertex
/*              T& operator*(){ return retrieve(); }
                //returns const reference to data in vertex
                const T& operator*() const{ return retrieve(); }
                //returns list of adjacent vertices
                std::list<vertex>& getList() const{ return adjacent; }*/
                //adds vertex to current vertex's adjacency list
                void addToList(const vertex& add){ adjacent.push_back(add); }
           private:
                T data;                 //vertex stores data of any type
                std::list<vertex> adjacent;     //list of adjacent vertices

                T& retrieve() const{ return data; }
        };

This is declared within class Graph{};

What is the error about? And what is the best way to implement from scratch, I would like to work on some cool projects with it.

***EDIT: IN CASE IT HELPS HERE IS THE FULL CLASS

#ifndef GRAPH_H_
#define GRAPH_H_

#include <iostream>
#include <list>
#include <vector>
#include <string>
//#include "edge.h"

template <typename T>
class graph{

   private:
        class vertex;           //FORWARD DECLARATION OF CLASS VERTEX

        //We are declaring the edge class first so the rest of the graph class functions
        //know it exists
        class edge{
           public:
                //default edge constructor
                edge(): start(nullptr), end(nullptr), weight(0){;}
                //constructor with two vertex parameters creates edge
                edge(const vertex& x, const vertex& y, int w)
                   :start(x), end(y), weight(w) {;}
                //edge destructor
                ~edge(){
                   delete start;
                   delete end;
                };

                //edge copy constructor
                edge(const edge& e){
                   start = e.start;
                   end = e.end;
                   weight = e.weight;
                };

                //edge move copy constructor using move semantics
                edge(edge&& e){
                   start = std::move(e.start);
                   end = std::move(e.end);
                weight = e.weight;
                };

                //edge move copy constructor using move semantics
                edge(edge&& e){
                   start = std::move(e.start);
                   end = std::move(e.end);
                   weight = e.weight;
                };

//              typename std::list<vertex>::iterator findEdge(std::list<vertex>& l, vertex a, vertex b);
           private:
                vertex* start;
                vertex* end;
                int weight;

                friend class graph<T>;
        };   //END OF EDGE CLASS

        //Each vertex holds a list of adjacent vertices
        class vertex{
           public:
                bool visited;           //used for paths. True if vertex has been visited

                //vertex constructor
                vertex(const T& d = T{}): data(d), visited(false){}
                //vertex move constructor
                vertex(T&& d): data(std::move(d)), visited(false){}
                //returns data in vertex
/*              T& operator*(){ return retrieve(); }
                //returns const reference to data in vertex
                const T& operator*() const{ return retrieve(); }
                //returns list of adjacent vertices
                std::list<vertex>& getList() const{ return adjacent; }*/
                //adds vertex to current vertex's adjacency list
                void addToList(const vertex& add){ adjacent.push_back(add); }
           private:
                T data;                 //vertex stores data of any type
                std::list<vertex> adjacent;     //list of adjacent vertices

                T& retrieve() const{ return data; }
        };

   public:
        //graph default constructor
        graph();
        //graph destrcutor
        ~graph();
        //graph constructor with 2 vertex parameters
        graph(const vertex& x, const vertex& y);
        //graph copy constructor
        graph(const graph& g);
        //graph copy move constructor
        graph(graph&& g);
        //graph assignment operator
        graph& operator=(const graph& g);
        //graph move assignment operator
        graph& operator=(graph&& g);
/*      //graph constructor with linked list of edges parameter
        graph(const list<edge>& edges);
*/

        //returns vertex
        vertex& getVertex(const T& data);
        //creates and adds a vertex to the graph
        void addVertex(const T& data){
           vertex x(data);
           std::cout << "Just created vertex with data: " << x.data << std::endl;
           vertices.push_back(x);
        }
        //connects an edge to the graph
        void addEdge(const vertex& x, const vertex& y);
        //determines whether first vertex is reachable by the second vertex
        bool isReachable(const vertex& start, const vertex& end) const;
        //returns list of adjacent neighbors of vertex
        std::list<vertex>& getNeighbors(const vertex& v){ return v.getList(); }

   private:
        size_t numVertices;
        size_t graphWeight;
        std::list<vertex> vertices;
        std::list<edge> edges;


};   //END OF GRAPH CLASS

   #include "graph.hpp"

Thanks

Operator comma overloading

I'm trying to learn more about how operator overloading works.

I understand that overloading the comma operator may not be the best idea, but this is for instructional purposes only.

I'm expecting the following code to use my overloaded operator (I used brackets as I'm aware the comma operator has the lowest precedence) to construct a vector containing (1,2) and then call the vector's assignment operator.

However, I get an error:

no known conversion from argument 1 from 'int' to 'const std::vector<int>&'

I don't understand why this is happening. (1,2) should construct a vector so it shouldn't be trying to convert from an int to a vector<int>?

#include <vector>
#include <utility>

using std::vector;
using std::move;

template <typename T>
vector<T> operator,(const T& v1, const T& v2)
{
    vector<T> v;
    v.push_back(v1);
    v.push_back(v2);
    return move(v);
}

int main()
{
    vector<int> a;
    a = (1,2);
    return 0;
}

std::forward with templated overloaded function

I've got no idea why compiler gives me warnings about template instantiations.

Thats a piece of code which runs just fine and outputs lvalue/rvalue properly:

//template<typename T>
void overloaded(const /*T*/std::string& in)
{
    std::cout << "lvalue" << std::endl;
}

//template<typename T>
void overloaded(/*T*/std::string&& in)
{
    std::cout << "rvalue" << std::endl;
}

template<typename T>
void pass(T&& in)
{
    overloaded(std::forward<T>(in));
}

int main()
{
    std::string a;
    pass(a);
    pass(std::move(a));
    getchar();
}

But i need to use it with templated type. So modifying the "overloaded" functions to

template<typename T>
void overloaded(const T& in)
{
    std::cout << "lvalue" << std::endl;
}

template<typename T>
void overloaded(T&& in)
{
    std::cout << "rvalue" << std::endl;
}

Gives template instantiations warnings, (when to me its clear T should be std::string), and console outputs rvalue 2 times instead of lvalue first.

What am i doing wrong?