FAQ Database Discussion Community


Spin locked stack and memory barriers (C++)

c++,multithreading,c++11,concurrency,memory-barriers
I have a implementation spin lock: class Spinlock { public: void Lock() { while (true) { if (!_lock.test_and_set(std::memory_order_acquire)) { return; } } } void Unlock() { _lock.clear(std::memory_order_release); } private: std::atomic_flag _lock; }; I use SpinLock class in: class SpinlockedStack { public: SpinlockedStack() : _head(nullptr) { } ~SpinlockedStack() { while (_head...

C++ why does SFINAE fail with only a class template parameter?

c++,templates,c++11,sfinae
I'm using SFINAE in the style of this answer in order to call a generic vector object by using an appropriate member function. For example, the following code calls operator[](int) const first, and if that doesn't exist then operator()(int) const: template<int I> struct rank : rank<I-1> { static_assert(I > 0,...

When the main exits where does the console output go?

multithreading,c++11
#include<iostream> #include<thread> using namespace std; void func() { for (int i = 0; i < 10000; i++)cout << "Print" << endl; } int main() { thread t(func); t.detach(); cout << "Exit" << endl; return 0; } In the above code, when the main exits, where does the "Print"text would be...

Junk varchar entries in MSSQL database using ODBC

c++,sql-server,c++11,odbc
I'm trying to insert a string-variable into a varchar(100)-field, but if the string is longer than 15 elements only junk is inserted (e.g. "0‰?"). First my setup: Development: Win7 (64bit) / VS2013 / C++11 / 64bit Application Database: Win8 (64bit) / Microsoft SQL Server Express 2014 (64bit) Driver: SQL Server...

Why is the boolean value within a structure within a vector not being updated?

c++,c++11
This might sound like a very basic question, but I have trying to fix a simple bug for over an hour now and I can't seem to understand what's happening. I have the following structure declaration in my header file: struct StudentBody { string name; Vec2 position; bool disabled; StudentBody(string...

C++ unordered_map move beginner error

c++11,move,unordered-map
Sorry for the noob question here, but i don't even know what to search on google. I tried some documention on the move semantic but i still can't solve my problem. So if somebody can give me some clues, i'll be really thanksfull. About the code: graph.hpp: #ifndef GRAPH_HPP #define...

Passing something as this argument discards qualifiers

c++,c++11
Using the below code, i get the following compile error: In static member function ‘static std::string ctedata::Record::getDispatcher<std::basic_string<char> >::impl(const ctedata::Record&, const string&)’: /home/jason/CrownTheEmpire/lib/ctedata/data.h:111:38: error: passing ‘const std::map<std::basic_string<char>, std::basic_string<char> >’ as ‘this’ argument discards qualifiers [-fpermissive] return rec.fieldValues_[field]; ^ In file included from /usr/include/c++/5.1.0/map:61:0, from...

Atomic/not-atomic mix, any guarantees?

c++,multithreading,c++11,atomic
Let's I have GUI thread with code like this: std::vector<int> vec; std::atomic<bool> data_ready{false}; std::thread th([&data_ready, &vec]() { //we get data vec.push_back(something); data_ready = true; }); draw_progress_dialog(); while (!data_ready) { process_not_user_events(); sleep_a_little(); } //is it here safe to use vec? As you see I not protect "vec" by any kind of...

syntax for calling a method on a member with multiple instances

c++11,inheritance,c++14
I the following case template<typename T> class base{ public: void test(){} }; template<typename T> class helper{ public: base<T> t; }; template<typename T, typename ... Ts> class holder: public helper<T>, helper<Ts>... { }; int main(int argc, char *argv[]){ holder<int, short, long> h; h.t.test(); // of course, error here } Which compiles...

need help to search element from vector of struct

c++,function,c++11,std
I have vector of struct partationPartItemTag_t type typedef struct partationPartItemTag { std::string partition; std::string partGroupId; std::string mathTuid; std::string partNumber; tag_t itemTag; }partationPartItemTag_t; I want to find element from vector having value for partition == 'a' and partGroupId == 'b' I have written following code and its working fine with C++11...

Segmentation fault when initializing a std::vector

c++11,segmentation-fault,stdvector
What are the possible causes of a segmentation fault at the following line? std::vector<double> d(8); ...

Why doesn't std::string contain a split() method? [on hold]

c++,string,c++11
I presume that there is a legitimate reason behind std::string class not containing a method to split a string based on a delimiter. With the existence of boost::split (and other good solutions posted here: Split a String in C++), it appears that it is possible to make a generic solution....

Insert std::string and shared pointer to object in map

c++,c++11,dictionary,singleton
I'm using singleton design pattern (I can't use the copy constructor). I have a: Obj.hpp and Obj.cpp file House.hpp and House.cpp file The Obj class contains a map of Houses, where I can search for a house using a string. I can't even compile my Obj.cpp file, don't know why......

Why is erasing via a const_iterator allowed in C++11?

c++,c++11,stl,const,erase
As of GCC 4.9.2, it's now possible to compile C++11 code that inserts or erases container elements via a const_iterator. I can see how it makes sense for insert to accept a const_iterator, but I'm struggling to understand why it makes sense to allow erasure via a const_iterator. This issue...

for loop init variable scope between c++, java, C#

java,c#,c++,c,c++11
I have a problem in understanding the difference in scope of initial variable of for loop in those 4 languages C, C++, C#, Java What I know is that in C#: for ( int i = 1; i<=5; i++) here, i is a local variable dose not appear out the...

How best to prevent unused variable warnings in custom assert without sizeof?

c++,c++11,lambda,assert,sizeof
Based on advice in http://cnicholson.net/2009/02/stupid-c-tricks-adventures-in-assert/ I've been working with my own version of assert (called emp_assert) for a while now. As such, when NDEBUG is set, my assert looks like: #define emp_assert(EXPR) ((void) sizeof(EXPR) ) This definition assures that any variables in EXPR still count as "used" in the compiler,...

forward_list: assign(_InputIterator __first, _InputIterator __last) / assign(size_type __n, const _Tp& __val)

c++,c++11,forward-list
I have implemented a subset of the forward_list and wanted to test the method assign(size_type __n, const _Tp& __val) but I get a compiler error because the compiler wants to call the method assign(_InputIterator __first, _InputIterator __last) instead. I have written the following snippet, just to illustrate the problem: test.h...

How to match one of multiple alternative patterns with C++11 regex [duplicate]

c++,regex,c++11
This question already has an answer here: Strange results when using C++11 regexp with gcc 4.8.2 (but works with Boost regexp) [duplicate] 1 answer With Perl, the following results in a match: echo xyz | perl -ne 'print if (/.*(yes|no|xy).*/);' I'm trying to achieve the same thing with a...

Template specialization with std::enable_if<>

c++,templates,c++11,template-specialization
The following code compiles and runs: #include <cinttypes> #include <cstdlib> #include <iostream> #include <limits> #include <sstream> #include <stdexcept> class UnsignedBox { public: typedef std::uint64_t box_type; template<typename UNSIGNED_TYPE, typename std::enable_if< std::numeric_limits<UNSIGNED_TYPE>::is_signed==false && (sizeof(UNSIGNED_TYPE) >= sizeof(UnsignedBox::box_type)), int>::type = 0 > UNSIGNED_TYPE toUnsigned()const { //We've established we're not returning a...

Fast method to transform a string with about 150mb

c++,performance,c++11
I've been trying to decrease every single char value in a std::stringstream by 100: std::string str = stream.str(); auto decrement = [](char c) { return c - 100; }; std::string out; out.reserve(str.size()); std::transform(str.begin(), str.end(), std::back_inserter(out), decrement); stream = std::stringstream(out); But it took 7 minutes stuck on the std::transform instruction. That...

Is executing C++ code in comments with certain Unicode characters allowed, like in Java?

c++,c++11,unicode,comments
I know that executing Java code in comments with certain Unicode characters is allowed. Please see this question for further clarification Executing Java code in comments. So was just curious to know if C++ has such features?

Address of an instance emplaced to std::vector is invalid

c++11,vector,standards,emplace
I have 2 std::vectors: to first vector, I emplace instance to second vector, I want to store the address of the instance just emplaced But it does not work, i.e., the stored address differs from the emplaced instance's address. If it matters at all, I'm on Linux and using g++...

Implicit use of initializer_list

c++,c++11,initializer-list
§[dcl.init.list] 8.5.4/2: The template std::initializer_list is not predefined; if the header <initializer_list> is not included prior to a use of std::initializer_list — even an implicit use in which the type is not named (7.1.6.4) — the program is ill-formed. Does that mean this program is ill-formed? #include <vector> int main()...

Relationship of std::unique_lock and conditional_variable cond

c++,multithreading,c++11
Here is my code: Class class carl{ public: int x = 0; std::mutex _mu; std::condition_variable cond; bool donecreating = false; void createFood(){ if(x == 0){ std::unique_lock<mutex> locker(_mu); x++; std::cout<<"creating food.."<<std::endl; cout<<"Food count: "<<x<<endl; locker.unlock(); cond.notify_one(); //notify std::this_thread::sleep_for(chrono::seconds(1)); //sleep } } void eatFood(){ std::unique_lock<mutex> locker(_mu); //lock std::cout<<"i am executing"<<std::endl; //notif...

Why is my code failing to compile? (perfect forwarding and parameter packs)

c++,c++11,perfect-forwarding,variadic-parameter
Here is the program: #include <memory> struct A; struct B { void fn(A* ptr) {} }; template<typename ...Args> void foo(B* b, void (B::*func)(Args...), Args&&... args) { (b->*func)(std::forward<Args>(args)...); } struct A { void bar() { B b; foo(&b, &B::fn, this); } // fails }; int main() { A a; B b;...

Turning this raw pointer situation into a unique_ptr?

c++,c++11,smart-pointers,unique-ptr
I have code that looks like this: ISessionUpdater* updater = nullptr; if (eventName == "test") updater = new TestJSONSessionUpdater(doc); if (eventName == "plus") updater = new PlusJSONSessionUpdater(doc); if (updater) { bool result = updater->update(data); delete updater; return result; } return false; Is there any way to do something like this...

C++ vector error C2036: 'int (*)[]' : unknown size

c++,templates,c++11,vector
I am getting 5 compile errors C2036: 'int (*)[]' : unknown size all from various places in the vector class. #include <gl\glew.h> #include "Vector2.h" #include "Vector3.h" #include "WFObjModel.h" #include <vector> #include <memory> using namespace math; using std::vector; using std::string; using io::WFObjModel; using std::unique_ptr; class Mesh { private: GLuint textureID; unique_ptr<vector<Vector3<float>>>...

Read a variable in another thread

multithreading,c++11,atomic,stdatomic
I'm using linux and I have two variable that is read/write in another thread. Once in a while (100ms) ThreadB reads the status of the variables and does something. It's basically a while(1){ dosomething(); usleep(); }. I'm worried the variables will be cached and never updated. What's the best way...

“Emulating” std::declval issues. Works (kind of) in g++, fails to compile in clang++

c++,c++11,decltype
Trying to better understand std::declval, I came up with the following "toy model" code: #include <iostream> #include <typeinfo> struct Bar { Bar(double); // some non-default ctor double f(); // some function of which return type we want to get }; using Barref = Bar&&; // emulating std::declval<Bar>() int main() {...

Sorting based on the rules set by a string variable

c++,qt,sorting,c++11
In my hypothetical app, I receive a list of hotels from the server. struct Hotel { std::string name; // e.g. Hilton, Ritz int stars; // In range [0..5], 0 stands for "unrated" int freeRoomCount; // Number of available rooms [0..N] int parkingPlacesAvailable; // Number of parking places availalble [0..M] }...

Remove smallest non-unique value from vector

c++,algorithm,c++11,unique
I have an unsorted vector of doubles (Actually objects with a double member which is used in this case). From this vector I need to remove the smallest non-unique value. However, it is not guaranteed that a non-unique value exists. It is allowed to sort the range. As always I...

Function with variable parameters as parameter to function C++

c++,templates,c++11
I am trying to create measuring class with one function that take function to be measured as parameter. Its called ChronoTimer.h content is: #include <chrono> template<typename TimeT = std::chrono::milliseconds, class ClockT = std::chrono::system_clock> class ChronoTimer { public: template<typename F, typename ...Args> static typename TimeT::rep duration(F func, Args&&... args) { auto...

c++ vector bubble sort

c++,c++11,vector,bubble-sort
I use g++ -std=c++11 Sort.cpp to compile my file. My problem is the bubble sort don't sort. Maybe I'm passing the vector by value but I don't know is closely my firt time trying work with c++ and I chose use vector library. My code is: #include <iostream> #include <vector>...

How can I convert an int to a string in C++11 without using to_string or stoi?

c++,string,c++11,gcc
I know it sounds stupid, but I'm using MinGW32 on Windows7, and "to_string was not declared in this scope." It's an actual GCC Bug, and I've followed these instructions and they did not work. So, how can I convert an int to a string in C++11 without using to_string or...

Calling variadic template function with no args failing

c++,c++11
Given the following code: #include <iostream> template <typename... Args> void foo(Args&&... bargs, Args&&... aargs) { std::cout << "Hello" << std::endl; } int main() { foo<int, double>(1, 2.0, 3, 4.0); //OK foo<char>('c', 'd'); // OK foo(); //FAIL } I get the following compiler error: In function 'int main()': 15:9: error: no...

VS2015: Variadic template specialization

c++,templates,c++11,c++14,visual-studio-2015
This code #include <iostream> #include <type_traits> template<typename Head, typename... Tail> struct Is_Admitted { constexpr static bool value = Is_Admitted<Head>::value && Is_Admitted<Tail...>::value; }; template<> template<typename T> struct Is_Admitted<T> : public std::false_type{}; template<> struct Is_Admitted<int> : public std::true_type{}; template<> struct Is_Admitted<double> : public std::true_type{}; int main() { std::cout << Is_Admitted<int,...

Lock Free Bounded Stack C++11 atomics

c++,multithreading,c++11,stack,lock-free
I was thinking about using very basic bounded (preallocated) stack to keep track of my threads ids in correct LIFO order. So i was wondering if my implementation is thread safe: // we use maximum 8 workers size_t idle_ids_stack[8]; // position current write happening at std::atomic_uint_fast8_t idle_pos(0); // this function...

No match for 'operator=' in sort function

c++,c++11,g++,codeblocks
I'm trying to have a program write out all permutations of a string. Here is my code: #include <stdio.h> #include <string> #include <iostream> #include <algorithm> using namespace std; int main () { string input; int length; cin >> input; input = sort(begin(input), end(input)); length = input.length(); do { cout <<...

Access to reference in member variable discards constness

c++,c++11,reference,compiler-errors,const
I made a wrapper around an object in my code that should modify accesses to the object. I choose to use an object here for testing instead of a functor that would have the same functionality. Basically: The wrapper receives a reference to the object and forwards all indexed accesses...

C++ lambda, not seeing function and argument?

c++,multithreading,c++11,lambda,boost-asio
I have some code using a wrapper class around std::thread, which is using a timer struct (based upon boost::asio), to call methodToCallEachIteration() every 5000 milliseconds: class OurThreadWrapperClass{ OurThreadWrapperClass(boost::asio::io_service& = generic_timer_queue_s()); }; class A { A() : thread1(_TimerIOService){ thread1.setInterval(5000); // This sets the callback function, to be called every INTERVAL ms....

Same function with and without template

c++,c++11
I am trying to understand a piece of code of C++11. A class contains 2 functions as shown below: class abc { public: void integerA(int x); template<typename typ> void integerA(typ x); }; I am unable to understand benefit of declaring 2 same functions. Why not declare only one template function?...

Call to implicitly-deleted copy constructor in LLVM(Porting code from windows to mac)

c++,osx,c++11,compiler-errors,llvm
We are in the process of porting some c++ code from windows to mac and are having issues compiling it with LLVM 6.1 using c++11. We are encountering errors all over the place of "Call to implicitly-deleted copy contructor" Some of these errors are popping up in our code. for...

In c++11 what should happen first: raw string expansion or macros?

c++,c++11,preprocessor,rawstring
This code works in visual c++ 2013 but not in gcc/clang: #if 0 R"foo( #else int dostuff () { return 23; } // )foo"; #endif dostuff(); Visual C++ removes the if 0 first. Clang expands the R raw string first (and never defining dostuff). Who is right and why?...

C++11 MinGW 4.9.1 shared_ptr and const static class field result “Undefined reference”

c++,c++11,static,const,mingw32
#include <memory> class CItem { private: int m_inner; public: static const int CAP = 1; CItem(int temp) : m_inner(temp) {} }; typedef std::shared_ptr<CItem> TPItem; int main() { int tttt = CItem::CAP; CItem *temp = new CItem(CItem::CAP); TPItem temp2(temp); TPItem temp3 = std::make_shared<CItem>(tttt); TPItem temp4 = std::make_shared<CItem>(CItem::CAP); //On MinGW there error:...

std::vector::resize(size_type) requires CopyInsertable?

c++,c++11,language-lawyer
This question is made while I answer this another question. N3337 23.3.6.3 "vector capacity" says (it's in 770 page): void resize(size_type sz); Effects: If sz <= size(), equivalent to erase(begin() + sz, end());. If size() < sz, appends sz - size() value-initialized elements to the sequence. Requires: T shall be...

How can I simulate a nested function without lambda expressions in C++11?

c++,function,c++11,lambda,allegro
I have the following code: int main(int argc, char **argv) { App app(800, 600); app.add_event_scene(Scene("Event Plot", event_plot)); Image x("sample.png"); struct foo { static void visual_plot() { x.draw(); } }; // Error. app.add_visual_scene(Scene("Visual Plot", foo::visual_plot)); app.run(); return 0; } And I get the following error: ||=== Build: Debug in Joy-Plus-Plus (compiler:...

Camera calibration and conversion of coordinates(OpenCV)

c++,opencv,c++11,computer-vision
I am trying to map the 2D pixel coordinates in an image to real world 3D coordinates with respect to a fixed webcam. The calibration tutorial on the OpenCV page (http://docs.opencv.org/doc/tutorials/calib3d/camera_calibration/camera_calibration.html) has given me the following xml file: <?xml version="1.0"?> <opencv_storage> <calibration_Time>"Wed Jun 17 12:02:01 2015"</calibration_Time> <nrOfFrames>25</nrOfFrames> <image_Width>640</image_Width> <image_Height>480</image_Height>...

Should checking loop conditions be counted towards total number of comparisons?

c++,algorithm,sorting,c++11
I have implemented three different sorting algorithms and now I want to confirm that my approach of counting the total number of comparisons is correct. In my mind, the number of comparisons shouldn't be tied to the conditional branches because if the condition isn't met, the comparison was still made...

construction of thread using lambda expression

multithreading,c++11,lambda,threadpool
Can somebody explain where a thread is created on the lambda function below? What is the technique used? Can somebody recommend a reference to understand the semantics? I posted the full code now: class ThreadPool { public: ThreadPool(size_t); template<class F, class... Args> auto enqueue(F&& f, Args&&... args) ->std::future<typename std::result_of<F(Args...)>::type>; ~ThreadPool();...

Why does C++ allow a semicolon at the start of a line? [duplicate]

c++,c++11,visual-c++
This question already has an answer here: Why no semicolon gives errors but too many of them don't? 4 answers #include <iostream> using namespace std; int main() { ;;;;int i = 90;;;;; ; ;;;;cout<<"Hello"; return 0; } The above program compiled and ran successfully. From my understanding, the ;...

How can I pass unique_ptr into a function

c++,c++11
How can I pass a unique_ptr into a function? Lets say I have the following class: class A { public: A(int val) { _val = val; } int GetVal() { return _val; } private: int _val; }; The following does not compile: void MyFunc(unique_ptr<A> arg) { cout << arg->GetVal() <<...

Arithmentic operator(+) operator will check both return type and passing arguments or not?

c++,c++11,visual-c++
#include<iostream> using namespace std; class B; class A { private: int a,b; public: A() { a=b=10; } void show() { cout<<"Hello of A: \n a:"<<a<<" b:"<<b; } friend A operator+( A AA ,B BB) ; friend B operator+ ( B BB,A AA); friend B operator+( A AAA ,B BB) ;...

Why is initialization of enum class temporaries with arbitrary values allowed?

c++,c++11
I came across some code like the following in one the CppCon 2014 talks that confused the heck out of me. The audience accepted it without comment, so I presume that it's legal: enum class Foo { Bar }; Foo const v1 = Foo(5); The question is: why does this...

Transforming a two-variable std::function to a single-variable one

c++,c++11,lambda
I have a function which gets two values, x and y, and returns the result: std::function< double( double, double ) > mult = []( double x, double y){ return x*y; }; Now I want to get a single-variable function for a constant y. I have written the following code, but...

Why is the common type of bool and int8_t an int32_t in C++?

c++,c++11,boolean,std
I'm curious about some of the behavior of the builtin bool type in C++. As I understand it, std::common_type determines the common type using implicit convertibility. I would expect that an expression with bool and another type would cause bool to convert to that type. For instance, I can see...

Dereferencing a temporary unique_ptr

c++,c++11,unique-ptr
unique_ptr<A> myFun() { unique_ptr<A> pa(new A()); return pa; } const A& rA = *myFun(); This code compiles but rA contains garbage. Can someone explain to me why is this code invalid? Note: if I assign the return of myFun to a named unique_ptr variable before dereferencing it, it works fine....

C++11 Allocation Requirement on Strings

c++,string,c++11,memory,standards
I had heard that C++11 was going to require strings to be allocated in contiguous memory. I even thought I saw a stack overflow question on it, but I can't seem to find it. I know that in practice both gcc and Visual Studio do allocate strings contiguously, I'm just...

C++ Create shared_ptr from Object

c++,c++11,dictionary,shared-ptr
So on my header file I have this declaration: typedef std::map<const std::string, std::shared_ptr<House> > myHouseMap; myHouseMap _myHouseMap; On my source file I can insert an object in my map like this: _myHouseMap.insert(std::pair<const std::string, std::shared_ptr<House>>("apartment", std::make_shared<House>("apartment"))); But now, I need to return the reference of the object. Therefore, I need to...

why sort function of STL is not working?

c++,c++11,stl
A set of numbers will be passed as input. Also the redefined relationship of the digits 0-9 in ascending order will be passed as input. Based on the redefined relationship, the set of numbers must be listed in ascending order. Sample I/O Input: 20 50 11 121 9231476058 Output: 50...

can't understand variadic templates in c++

c++,templates,c++11,variadic-templates
I was reading about variadic templates and I came across this example. The book mentions that to end the recursion process, the function print() is used. I really can't understand its use. Why does the author use this empty print() function? void print () // can't get why this function...

Win32 Message Pump and std::thread Used to Create OpenGL Context and Render

multithreading,winapi,opengl,c++11
If I have a function that does the following: bool foo::init() { [Code that creates window] std::thread run(std::bind(&foo::run, this)); while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } } Where run is defined as: void foo::run() { [Code that creates initial opengl context] [Code that recreates window based on new...

Is there a flat unsorted map/set implementation?

c++,c++11,boost,stl,containers
There is the boost.container flat_map and others, and the Loki AssocVector and many others like these which keep the elements sorted. Is there a modern (c++11 move-enabled, etc.) implementation of an unsorted vector adapted as a map/set? The idea is to use it for very small maps/sets (less than 20...

What does (&) — ampersand in parentheses — mean in this code?

c++,c++11
In this answer, the following code is given (C++11): template <typename T, size_t N> constexpr size_t size_of(T (&)[N]) { return N; } What does the (&) mean in this context? This sort of thing is exceptionally difficult to search for....

How to parameterize the number of parameters of a constructor?

c++,templates,c++11,constructor
I want to accept up to a number of parameters (this number being defined in a template parameter) in a template class constructor. I can't use an initializer_list, since I can't assert its size at compile time, as far as I know. What I tried My first attempt was using...

Pass a callback function with a parameter to a function

c++,c++11,function-pointers,void-pointers
I want to call the following function and pass it a function with a parameter. The purpose of that is that it should call the function with my specified parameter so I know what triggered the function (in that case a gpio pin on the Raspberry Pi). int wiringPiISR( int...

Why do the const accessors of std::string return a reference?

c++,c++11,stl,language-design,stdstring
The std::string accessors (back, front, at, and operator[]) have const and non-const overloads, as below: char& x(); const char& x() const; Why does the second version return a const reference, as opposed to simply returning the char by value (as a copy)? According to the rules of thumb on how...

Releasing memory with std::move()?

c++,c++11,move-semantics
Says I have a class with a standard container: class Library{ std::vector<Book> books; public: void putOnFire(){ books.clear(); } }; The usual way to clear a container is "clear", however most code is not "STL compliant" so many containers (by third parties) may not have a "clear" method. however, If they...

I think assigning JsonValue values to JsonValues might be very slow, in comparison to having a Value be a key

c++,json,c++11
Json::Value is located in: #include <json/value.h> I have a result Json::Value object being created which will be pushed back to the user. The issue with it is that it takes a super long time to complete, which boggles my mind. I think that there is something off with Json::Value, maybe...

C++ operator []

c++,c++11,operator-overloading
I am trying to implement the operator [] that is to be used once for Set and once as Get, i need to differentiate between the two cases, as in the case of get, i need to throw an exception if the returned value is equal to -1; whereas in...

C++ error: deduced conflicting types for parameter 'T' string vs const char *

c++,string,templates,c++11,char
So, I am writing a simple, templated search function for deque container. Here's the code: template <typename T> void searchInDequeFor(std::deque<T> Deque, T searchValue) { for(const auto & element : Deque) { if(Deque.empty()) { std::cout << "Deque is empty, nothing to search for..." << "\n"; } else if(element==searchValue) { std::cout <<...

No match for 'operator*' error

c++,c++11
Hello fellow programmers! I was going to write a small program for calculating total pay for different periods of time depending on the amount of hours and the salary that the user enters. I managed to make a small bit of the program but when I try to run it...

namespace and extern 'C' compilation errors

c,c++11
I have tried to google the errors but to no avail. Maybe I am searching in the wrong direction. I am trying to compile a file but when i tired to compiled it, the compiler gave me these errors: C2059 syntax error: ';' C2059 syntax error: '}' C2061 syntax error:...

undirected weighted graph data structure in c++

c++,class,c++11,data-structures,graph
I am learning C++ and I appreciate your support by answering my question to help me to understand fundamental concepts. I am sure I need to learn many stuff, but I need a some advice to help me to find the right way. The problem I have is explained in...

std::push_heap and std::pop_heap with MoveConstructible objects

c++,c++11,stl,heap,move-semantics
I want to maintain a heap where the payloads are MoveConstructible (because they hold a std::unique_ptr inside.) Although the documentation suggests that the object must be MoveAssignable and MoveConstructible, doing so throws an error both in GCC and Clang. Sample Code I don't use an std::unique_ptr yet, but just disable...

Using the assert macro while global variables are initialized

c++,c++11,assert,assertion
In the following code, the first assert does not compile because, in MSVC2015RC at least, it is defined essentially as assert(expression) (void)(!!(expression)). int x = 1; assert( x == 1 ); void foo() { assert( x == 1 ); } The error message is C2062 type 'void' unexpected The second...

Error using range-based for loop - Eclipse CDT Luna

templates,c++11,for-loop,mingw,eclipse-luna
I am a beginner at C++ programming. I tried to write a very simple program that combines the use of templates, passing arrays as arguments to a function and a range-based for loop. This is the program that I wrote and compiled using the Eclipse Luna CDT software. #include <iostream>...

Setting the content of a std::stringstream with str(const char*) has strange consequences

c++,c++11,stringstream
I use std::stringstream extensively to generate code. I have run into some querious behavior when setting the content with the str() function followed by using the operator<<. Can someone explain this behavior to me. I would very much appreciate it - Thanks. Example One: std::stringstream ssa; ssa.str("Setting string"); std::cout <<...

How to check a value like “#define VERSION 3.1.4” at compile time?

c++,c++11,preprocessor
I am adding compile-time checks to my company's C++ projects to make sure the third-party libraries on all development machines and build servers are up-to-date. Most libraries define something like the following for e.g. version 3.1.4: #define VERSION_MAJOR 3 #define VERSION_MINOR 1 #define VERSION_BUILD 4 This is nice and easy...

How to re-write templated function to handle type deduction

c++,templates,c++11
So, I have this search function for the map container: template <typename Key, typename T> void searchInMapByKey(std::map<Key,T> Map, T keyValue) { if(Map.empty()) { std::cout << "Map is empty, nothing to search for..." << "\n"; } else { for(const auto & element : Map) { if(element.first==keyValue) { std::cout << keyValue <<...

Error with stoi and debugged with gdb [closed]

c++,c++11,segmentation-fault,coredump
My OS is ubuntu 14.04, laptop, i7. The g++ version is g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2. I tried to run a simple code to test stoi: #include <string> int main() { std::string s = "123"; int i = std::stoi(s); } When I compile it with: g++ -g prueba2.cpp, I get: prueba2.cpp:...

c++ internal helper class

c++,c++11
I would like to ask question regarding internal helper class in C++. What is the best way to structure this? Let me clarify what do I mean by internal helper class by example. // MyClass.h class MyClass { int myData; bool isSomething; ... public: void DoSomething(); }; // MyClass.cpp //...

std::move on a C++ class does not move all members?

c++,c++11,move
I understand that using v.push_back(std::move(foo)) will move foo contents to a vector. However I do not understand why the below code : #include <iostream> #include <vector> struct Foo { std::string s; float f; friend std::ostream& operator<<(std::ostream& stream,const Foo& foo) { stream << "{" << foo.s << ":" << foo.f <<...

Sorting vector of Pointers of Custom Class

c++,sorting,c++11,vector
I have vector<FPGA*> current_generation_, which I'd like to sort by FPGA member fitness_ using the sort_members function. Applicable code follows: bool sort_members (FPGA* fpga_first, FPGA* fpga_second) { return (fpga_first->fitness() < fpga_second->fitness()); }; fpga.hpp #include <vector> class FPGA { public: explicit FPGA(int input_gates, int output_gates, int normal_gates); const int fitness(); protected:...

Type function that returns a tuple of chosen types

c++,templates,c++11,metaprogramming
I've implemented a type function Tuple that turn a list of My_enum values into an std::tuple of corresponding types: #include <tuple> enum My_enum{ t_int, t_double }; // Bind_type is a type function that given a My_enum returns the corresponding type template<My_enum E> struct Bind_type; template<> struct Bind_type<t_int>{ using type =...

Can't compile C++11 source using GCC 5.1 toolchain

c++,c++11,gcc5
I'm trying to compile a library written with C++11 features using GCC 5.1 on Ubuntu. However, it complains std::unique_ptr is not defined. gcc (Ubuntu 5.1.0-0ubuntu11~14.04.1) 5.1.0 g++ (Ubuntu 5.1.0-0ubuntu11~14.04.1) 5.1.0 CXX flags: -std=c++11 -Wall -Wextra -Weffc++ -pedantic Output: error: ‘unique_ptr’ in namespace ‘std’ does not name a template type std::unique_ptr<...

Simple thread/mutex test application is crashing

c++,multithreading,c++11,mutex,mingw-w64
I wrote a simple test program which accumulates random samples to a buffer using multiple threads. Each thread uses a stack for reducing the mutex waits. This is for investigating problems in a much larger program. The code currently crashes on mingw-w64 4.9.2 Any idea why? Debugging halts on "signal-received"...

Can you put a pimpl-Class inside a vector

c++,class,c++11,smart-pointers
I have a class implemented using the PImpl Ideom: class FooImpl {}; class Foo { unique_ptr<FooImpl> myImpl; public: Foo(); ~Foo(); }; And now I want to put this into a std::vector void Bar() { vector<Foo> testVec; testVec.resize(10); } But when I do that, I get a compiler error (VC++ 2013)...

Pointer not working anymore after second iteration

c++,c++11
I'm doing regular challenges at reddits dailyprogrammer to learn and practice C++. With last week challenge I got stuck on something with pointers. The challenge is/was to create a todo-list with categories. I already had the todo-list part implemented in the previous challenge and I workend on from there. This...

Syntax help. Template operator() in template function object

c++,templates,c++11,functor
What is the proper syntax I need to run what I'm trying to run in main() below? #include <iostream> #include <vector> template <int... Is> void foo() { std::vector<int> v{Is...}; for (int x : v) std::cout << x << ' '; } template <int... Is> struct Foo { template <typename T,...

Reordering vector of vectors based on input vector

c++,c++11,vector,stl,idioms
In a small application, I've been using a std::vector of std::vector<std::string> to temporarily store some data (pulled from a non-SQL database) before processing it and uploading it to a SQL database. Unfortunately, the API from which I am extracting the data does not necessarily return fields in the order specified...

Alias the return type of a const overloaded function

c++,c++11,const,decltype
I have the following overloaded function : template<size_t N, typename T> auto get(const T & _t) -> decltype(std::get<...>(_t)) { ... } template<size_t N, typename T> auto get(T & _t) -> decltype(std::get<...>(_t)) { ... } First question is : does the first one uses std::get(const tuple<_Elements...>& __t) and the second one...

Mapping const char * to duck-typed T at compile-time or run-time

c++,templates,c++11
I have many classes A, B, C, D, etc that are duck-typed and thus have the same methods and interface but do not inherit from the same class. E.g. class A { public: void foo(); void bar(); } class B { public: void foo(); void bar(); } class C {...

Finding all keys that correspond to same value in std::unordered_map

c++,c++11,stl,c++14
I have an unordered_map looking like this: std::unordered_map<int, std::string> theMap2 = {{1,"a"}, {2,"b"}, {3,"c"}, {4,"a"}}; I want to find all the keys that have same value lets say 1. Any suggestions beside the obvious way: std::vector<int> arrKeys; std::string value = "a"; for (const auto& element : theMap) if (element.secont ==...

Output MySql table to Console Output [on hold]

c++,mysql,sql,c++11
Is there a way to display a MySql table to the standard console with only its name and without creating a new file? I already have the path, I just don't know how to display this table. It's referred to as SQL_TABLE_NAME in my code. Thanks in advance.

Call template function for the value of a pointer out of a template function, in C++

c++,templates,pointers,c++11
I am trying to call a template function for the pointer that was given as template parameter in my calling function. My code is: template <> struct serialize_helper<std::string> { // not important code... } }; template <class T> inline void serializer(const T& obj, StreamType::iterator& res) { if(std::is_pointer<T>::value) { //THIS doesn'...

Configuring Flycheck to work with C++11

c++,c++11,emacs,flycheck
I am having significant trouble configuring flycheck for C++11. Right now, flycheck is flagging things like std::to_string(). The checker I am using is just g++. What can I add in the .emacs file such that flycheck will assume C++11 by default?

Issue using std::atomic_flag with worker thread

c++,multithreading,c++11,stdatomic
sorry for the verbosity - I did my best to condense my code sample into a minimally functional class and main() method. I'm trying to use an atomic_flag to notify _rx() within my worker thread to quit when stop() is called. I believe the issue is in trying to create...

Confusion regarding types, overflows and UB in pointer-integral addition

c++,pointers,c++11
I used to think that adding an integral type to a pointer (provided that the the pointer points to an array of a certain size etc. etc.) is always well defined, regardless of the integral type. The C++11 standard says ([expr.add]): When an expression that has integral type is added...

C++ Opengl - How to load tgas and pngs in modern OpenGL? [on hold]

image,opengl,c++11,png,tga
I am looking for a way to load tgas and pngs in C++ Opengl - I dislike the idea of using a library though. Is there any sample code / links / advice you could give me in this topic?...

Is there a syntax for incomplete nested type without a forward declaration?

c++,c++11,nested,forward-declaration
The following program produces a diagnostic error. #include <memory> class Containing { // class Nested; // [1]: This line seems required. typedef std::shared_ptr<class Nested> Ptr; class Nested { Ptr & ptr (); void foo (const Ptr &p) { p->ptr() = ptr()->ptr(); // [2]: Error here without [1] } }; };...