question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
62,304,836
62,305,077
mistake with allocators in c++
namespace Test { template <typename DataType, typename Allocator = std::allocator<DataType>> class List { private: struct Node { Node* next; DataType Data; Node(DataType Data,Node* next = nullptr); }; typename Allocator::template rebi...
Try changing typename Allocator::template rebind<Node*>::other allocator; to typename Allocator::template rebind<Node>::other allocator; The pointer is implicit. Also you should use std::allocator_traits together with an allocator instead of using the typedefs and functions of an allocator directly.
62,304,843
62,423,973
Type of member variables in a const member function
When I have a member function marked as const and inspect the types of the member variables I get some results I don't expect. #include <iostream> #include <string> template<typename T> struct type_printer; class const_type_test { public: void test() const { type_printer<decltype(value)> _; } int&...
decltype has special rule for class members. It returns the actual type of the member. If you want decltype to consider the context (inside a const function), then you can wrap the expression inside parentheses. Without Paranthesis: void test() const { type_printer<decltype(value)> _; } c.cpp:10:39: error...
62,305,053
62,305,693
How to set a huge head allocate array as specific float number C++
At first, I allocate a huge block memory by using Intel Math Kernel Library API. After that I want to set this array as specific value, for example 1234.5678. I plan to use the void* memset( void* dest, int ch, std::size_t count ); function, but it seems that this function can only set int value. I can use the simple f...
You can use std::fill_n to assign a value to each value of your array #include <algorithm> std::fill_n(data, count, 1234.5678); Note that many compilers will generate the same code even if you use a raw for loop for (std::size_t i = 0; i < count; ++i) { data[i] = 1234.5678; } See this Compiler Explorer example, ...
62,305,390
62,306,280
Explicitly-specified template parameter packs
Let's say, I have the following piece of code: #include <iostream> template <size_t... Is> struct E {}; template <typename... Ts, size_t... Is> void func (E<Is...>, Ts...) {std::cout << __PRETTY_FUNCTION__ << std::endl;} int main() { func(E<1,2,3>{}, 1, 'a'); } It works perfectly fine and produces void func(E<...
This follows from the rules for template argument deduction. When you explicitly specify the template parameters for func, the compiler will match it to the first parameter pack greedily. The compiler does not figure out that once you start putting ints in the parameters, it should start substituting for Is.... Instea...
62,305,516
62,305,815
C++17 fold syntax to test vector composition
Standard C++17 implementation of vector any, all: template<class C, class T> bool contains(const C& c, const T& value) { return std::find(c.begin(), c.end(), value) != c.end(); } template<class C, class... T> bool any(const C& c, T&&... value) { return (... || contains(c, value)); } template<class C, class... T> ...
template<class C, class...Ts> bool only( C const& c, Ts&&...ts ) { std::size_t count = (std::size_t(0) + ... + contains(c, ts)); return count == c.size(); } this counts how many of the list ts... are in c, and returns true if the number you found ear equal to the elements of c. Now this assumes uniqueness of c an...
62,305,731
62,312,853
ID2D1Bitmap to Wic with Alpha but not PNG
I 'm saving the bitmap of a Direct2D Device Context. My goal is to keep 32-bit (RGB with alpha) but not have a PNG, I 'd rather have a 32-bit bitmap. I'm using this function: HRESULT SaveBitmapToStream( _In_ CComPtr<ID2D1Bitmap1> d2dBitmap, _In_ CComPtr<IWICImagingFactory2> wicFactory2, _In_ CComPtr<ID2D1De...
The native BMP codec supports one property, EnableV5Header32bppBGRA of type VT_BOOL: Specifies whether to allow encoding data in the GUID_WICPixelFormat32bppBGRA pixel format. If this option is set to VARIANT_TRUE, the BMP will be written out with a BITMAPV5HEADER header. The default value is VARIANT_FALSE. Note...
62,305,816
62,306,079
Is locking a mutex for a long time safe?
There is a set of problems in which mutexes themselves (without additional stuff like condition variables) can be used to synchronize threads. For example, let's say I want a background thread to perform some possibly-time-consuming initialization and then to perform its main job, but the main job should start not earl...
There's no specific downsides to locking a mutex for a long time. If I understood correctly, you have a thread that will lock a mutex during its init. Another thread will try to get that mutex (to be sure the init of the other thread is finished) and then get the mutex for the rest of the program runtime. That is fine...
62,305,974
62,417,347
generic way to evaluate a function cost at compile time
I am currently working on the implementation of a multidimensional array iterator. Considering the iteration over two contiguous ranges (for std::equal, std::copy purposes) that represent compatible data with different alignements (row vs col major in 2D), I would like to find the stride order for each iterator giving ...
No. Your question is based on bad assumptions. Some of the bad assumptions (there might be others): The function is used as it is: The compiler might inline it in many places or decide you are better-off having it in a separate function because the code size improves. Since you can get slightly different behavior by t...
62,306,358
62,306,990
How to start async threads on C++
I want to have different OpenCV functions running with std::async() As an example, I'm trying to acquire and display images using my webcam. I did a class called camHandler to encapsulate this. This example is made asynchronous on purpose, I know I could just display the image after acquiring it :) I first use the o...
If you try to call cv::imshow with an empty cv::Mat, it will throw an exception, and async will end. Since it's running in async, cv::imshow("Live", this->frame) can be called before cap.read(this->frame). You should check cv::Mat is not empty before displaying.
62,306,496
62,307,033
Last Digit of the Sum of Fibonacci Numbers in range a to b
my solution is failing the test case 1234 12345 in the output and it is giving output 2 instead of correct output 8 although some of the test cases in the question sample have passed . please point out my mistake. thank you. #include <bits/stdc++.h> using namespace std; int calc_fib(long long n) { long long int ...
If you are doing calc_fib(b) anyway, you can just collect the result in a separate variable when i reaches a and on wards. This way, you can avoid calc_fib(a-1); If this is for a single range of a to b, you can compute on the fly, else precompute them by caching them in an array and just do calc_fib(b) - calc_fib(a-1)....
62,307,357
62,308,756
How do I access variables output of a scope in C++?
For example, class GetDepth_Class { public: vector<int> positionX, positionY; vector<int>::iterator it; int getDepth(); }; int GetDepth_Class::getDepth(){ ...... ...... if (scalar[0] == 0 && scalar[1] == 0 && scalar[2] == 0) { ...
You can use a struct for returning multiple values too: #include <iostream> #include <vector> using namespace std; // using a struct for returning multiple variables struct Decl { vector<int> posX; vector<int> posY; }; class GetDepth_Class { // these are private members now vector<int> positionX, pos...
62,307,522
62,307,593
Filling std::vector with objects created elsewhere
I'm trying to fill a std::vector with objects created in a function like so: class Foo { public: Foo() { std::cout << "Foo created!\n"; } Foo(const Foo& other) { std::cout << "Foo copied!\n"; } Foo(Foo&& other) { std::cout << "Foo moved\n"; } ~Foo() { std::cout << "Foo destroyed\n"; } }; static Foo createF...
How can Foo be destroyed more times than it is created? The output shows exactly as many creations, as it shows destructions: change -> cumulative total Foo created! +1 -> 1 Foo moved +1 -> 2 Foo destroyed -1 -> 1 Foo created! +1 -> 2 Foo moved +1 -> 3 Foo destroyed -1 -> 2 reach...
62,307,634
62,308,211
Passing std::promise object to a function via direct function call
I am learning the std::promise and std::future in C++. I wrote one simple program to calculate the multiplication of two numbers. void product(std::promise<int> intPromise, int a, int b) { intPromise.set_value(a * b); } int main() { int a = 20; int b = 10; std::promise<int> prodPromise; std::future...
When you compile this code, even if don't use std::thread explicitly, you still have to add -pthread command line option, because internally std::promise and std::future depend on the pthread library. Without -pthread on my machine I get: terminate called after throwing an instance of 'std::system_error' what(): Unk...
62,307,745
62,324,026
CORBA exception raised: NotFound
Hello I'm trying to implement simple client/server CORBA app with docker. Here is Print.idl code : module Test { interface Printer { void print(); }; }; Here is the client code: #include <iostream> #include "PrintC.h" int main(int argc, char** argv) { try { CORBA::ORB_var orb = CORBA::ORB_init(...
Thanks to Wireshark, I have obtained more info about the error. wireshark Thus it seems to replace : name = naming_context->to_name("test/Printer") by name = naming_context->to_name("Printer") works. (Same thing for the client code)
62,307,844
62,311,757
no matching function for call to 'distance (int&,int&)'
I wrote the following code in Rcpp(sorry if it is abit sloppy. It is my first experience in Rcpp) : #include <RcppArmadillo.h> // [[Rcpp::depends(RcppArmadillo)]] using namespace Rcpp; using namespace arma; // [[Rcpp::export]] Rcpp::NumericMatrix rr (Rcpp::NumericMatrix edge,Rcpp::NumericMatrix riskset, Rcpp::Nume...
Changing Rcpp::NumericVector recencySend (nedge, 0); Rcpp::NumericVector recencyReceiv (nedge, 0); Rcpp::NumericVector recencyContinue (nedge, 0); to Rcpp::NumericVector recencySend (nedge, 0.0); Rcpp::NumericVector recencyReceiv (nedge, 0.0); Rcpp::NumericVector recencyContinue (nedge, 0.0); will resolve your error ...
62,308,247
62,308,694
How can I create a vector of derived objects?
I've read several posts on this website, but I still can't figure out what's the right way to create a std::vector of objects from different derived classes. I've created a class Column: template <typename T> class Column { public: Column(); virtual ~Column(); vector<T>& getData(); string getName(); ...
First of all, you're missing a base class. Column is a template, not a class, and having virtual methods inside a template is rarely useful. class Column { public: Column(); virtual ~Column() {} std::string getName() const { return _name; } virtual std::string getType(); protected: std::string _nam...
62,308,486
62,456,435
How to avoid qWarning of float values
I have these following code to set a variable: void TypeLogVisualization::setGain(double gain) { qWarning("Floating point comparison needs context sanity check"); if (qFuzzyCompare(m_gain, gain) || gain < 1.0 || gain > 2.1) return; m_gain = gain; setPath(); emit gainChanged(m_gain); } The variable gain is set in ...
Like everyone said, the only way it's remove that lines
62,308,664
62,321,743
Why does GCC's threading standard library implementation throw exceptions if you don't include pthread?
When I write code that uses, for example, std::promise, and I don't include the PThread library in GCC, I get an exception thrown rather than a linker error. For example: void product(std::promise<int> intPromise, int a, int b) { intPromise.set_value(a * b); } int main() { int a = 20; int b = 10; std::p...
The reason for this is that libstdc++ uses the so called weak references. We can easily trace why your particular code example throws an exception. set_value() calls std::call_once. That function in its implementation has the line*: int e = gthread_once(&once.M_once, &once_proxy); where gthread_once is: static inline...
62,308,918
62,309,050
How to initialize an object of a class using curly brackets {}
I'm looking to make this code compiled with no error (and without using std::initializer_list) Here's the code : template<typename T> class Vector { public: T* Arr; int Size = 0; int Capacity = 1; Vector(); }; template<typename T> Vector<T>::Vector() { Arr=new T[1]; } int main() { Vector<int>V1...
How to initialize an object of a class using curly brackets {} Vector<int>V1 = { 1,2,3,4,5 }; Option 1: Use std::initializer_list. (and without using std::initializer_list) Well, then use one of the other options: Option 2: Make the class an aggregate. You initialise the members of the class with {x, y, z}. This a...
62,309,283
62,309,525
C++: How to find a and b from k = 2^a * b?
Given following in C++: $$k = 2^a \cdot b,$$ only knowing the value of k and that b is odd. How do you find the value for a and the value for b? I did consider the following: if k is odd, a has to be zero and b is k if k is even, I would go through all possible b's with a for-loop and check if k % b == 0. If that is t...
You might do the following: int a = 0; while (k % 2 == 0) { ++a; k /= 2; } int b = k; // you have a, b idest, divide by 2 the number 2**a*b until it is no longer even, so you found b.
62,309,487
62,310,838
Pybind11: init<> with lambda
I use pybind11 as a wrapper of my C++ code into a python library. It happens that there are arguments that I can't provide or sometimes I want to do a conversion/initialization that I know in the C++ side. It could be because the class is not known in python, for instance. How could that be done? The only "solution" I ...
pybind11 lets you bind factory functions as init methods. So you would have to provide a function in c++ that took a B and return an A and then you could bind that as an init method for A. An example from the pybind11 docs class Example { private: Example(int); // private constructor public: // Factory function...
62,309,621
62,523,557
cosimulation using VIVADO HLS
Xilinx System generator can be used for a cosimulation between the original MATLAB reference model and the actual HW board. Can we follow a similar procedure for a cosimulation between the original C++ reference model (before datatype and algorithm optimization for HDL) and the actual HW board in VIVADO HLS?
Yes, we can! If you already have a C++ reference model you can compare its results with the host and device side code accelerated on FPGA. I use host/device terminology as in OpenCL which is what Vitis currently uses for C++ FPGA kernels. Typically all buffer handling across PCIe to/from FPGA is done by the host side c...
62,310,149
62,310,206
I need help in entering two string in a class and getting its output
When I am trying to enter the two string name str1and str2 in program it is giving me error cpp|19|error: cannot convert 'std::__cxx11::string' {aka 'std::__cxx11::basic_string<char>'} to 'int' in return| |26|error: cannot convert 'std::__cxx11::string' {aka 'std::__cxx11::basic_string<char>'} to 'int' in return| #i...
That's because return type of getter functions is int instead of string: string get_first_name() { return str1; } string get_last_name() { return str2; } Update: Answering to question from comments. class Student { string str1,str2; int age, st; public: void set_first...
62,310,556
62,310,687
Pushback elements of other arrays
I created two arrays A and B, the array C should store the first elements of A and B. Ex : A={1,2,3}, B={4,5,6}, C must be {1,4,2,5,3,6}. My program doesn't show anything after the input of my arrays. This is my loop : for(int i(0);i<3;i++){ C.push_back(A[i]); C.push_back(B[i]); } for(int i(0);i<6;i+...
Try this: int main() { std::vector<int> A = {1,2,3}; std::vector<int> B = {4,5,6}; std::vector<int> C; for (int i(0); i < 3; i++) { C.push_back(A[i]); C.push_back(B[i]); } for (int i(0); i < 6; i++) { std::cout << C[i] << " "; } return 0; } Or you can c...
62,310,946
62,310,995
Why aren't all the string characters being accessed?
The purpose of my program is to remove all the vowels in a string. std::string disemvowel(std::string str) { for (unsigned int i = 0; i < str.length(); ++i) { switch(str[i]) { case 'A': case 'a': case 'E': case 'e': case 'I': case 'i': case 'O'...
Every time you erase a character, str changes, and then when you increment i, you are skipping the next letter. Generally, don't remove things from a sequence as you are iterating it, but if you are iterating with an index, then a good trick is to go backwards if you can. You are changing everything after i, but you do...
62,311,094
62,311,246
Size of derived class in virtual base class function
Consider the following code class A { int x, y; public: A(){} virtual void PrintSize(){ cout << sizeof(typeof(*this)) << endl; } }; class B : public A { int a, b, c; public: B(){} }; int main() { A obja; B objb; obja.PrintSize(); objb.PrintSize(); } The intent of "PrintSize()" is...
You can use the CRTP idiom to do this. https://eli.thegreenplace.net/2011/05/17/the-curiously-recurring-template-pattern-in-c The idea is the parent class is a template, so you can have access to the type of the child class directly in it. With that, you'll be able to remove all "PrintSize" from child class. Example :...
62,311,211
62,315,239
Postponing the call of a destructor
Suppose, the program gets two arguments, one of them is storage_duration_name and the other is count. We have a class called anywhere which has a default constructor and destructor. The program must create exactly <count> (not more, not less) objects of type anywhere, one after another, starting from index argument val...
If I understand the question correctly, strictly speaking it is not possible to allocate an arbitrary number of objects of automatic storage class. Automatic variables are named objects, therefore one would need an arbitrary number of names, one for each variable. Furthermore, though the the C++ standard does not stric...
62,311,279
62,311,392
How is `auto *x = new some_struct{};` an uninitialized variable?
Recently, I decided to try out CodeInspector. In my code, I've written the following: auto *v4Addr = new sockaddr_in{}; Code Inspector has flagged this line (as well as a few other similar lines) as Violation | Critical/security | Uninitialized variable: v4Addr It is my understanding that new some_struct{} initialize...
It isn't. CodeInspector is wrong. You should report a bug to its authors.
62,311,663
62,311,676
G++ compiler: cant write to file
So one day I made a small program to test out for a much bigger one that I was making on Visual Studio 2019 and here's what it looked like: #include <iostream> #include <fstream> using namespace std; int main() { string path; cout << "Enter path and filename: "; cin >> path; ofstream writer(); writ...
ofstream writer(); This is wrong. You accidentally declared a function. Remove the (). (You must have been running different code under Visual Studio.)
62,311,746
62,316,280
is there any way to index the hana adapted struct by its member name?
I have a hana defined struct, I knew I can iterate through it, but I wonder how can I index it by member name? #include <string> #include <boost/hana.hpp> int main() { struct Person { BOOST_HANA_DEFINE_STRUCT(Person, (std::string, name), (int, age) ); }; Person john{"...
Turns out there is at_key. we can use hana::at_key(obj, key)
62,312,140
62,312,160
Implemented `operator<` still gives error - no match for 'operator <' (opereate types are const StorageFile' and 'const StorageFile')
I have a custom struct named StorageFile which contains some information about a file do be stored in a database. class StorageFile : public QObject { Q_OBJECT public: int ID = -1; QString filename; QString relativeLocation; MediaType type; QDateTime dateLastChanged; quint64 size; ...
Your operator< is incorrect. To allow < to work when the left hand side operand is a const object, you need to const-qualify the member operator< as well: bool operator< (const StorageFile& storageFile) const; // ^^^^^ Note that a map would usually require that const keys c...
62,312,488
62,312,622
How do you properly send an array from ROS in C++?
I'm using Kinetic. I have a custom message path.msg string path_name segment[] segments I'm trying to send a ROS goal with that message type. I initialize an array in my code cuarl_rover_planner::segment segments[path->getSegments().size()]; //do stuff that populates the array cuarl_rover_planner::path action_path; a...
action_path.segments is a std::vector<segment>, but your segments variable is just a single segment, not a vector of segments. If you want to add only one segment, you can use action_path.push_back(segment). Otherwise, you can declare segments as std::vector<cuarl_rover_planner::segment> segments(path->getSegments().si...
62,312,558
62,313,430
How to create a makefile to find and run C++ header file and class file in sublime text 3?
Hey I am new to programming and especially new at C++. I am trying to create a makefile that will allow the compiler to compile a C++ program with separate class files in sublime text 3. Below is the current makefile I am using, however it isn't recognizing the header and class files of the C++ program. { "cmd": ["g++....
That is not a makefile. It however looks like it may be a script to generate one given the parameters. I strongly suggest if you are new to c++ that you should write your own makefile from scratch. below is an example makefile I grabbed from https://www.gnu.org/software/make/manual/html_node/Simple-Makefile.html Remem...
62,312,593
62,315,615
CodeLite doesn't run C++ program in certain workspaces
I am using CodeLite as an IDE for C++ in order to do some of the exercises for a book I am trying to read. As of now, I have generated a workspace, and have multiple projects (each one corresponding to one exercise). CodeLite was working ok until, for one of the projects, I began copying over some helper functions (the...
I mean first look (using your OS file browser) if the executable exists. Thanks for this comment, I think this may be the root of the issue. CodeLite does make a folder where it would place the executable (folder is called Debug for me), but it does not make an executable. I think this is entirely my fault, as I name...
62,312,772
62,320,360
Why am I getting a linker error: undefined reference to ...?
Why am I getting this error: undefined reference to `bfopen(char const*, int)'? I have a shared library that I created that includes a function definition for the function bfopen among others. The name of this library is libfiles.so and it is in a local ext/lib directory to where I am building from. and I am compiling ...
One possible problem is, that you have ext/sample/src/test.c a C-file, which will compiled as C-code. But your application which uses your library is C++ code g++ -std=c++11 -fPIC -g -Wall -D_DEBUG -I./src -I$(PWD)/ext/include -o test_tst test_tst.cc -L$(PWD)/ext/lib -ltest and includes a header, which is in this case...
62,312,904
62,313,156
Adding line to shader makes nothing draw
I have this vertex shader. When i remove in vec3 LVertexNorm and everything related to it. It render fine. But if i add it in, nothing renders anymore. #version 140 in vec3 LVertexNorm; in vec3 LVertexPos2D; uniform mat4 MVP; out vec3 norm; void main() { norm = LVertexNorm; gl_Position = MVP * vec4( LV...
The argument to glEnableVertexAttribArray has to be the vertex attribute index: GLuint pos_inx = program->getAttribute("LVertexPos2D") glVertexAttribPointer(pos_inx, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), NULL); glEnableVertexAttribArray(pos_inx); GLuint norm_inx = program->getAttribute("LVertexNorm"); glVertexAt...
62,312,973
62,313,100
How to initialize unique_ptr from raw C heap memory pointer?
I am using a function (which is part of a library) which returns a raw uint8_t* pointer to some memory which has been allocated on the heap and holds image pixel data. The caller of this function is responsible for calling free on the pointer. My code where I call this function has many branches with early termination...
This is pretty simple to do! The template for std::unique_ptr looks like this: template<class T, class Deleter> class unique_ptr; And the Deleter is used to clean up the value pointed to by the unique_ptr when it falls out of scope. We can write one to use free really simply! struct DeleteByFree { void operator()(...
62,313,136
62,313,767
how to include the draco_dec library?
I want to include the draco library for my c++ project and I built draco with cmake on ubuntu. When i try to add any draco header i see "include errors". I've tried to compile header file and this command worked for some drace headers but didnt find many on them. g++ -I "\\wsl$\Ubuntu\home\antmedia\draco\src\draco" Obj...
For convenience, install the downloaded library in a directory where you keep all the libraries you download and compile yourself. Start by creating such a directory. Example: mkdir ~/local You then need to configure the Draco project to be installed in that location before building. Inside the draco/build_dir direct...
62,313,143
62,313,306
return std::move(m_field) or return m_field?
I have read in some others posts that move is unnecessary and even deoptimizes mechanisms like NRVO. But it was in most cases about a local field. Consider this example: A class stores a temporary field after a computation. I want to take this field without copying it ("consuming" it). In this case, is it appropriate...
If you were to return an object with automatic storage, then you should never return with std::move because former is faster in best case, and equal in worst case. I have read in some others posts that it's unecessarily and even deoptimize mecanisms like NRVO. And this is the reason. This doesn't however apply to th...
62,313,187
62,313,632
Call template provided (static) function
I am trying to create a C++ wrapper for a freertos Task. The challenge here is that freertos needs to take a c function pointer as described here https://www.freertos.org/xTaskCreateStatic.html Now I came up with this template<typename Functor_T, uint32_t u32StackSize> class CFreeRTOS_Task { public: ///Constructor ...
The way you have your class template written, Functor_T is a type not a value. There are a couple of places you've gotten tripped up by that: static CFreeRTOS_Task<TestTaskFunc,10> testTask("test_task"); Here, you're trying to pass a value where CFreeRTOS_Task is expecting a type. template<typename Functor_T, uint32_...
62,313,504
62,313,644
What is the correct usage of "std::reduce"
The following code compiles on MSVC but it fails on GCC. It seems GCC requires the type of the dereferenced iterator and init to be the same, even though there is no such requirement according to this reference. Note that if I replace std::reduce() with std::accumulate() then it works. std::random_device e; std::unifor...
From [reduce]/5 Mandates: All of binary_­op(init, *first), binary_­op(*first, init), binary_­op(init, init), and binary_­op(*first, *first) are convertible to T. You lambda can't work for binary_­op(*first, *first) so gcc is correct in rejecting it.
62,313,581
62,313,645
How to add characters to strings in C++?
I am writing an IP calculator program to convert an IP adress into the broadcast adress, network adress etc. I need to convert the adress into 8-digit biniary first, I already used itoa for it decimal to biniary conversion, but I still need to make it always 8 digit. I want to use a switch to do it. First the program ...
Single quotation marks are for single characters, double quotation marks are for strings, i.e. more than one character, so you need "00". There is no std::string constructor for the parameters you provide, among other methods, you can use: string e1; e1.append("00").append(e); Or string e1 = "00"; e1 += e; Aditional...
62,313,780
62,414,791
Gnuplot not updating correctly even after reread
I am trying to plot two 3D objects that translate and rotate in gnuplot via gnuplot-iostream. In my .cpp file, I have a for-loop that goes for a 100 iterations. For each iteration the .dat files I wish to plot changes, so I'm expecting my plot to move. I have set my gnuplot to persist so the plotting should "animate" ...
So in order for me to plot my two figures' rotations and translations on the same window I had to completely change my approach. It turns out I didn't even need to use the whole Gnuplot gp(gnuplot -persist), nor did I need refresh, replot, reread, clear and etc. I used send1d to input my data instead of writing consta...
62,313,882
62,315,108
C-style cast of enum class to reference of underlying type char
Is this legal C++ (>=14), resulting in a char being read and saved into aCode? enum class ECode : char { Code1 = 'a' }; std::istream& operator>>(std::istream& aIn, ECode& aCode) { return aIn >> (std::underlying_type_t<ECode>&)aCode; } I would prefer return aIn >> static_cast<std::underlying_type_t<ECode>&>(aCode) wh...
As has been noted in comments, there is no strict aliasing violation because char can alias any type. In practice I doubt any real compiler would do anything other than the "obvious" implementation, i.e. give the enum the same size and representation as the underlying type. In which case your reinterpret_cast would be ...
62,314,317
62,316,050
Error message with operator syntax, but not with function syntax
Why am I getting an error message when calling unary + with operator syntax? If I call it with function syntax, it is OK. Live demo. template <int size> struct Buffer { char buf[size]; }; template <class T> struct Wrapper { void operator+() {} }; Wrapper<Buffer<-5>> a; void f1() { +a; } // error: Buffe...
The unqualified lookup invokes ADL, which needs to know if there are any friend functions defined in the associated classes. Buffer<-5> is one such, so it is instantiated. The fact that it’s syntactically obvious that it declares no friends doesn’t change the fact that the check for same involves completing the class...
62,315,162
62,315,196
C++ std::future with a unique pointer is calling synchronously
I recently asked this and this question. I wanted to use both answers I got, but when I do so, the std::async gets called synchronously. #include <thread> #include <chrono> #include <iostream> #include <future> #include <memory> typedef struct { std::unique_ptr<std::future<int>> a; } test; int f(int id) { std:...
The destructor of t is still called when the scope of the switch exits. You need to declare the scope of t to be the entire function: int f(int id) { test t; // declare outside switch switch (id) { // ... t = test{ std::make_unique<std::future<int>>(std::move(a)) }; } } Here's a demo.
62,315,899
62,315,984
undirected graph incidence matrix implementation
Here I wrote a little program to represent graph using incidence matrix, with use of vector of vector to incorporate dynamic memory allocation. #include <iostream> #include <vector> #include <utility> void print_graph(const std::vector<std::vector<int> > &adj); void addEdge(std::vector<std::vector<int> >& adj, int u, i...
This statement: std::vector<std::vector<int> > adj(3); defines a vector of 3 empty vectors. Try that: std::vector<std::vector<int> > adj(3, std::vector<int>(3));
62,316,000
62,316,672
String literals in structure is showing an error but when string literals declare as a constant it will not show an error why?
This program is compiled and run but showing error: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings] #include<iostream> using namespace std; struct person{ char* name; char* lastName; int age; }; void show(person temp){ cout << temp.name << " " << temp.lastName << " age is: " << temp.age; }...
I see your confusion about your sample source code. However, I see two questions you did not explicitly state, but implied. So I will answer both! What are String Literals in C++? The ISO/IEC C++ standard defines a string literal as an array of const char * , and your sample code violates this definition by declaring y...
62,316,094
62,318,133
How to read bits from std::bitset in a sliding window fashion and convert them to int?
I have std::bitset, where first n bits are set to some values. For each index in std::bitset, I want to read m bits (m < n) and convert them to int. When (index + m) > n, I want to wrap around. For example, for n = 6 and m = 2: std::bitset<8> my_bits {0b00101101}; // out of 8 bits, first 6 are set // bit indexes ...
Write a function. Encapsulate the algorithm. Accumulate results in a entity you would return. And use bitshifts instead of std::pow. #include <iostream> #include <bitset> #include <vector> template<size_t N> std::vector<int> convert_bitset_to_ints(const std::bitset<N>& bs, unsigned n, unsigned m) { std::vector<int...
62,316,163
62,316,191
C++ which template would be call if both template function match the argument list
template<class T> void fn(T t){} template<class T> void fn(std::vector<T> vt){} void f() { std::vector<int> vt; fn(vt); } I know that the second template function would be called, but i dont know the rules for template function matching.
Partial ordering takes place in the overload resolution for a call to a function template specialization. Informally "A is more specialized than B" means "A accepts fewer types than B". For this case, the 2nd fn is more specialized and wins in overload resolution, because it accepts types of instantiations of std::ve...
62,316,263
62,316,392
Having to redeclare an int for a second for loop
I am playing around on edabit.com C++ challenges to refresh myself and I was presented with a challenge where I needed to write a function that would, given a vector, return true if all even indices are even and all odd indices are odd. Otherwise return false. The logic and everything of the function was fine. I know t...
Firstly, JS and C++ have very different models of scopes, and JS is known (sorry) for its bad practices. In C++ the rule is more consistent: the variable is destroyed whenever the program exits the scope. That means that in this code: for (int i = 0; ; ) { } the variable i is defined just for this scope, it cannot be ...
62,316,407
62,316,784
"No template named 'variant' in namespace 'std'" in Android Studio
It's weird because it does recognise it in another project that I have. Here's the CMakeLists.txt fo; for the project where I get the error: cmake_minimum_required(VERSION 3.4.1) # Require C++17 compiler with no extensions set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) (....
The problem was that I didn't specified Gradle the version of CMake that I wanted to use. std::variant is not supported in older versions of CMake. So I went to build.gradle and did this: (...) android { compileSdkVersion 28 sourceSets { main.java.srcDirs += 'src/main/kotlin' } defaultConfig {...
62,316,471
62,317,832
Difference between int* a and int* a =new int
I m studying Binary Search Tree just had little Doubt, here is struct to construct a node. struct Node { int data; Node* left, *right; }; Now My doubt is when I m creating a new node why do I have to write Node* node =new Node; Why not Node* node;
Node* node; You define a pointer, but the pointer points to nothing. Node* node =new Node You define a pointer and a Node object, and make the pointer point to the object.
62,316,533
62,316,945
Add a Data value to the end of an array in c++
I need some help with this. I am running through some payroll data. I have run a function that reads a .txt file, and then stores it in arrays. I am now trying to write a function that allows you to add to those arrays (they are arrays of 32 but only have 20 elements from the file) So it needs to loop through the arr...
There seem to be a few issues here. Some have been dealt with in the comments above. So I will mention the others. The most important issue is that the purpose of the function is confused. It is both validating the existing data and adding (but not validating) new data. Nothing wrong with either of these things, but th...
62,316,580
62,317,109
Why would LVSCW_AUTOSIZE_USEHEADER stretch my first column to match width of listview control's width?
I'm working with Comctl32.dll's list-view control and attempting to divide the width of it amongst 10 columns, auto-sizing to match the strings in their respective headers. I am using the ListView_SetColumnWidth macro with the LVSCW_AUTOSIZE_USEHEADER value, and it's working with every column except the first one: He...
From the ListView_SetColumnWidth documentation: LVSCW_AUTOSIZE_USEHEADER Automatically sizes the column to fit the header text. If you use this value with the last column, its width is set to fill the remaining width of the list-view control. When you use this for the first time, there's only one column, so it is the...
62,316,583
62,316,625
Why substract vector::size with store it to a variable first and without return different result?
Size of the vector is 5, then I want to subtract it by 6. It should return -1, but the first try which I don't store the size in a variable doesn't return -1. It's return bunch of random number. Why is this happen? It looks exactly the same to me, with or without storing the size first to a variable. Both should return...
The return type of arr.size() is an unsigned integral type, most commonly std::size_t. When you subtract 6 from it, the value underflows and wraps around to the largest integer the size can store because the type cannot store negative values. When you store the result in a variable, you are also converting it to int w...
62,316,932
62,316,980
Create C++ dll with functions whose arguments can be called as out parameter in c#
I want to create a function in c++ that takes two parameter(char[], int) and modifies the parameters(Similar to out parameter in c#) and then create a dll that can be used in c#. C++ Sample Code: static void funct(char * name, int size) { char[] testName="John"; name=&testName; size=5; } C# Sample Code: ...
Use pointers in the C++ side and marshal these by ref on the C# side. static void funct(char** name, int* size) { char[] testName="John"; *name=&testName; *size=5; } const string dllLocation = "D:\\Test.dll"; [DllImport(dllLocation, CallingConvention = CallingConvention.Cdecl)] private static extern void f...
62,317,045
62,317,784
Increase the resolution of a geometry shape
The task is to increase the resolution of a geometry shape like this: So that the shape becomes this by adding data points: The shape is define by data points which has x and y coordinates and a index. The index represent the order to connect them. What type of algorithm should I use to achieve this?
You can use linear interpolation between segment ends. It is not clear yet - how many new points you want to insert in every segment. Does it depend on segment length or other reasons? Seems your picture shows mixed approach: n is at least nmin, part length is at most lmax like this n = max(nmin, int(seglength / lmax))...
62,317,097
62,317,225
Covariant type error when returning a derived type
I'm trying to create a base class with a derived type; where in the base class I have a pure virtual method that returns something of the type DtBase (another class), and when overriding it in the derived class returns something of the type DtDerived (which derives from DtBase). I get an error saying that the type of ...
You need to return a DtBase pointer DtBase::foo() and DtDerived pointer in DtDerived::foo(), otherwise the DtDerived portion would simply get sliced off and the caller would never see that it was actually a DtDerived that was returned.
62,317,111
62,317,411
C++ concept assignable_from won't accept const&-returning operator=
In the following MCVE, std::assignable_from reports that A<double>& can't be assigned to from A<double> -- when it clearly can. #include <iostream> template <typename T> class A { public: const A& operator= (const A& other) { return *this; } }; int main () { A<double> d1, d2; d1 = d2; //this works fine...
I've always had = return const &, because I thought it was dumb to say (A=B)=C. You are free to do that, but there are consequences when you break with established conventions. You have encountered one of them. std::assignable_from requires that you follow established C++ conventions for assignment operators. And thi...
62,317,113
62,317,933
How to display structures Arrays in functions
This program is essentially supposed to count the results of random throws of a dice 100 times and count the occurrence of each face then display all of them as a histogram of asterisks. It would seem the functions could be working but i'm unable to verify because after I make my choice, nothing displays. #include <ios...
So, this code contains many different mistakes. Let's go in order. In structBar label may be const struct Bar { int value; const Side label; }; You don't need forward declaration for function signature In rollDice you have many unnecessary local variables and I would use mt19937 random generator. So rollDice wi...
62,317,118
62,330,553
How can I list all the available VCL styles in a combo box and in the ComboBoxChange event, apply that style in C++ Builder?
I'm currently trying to add a feature in my application where the user can select a VCL style to there preference. I could manually add all the styles into the ComboBox directly but i'm sure there's a much easier way.
Create a new C++Builder VCL application. In the Project | Options | Application | Appearance menu choose some Custom Style Names. Then add Button and ComboBox box components to your C++ VCL form. For the Button's onlick and ComboBox's Change events use the following code. You'll also need to put #include near the top...
62,317,531
62,317,638
Can static variables in member functions be thread safe?
I am implementing something very similar to the question here. Window::Window() { static bool flagInit = true; if (flagInit) { doInit(); // doInit should be called only once. flagInit = false; } createWindow() } I understand that using static variables can generally be a bad idea when it comes to ...
There's a tool exactly for this: std::call_once: class Window { static std::once_flag flagInit; // ... }; Window::Window() { std::call_once(flagInit, doInit); // Note: can throw createWindow(); } You can also technically still accomplish this with statics since C++11 made their initialization thread-safe: Win...
62,318,099
62,332,461
How is WakeByAddressAll ordered?
This is the follow-up of the question How is std::atomic<T>::notify_all ordered? What would be the answer to that question, if I use WaitOnAddress or futex directly. From the answer to that question the conclusion is that the below program does not hang, and C++ provides necessary guarantees, although wording still ma...
From Synchronization and Multiprocessor Issues page of Windows documentation: Memory Ordering [...] The following synchronization functions use the appropriate barriers to ensure memory ordering: Functions that enter or leave critical sections Functions that signal synchronization objects Wait functions Interlocked f...
62,318,188
62,318,252
0x%08lx format specifier in printf statement to cout
I have a printf statement as: printf("Buffer A Data: 0x%08lx, Buffer B Data: 0x%08lx\n\n", (ul) bufa, (ul) bufb); How do I write this statement using std::cout? Buffer variables contains huge addresses.
You can use the std::setw, std::setfill and std::hex modifiers: std::cout << "0x" << std::hex << std::setw(8) << std::setfill('0') << bufa; Notes: std::setw resets after printing something As noted by Tarang Jain, std::showbase would place the base marker inside the filling (i.e. 000xDEAD instead of 0x0000DEAD) so I ...
62,318,969
62,318,997
Why Incrementing Array name works in this case?
I've learned that array name is treated like a const pointer, and thus it cannot be incremented. However, I found that it works under this condition: when array is passed as an argument of a function, inside the function, name of the array can be incremented. can some explain me why this works? Here is the code: using ...
It's true you cannot increment an array but str is a pointer not an array. You can tell by looking at the decalration const char* str. The strange thing is that even if you change the declaration to this const char str[] then str is still a pointer. It's impossible to have an array as a parameter in C++ (or C).
62,319,450
62,319,814
Conversion from string to double in C++ with data extracted from .csv file (stod, strtod, atof)
I have issues when I try to convert string values extracted from a csv file to double with the functions stod, strtod and atof. I only get the integer part of the values. I compile with catkin build, which is used to build packages used in ROS. The values I want to convert are the 8 values in the second line in this cs...
You need to remove "'s from beginning and end of the string before calling std::stod. Change your conversion code to : for (auto &s : positions_str) s.erase(remove(s.begin(), s.end(), '\"'), s.end()); // this will remove double quotes from the string if present cout << "Position in double format using stod() : " <...
62,319,649
62,319,777
What is the difference between std::enable_if and std::enable_if_t?
C++-14 introduced std::enable_if_t. What is the difference between it and std::enable_if? Are there any advantages or differences in using std::enable_if_t?
std::enable_if_t is a type alias of the inner ::type of std::enable_if, it's syntactic sugar so you don't have to write typename std::enable_if</* */>::type
62,319,929
62,320,898
C++: Initialize a member array within a constexpr constructor
I am implementing a class in c++17 that needs to be able to construct an object at compile time using a constexpr constructor. The object has an array member which I cannot seem to be able to initialize through an argument. I've been trying to use std::initializer_list for this, something along the lines of: #include <...
The explanation is going to be long, but bear with me. You can't initialize an array with an std::initializer_list. When you write something like int arr[] = {1,2,3}, the part enclosed in braces is not an std::initializer_list. If you don't believe me, consider a similar initialization for a structure: struct A {int ...
62,320,177
62,326,599
Cannot format argument from within spdlog
I am trying to use spdlog. I incorporated it with my code, but now I am getting the following error: ....fmt\core.h(1016): error C2338: Cannot format argument. To make type T formattable provide a formatter<T> specialization: https://fmt.dev/latest/api.html#formatting-user-defined-types ....fmt/core.h(1013): note: wh...
spdlog uses the {fmt} library for formatting the output text, and that requires the <fmt/ostream.h> header file to be included in order to enable std::ostream-like support. Regardless of using external implementation of the {fmt} library, or the one from spdlog sources itself, there's the special header <spdlog/fmt/ost...
62,320,330
62,332,957
-fno-unwind-tables and -fno-asynchronous-unwind-tables does not work NDK clang++
I'm compiling my C++ code using clang++ that comes with ndk21. I've set both compiler flags -fno-unwind-tables and -fno-asynchronous-unwind-tables but the number of entries in the unwind table do not reduce. I also checked by setting the opposite -funwind-tables and -fasynchronous-unwind-tables but it doesn't increas...
Typically the reason is that you're depending on some other libraries that do have unwind tables. The C++ stdlib is definitely built with them, so if you're using libc++_static.a they'll be added to your library. Since that code is already compiled, your compiler flags won't have any effect on it :) I should also note ...
62,320,782
62,322,017
undefined reference to "boost::archive..." g++ / wsl
I'm using draco and boost together. Draco is working well after this question. I have tried to install boost and i think its done. Now i try to run this command in vs-code on wsl : g++ -I ~/local/include -L ~/local/lib -o prog ObjContainer.cpp -ldracodec -lboost_system errors: ObjContainer.cpp:(.text._ZN5boost7arc...
The boost::archive class is part of Boost.Serialization library. You need to link with -lboost_serialization -lboost_system at the end.
62,321,180
62,509,679
How to run multiple objects of a class having a function calling only threads in C++?
I have a subclass called WiFiControlImplementation , it is a subclass of another class called WifiSniffer The WiFiControlImplementation contains a public method: class WiFiControlImplementation : public WifiSniffer { public: WiFiControlImplementation(){}; void startControlProcess (void); private:...
In order to run class functions in threads from a main program , I just used a function for each one of them, and the second function returns a thread that executes the first function in a lambda call, here is the example : In wifi_Hopper.h : #include <thread> class wifi_Hopper { public: wifi_Hopper(){};...
62,321,276
62,321,399
How to pass char[ ] as call by reference in function
I want to pass a char[] as reference or pointer to a function which modifies the array. void GetName(char* name[],int* size) { char arr[5] = { 'a','b','c','d' }; for (int i = 0; i < 4; i++) *name[i] = arr[i]; *size = 4; } int main() { char array[10]; int size=NULL GetName(&array,&size); ...
The way to modify an array is to pass a pointer to the first element of the array, using the fact that arrays decay to pointers void GetName(char* name,int* size) { char arr[4] = { 'a','b','c','d' }; for (int i = 0; i < 4; i++) name[i] = arr[i]; *size = 4; } int main() { char array[10]; int...
62,321,812
62,322,273
C++20 - Call function declared as auto in template
I'm building a nodejs addon in C++ and I am trying to make a function exporter from C++ to node. More exactly, I'm trying to build a functionality similar to this: std::string func(std::string param) { return param; } void func_wrapper(const v8::FunctionCallbackInfo<v8::Value>& args) { Isolate* isolate = args.Ge...
Includes: #include <functional> #include <utility> #include <type_traits> #include <concepts> #include <string> Conversion functions: decltype(auto) Convert(v8::Isolate* isolate, const v8::Local<v8::Value>& value, std::type_identity<std::string>) { return *v8::String::Utf8Value(isolate, valu...
62,321,815
62,338,065
Process only tiled event and not maximize event
I'm building a very basic calculator program using GTKMM Basic Calculator screenshot The layout is in landscape mode (buttons and display label in horizontal orientation) by design I want to orient those two to portrait mode (ie., in vertical) when the user snaps/tiles the window to the right or left Below is a sample ...
After hacking around a bit with the GdkEventWindowState enums, I figured I can compare against the tiled state with the window maximized state together ie., make sure to switch orientation to vertical only if the window is tiled and not maximized Because the code ... if ( window_state_event->new...
62,321,906
62,322,054
c++ lambda executed at wrong address / in wrong context
The following code is also available at godbolt.org/z/SjkAWZ. I have a struct with a std::function as member variable, which gets assigned by a lambda expression in the constructor. The lambda can be called from the constructor successfully, but not from a member function. #include <vector> #include <functional> struc...
You missed the copy / move constructor for your struct! If you assign some vars to a std::vector it will reserve sometimes new memory and copy all content to the new memory. In your case, the lambda is not aware about the change and keeps the reference to the old instance of S. So your code is simply broken. You can wo...
62,322,085
62,322,350
Assign vector from pair<first,last>
I'd like to construct a vector from data provided by a 3rd party lib. The lib holds the data and provides access to it like this: const uint8_t* data; std::pair<const uint8_t*, const uint8_t*> getvalue() const { return std::make_pair(data + offset, data + length); } For further processing this data I'd put it into a...
Structured bindings As of C++17, you can use structured bindings to bind the first and second members of std::pair<...> return value from getvalue(): const auto [data_begin, data_end] = thirdpartydata.getvalue(); const std::vector<uint8_t> v(data_begin, data_end); C++17 also introduced class template argument deductio...
62,322,604
62,322,823
OSX clang++: Undefined symbols for architecture x86_64 for explicitely instantiated template in cpp file
I have template class defined in .h file and template methods are defined in .cpp file. This .cpp file also contains explicit template instantiation via template clas Class<type>. This use case works correctly on VS2019 as same as on GCC (7.4.0). But, it's not working on OSX with clang++ (Apple LLVM version 10.0.0 clan...
The member function was not instantiated. Which is no surprise, because you do the explicit instantiation before defining CTemplateTest<T>::Test. Move the explicit instantiation into the end of test.cpp template <class T> int CTemplateTest<T>::Test() { return 42; } template class CTemplateTest<int>; template clas...
62,322,943
62,661,217
Building libraries using Premake5 without separate project files for each build
I have a large project and it takes quite a lot of time to compile the whole thing. A small change in a header file will result in building the whole project again even though it doesn't affect most of the other components. Is there a way to use premake5 to build source files in the project to its own library file (pre...
No, that is not possible. Premake is designed to generate projects that can work with a variety of different toolsets, and most (no?) IDEs support that workflow.
62,323,122
62,323,317
C++) How to use other class' method from a class?
Here, I want to use class var's method "whats" from class func. How to call it, 1. in one script 2. separated into several class files. Help!! #include <iostream> using namespace std; class node { public: int y; node(int x){ y = x; } }; class var { public: node* head = new node(2); int whats...
You cannot execute methods in headers, but anywhere else, it's simple, the way you access it is by creating a new pointer. var * v = new var(); v->whats(1); Note that this is prone to memory leaks, so consider deleting pointers after you use them, like delete ( v );
62,323,372
62,323,633
Windows calling conventions
Hi so a friend told me that: calling conventions are c++ function specifiers that determine if the function that calls another function should clean the stack frame or that would be the job of the called function is that true? Also how would the cleaning part look in assembly with a syscall function calling another ...
Historically, the Fortran and Pascal languages used a convention where the caller pushed its arguments on the stack (first parameter first in stack), and then called the callee function. The prologue code in the callee usually popped the return address and the parameters, and pushed again the return address ( this part...
62,323,612
62,324,136
How to use map_indexing_suite from Boost.Python with custom not std object?
Simple example of 'map_indexing_suite' usage is working fine: class_<map<int, string> >("testMap") .def(map_indexing_suite<std::map<int, string>, true>()) ; and on python side it works as expected: a = riversim.testMap() a[1]='sdf' But! If I try to use more complicated object BoundaryCondition instead of ...
First off, bcs = riversim.t_BoundaryConditions Assings the class. It needs to be bcs = riversim.t_BoundaryConditions() Now bcs[1] = bc Results in Traceback (most recent call last): File "./test.py", line 10, in <module> bcs[1] = bc TypeError: Invalid assignment That's because the same applied to bc, both the...
62,323,704
62,323,860
Why I can not print NULL address in c++
Let's say that I have a Linked list class as follows. struct Node { int data; Node* rptr; }; class LinkedList { public: Node* curr; Node* prev; Node* first; Node node; LinkedList() { curr = NULL; prev = NULL; first = NULL; node.data = NAN; node.r...
The problem here is, that you did not try to print a nullptr, but you access it and want to print the result. Before you get the result to print, your program already has a null pointer exception which is totally unrelated to printing. first = first->rptr; first is a valid pointer ( not nullptr ) and you assign first ...
62,324,009
62,325,223
_mm256_load_ps cause segmentation fault with google/benchmark in debug mode
The following code can run in both release and debug mode. #include <immintrin.h> constexpr int n_batch = 10240; constexpr int n = n_batch * 8; #pragma pack(32) float a[n]; float b[n]; float c[n]; #pragma pack() int main() { for(int i = 0; i < n; ++i) c[i] = a[i] * b[i]; for(int i = 0; i < n; i += ...
Your arrays aren't aligned by 32. You could check this with a debugger. #pragma pack(32) only aligns struct/union/class members, as documented by MS. C++ arrays are a different kind of object and aren't affected at all by that MSVC pragma. (I think you're actually using GCC's or clang's version of it, though, becaus...
62,324,050
62,324,367
Can lambdas be used as non-type template parameter?
Is the following code legal? template <auto Lambda> struct A {}; int main () { auto lmb = [](int i){return i*i;}; A<lmb> a; return 0; } I noticed that g++ compiles it fine, while clang++ returns error: a non-type template parameter cannot have type '(lambda at main.cpp:...)'.
Can lambdas be used as non-type template parameter? Yes, with implementations that has implemented P0732R2 - Class types in non-type template parameters but clang++ has not implemented it yet. Source: https://en.cppreference.com/w/cpp/compiler_support Note that the lambda needs to be at least constexpr (which it is ...
62,324,475
62,325,339
Why does initializing a class with a ternary if cause a double-free?
When the following code is compiled using clang with the clang-analyzer enabled: #include <stdlib.h> struct Buffer { unsigned char *buf; Buffer() : buf(0) {} Buffer(const Buffer &that) { buf = new unsigned char; *buf = *that.buf; } Buffer(Buffer &&); ~Buffer() { delete buf; } ...
The program is ill-formed because the move constructor is used, but not defined which violates the One Definition Rule. The scanner diagnostic may be false positive caused by this bug in the program. The copy constructor is not used, but it is broken because it potentially indirects through a null pointer.
62,324,504
62,324,714
C++ generate function with template metaprogramming
How can I generate a function using template metaprogramming. What I want to do is have a bunch of functions that basically do the same thing: Type1 fun1(int arg1, int arg2) { Type1 newType1 = {}; newType1.arg1 = arg1; newType1.arg2 = arg2; return newType1; } Type2 fun2(int arg1, int arg2, int arg3, bool arg4...
This is a c++17 answer: template<auto PMem> struct member_type {}; template<class T, class M, M(T::*ptr)> struct member_type<ptr> { using type=M; }; template<auto PMem> using member_type_t=typename member_type<PMem>::type; template<class T, auto...PMem> T func( member_type_t<PMem>... args ) { T retval = {}; ( ((re...
62,324,847
62,326,321
Create regExp to textField in QML
I need a regExp to a textField who will receive a ip and mask, something like that: "000.000.000.000/00". It's necessary, if field is empty, return 0: example - 192.168.0.12 I have that: Custom.VisTextField{implicitWidth: 200; implicitHeight: 30 id: ipValue validator:RegExpValidator { ...
I search in many fonts to discover a resolution, but i realize a conflict with inputMask and regEx. I solved using something like that: Custom.VisTextField{implicitWidth: 200; implicitHeight: 30 id: ipValue validator:RegExpValidator { regExp: /^(([01 ]?[ 0-9]?[0-9 ]|2([ 0-4][...
62,324,872
62,329,078
Shared Pointer ambiguous call / undefined reference to call
My program compiles and runs fine with MSVC but if I compile it with linux with an intel compiler it suddenly has linking problems: undefined reference to Model::Model(boost::property_tree::basic_ptree<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std:...
"undefined reference" is not the same as ambigous function call (if you're talking about overloaded functions). It means that the compilation unit (i.e. the .cpp file) containing that function hasn't been included in the link, or some macro or using namespace has changed the meaning of the function in the place where i...
62,325,094
62,325,349
How to define concept of a function that returns bool
I want to define a concept of a function that takes in a single argument and returns bool. Here is what I came up with: template <typename T> concept ConditionFunc = requires(T t) { { ConditionFunc(t) } -> std::same_as<bool>; }; I want to use it like this #include <concepts> #include <vector> bool IsEven(int n) {...
Your concept should be based on 2 types, the argument type T, and the function type: template <typename Func, typename T> concept ConditionFunc = requires(T t, Func f) { { f(t) } -> std::same_as<bool>; }; Then you can constrain Foo to accept a function with the signature bool(T);, like this: template <typename T> ...
62,325,198
62,325,544
Braced functional cast to reference type, a hole in the standard or compilers bug?
According to the standard, a braced functional cast always results in a prvalue, [expr.cast]/2 Otherwise, the expression is a prvalue of the specified type whose result object is direct-initialized with the initializer. Which is hard to interpret when the specified type is a reference type, as it may happen in generi...
This is CWG1521: T{expr} with reference types According to 8.2.3 [expr.type.conv] paragraph 4, Similarly, a simple-type-specifier or typename-specifier followed by a braced-init-list creates a temporary object of the specified type direct-list-initialized (11.6.4 [dcl.init.list]) with the specified braced-init-list, ...
62,325,585
62,326,083
Mock member function call to lambda
Using c++17 and gmock, I am mocking a class and would like to redirect calls to one of its member functions to a lambda. Is this possible? He're a minimal example: #include <gmock/gmock.h> using ::testing::_; using ::testing::Invoke; using ::testing::Return; class Foo { public: virtual uint8_t MyCall(const uint8_...
The return type of your lambda does not match that of your member function The error messages of gmock can be somewhat cryptic, and it doesn't help when you are working with types that are typedefs to fundamental types; in this case uint8_t. If we look closer at the error message: error: no matching function for call ...
62,325,615
62,327,536
OpenCV data of two mats are the same but values when retrieved with Mat::at are corrupted
I serialize and then deserialize a Mat using custom functions. When you compare the uchar* Mat.data of two functions they are the same but when I try to check values directly using Mat.at<> after third element, element values are stuck at some corrupted float values. I tried changing elements to every other value, noth...
+ Edit Since you want to save byte for generic types, you can just iterate each byte like this. In serializeMat for (int i = 0; i < operand.total() * operand.elemSize(); i++) { srlzstrstream << pixelPtr[i] << " "; } In deserializeMat for (int i = 0; i < matoper.total() * matoper.elemSize(); i++) { desrlzstrst...
62,325,655
62,325,884
How to start GDB for C++ called from Python?
I need to debug a C++ function that is called from Python code. How to start GDB (or better DDD) in such a way that it debugs the C++ code called from a given Python command line? The given Python command line is: python3 -m e2e.Tests.Libs.HundredEightyOneTest It calls a C++ code that I need to debug.
My recommendation: recompile your python interpreter from its source code (so it gets compiled with DWARF debug information, practically speaking with GCC invoked as gcc -Wall -O -g). Once you get such a python3 interpreter (with DWARF debug info), perhaps in /usr/local/bin/python3, read the documentation of Python, th...
62,325,666
62,360,842
How to properly release C++ software (game) on Linux
I have created a small test game (Pacman-clone) with my newly self-created 2D/3D game engine. I have not used any IDE to create this, but only used vim and premake5 to create the Makefile. The only dependency I have is SDL2 for window creation/events and OpenGL for rendering. So I am not using any framework like Unity,...
I found a solution that seems to work and I think is also used by other games on Steam/GOG/Itch that do not use wine/mono/... to just make their windows game work on Linux. I installed Ubuntu 18 (or 16 if you prefer it to work on older OSses too) and set up my build environment there (I had to rewrite some of my C++ co...
62,325,679
62,325,770
What is std::jthread in c++20?
What advantages does it offer over std::thread? Will it deprecate the existing std::thread?
std::jthread is like std::thread, only without the stupid. See, std::thread's destructor would terminate the program if you didn't join or detach it manually beforehand. This led to tons of bugs, as people would expect it to join on destruction. jthread fixes this; it joins on destruction by default (hence the name: "j...
62,325,751
62,326,009
Converting uint8_t* buffer to uint16_t and changing endianness
I'd like to process data provided by an external library. The lib holds the data and provides access to it like this: const uint8_t* data; std::pair<const uint8_t*, const uint8_t*> getvalue() const { return std::make_pair(data + offset, data + length); } I know that the current data contains two uint16_t numbers, bu...
Maybe with something like this union? No. Type punning with unions is not well defined in C++. This would work assuming big_int16_buf_t and therefore datatype is trivially copiable: datatype d{}; std::memcpy(&d, data, sizeof d); uint16_t first = data[1] <<8 + data[0] uint16_t second = data[3]<<8 + data[2] However ...
62,326,285
62,331,103
How to extract hive and registry name from registry key
I have to extract hive from registry key and registry name so that I can open the key in regopen Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Mozilla\Firefox I have to extract HKEY_LOCAL_MACHINE and Software\Mozilla\Firefox Is there any API to extract them as wstring? wstring keyname = L"HKEY_LOCAL_MACHINE\SOFTWARE\Mozilla\Fi...
If I understand you correctly, you just want to split the string "HKEY_LOCAL_MACHINE\SOFTWARE\Mozilla\Firefox" into substrings "HKEY_LOCAL_MACHINE" and "SOFTWARE\Mozilla\Firefox". There are no Win32 API functions for that exact purpose, but you can use the find() and substr() methods of C++'s std::wstring class, eg: #...
62,326,830
62,326,982
Is it possible to make std::cout flush automatically before program termination in various failure cases (e.g., exception)
If an exception is thrown, the lack of a flushed stdout makes it harder to diagnose the issue. Are there any mitigations that can be used? (e.g., termination hooks, compiler flags, etc). I can understand that in a segfault it's probably very difficult to flush, but I would think that it for uncaught exceptions in arbit...
When program terminates due to uncaught exception, std::terminate will be called. This calls the terminate handler that has been registered using std::set_terminate. Within this terminate handler, you can flush the standard output streams. std::terminate is also called in some other cases such as throwing exception out...