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
65,848,634
65,946,578
Boost.Python library build errors when no default constructor and unique pointer
I am trying to wrap my C++ code using Boost.Python and have encountered a couple errors and could use some help at solving them. But first here are the assets I have. Product.h namespace Products { class Product { public: virtual ~Product() {}; virtual int generateProduct(int verbose = 0) = 0; virtual...
Apparently the Python code copies your ProductBuilder object. However, ProductBuilder contains a unique_ptr, which cannot be copied (it can only be moved). One easy way to fix this is to replace the unique_ptr by a shared_ptr, which is copyable.
65,849,269
65,849,451
I am beginner in c++, i want to know the error in my code
#include <iostream> using namespace std; int main() { cout << "entre two numbers"; double x, y; cin >> x >> y; if (x != y) if (x % 2 == 0) if (y % 2 == 0) cout << "the two numbers are accepted"; else cout << "the two numbers are not acc...
You have to declare the variables of 'int' type instead of double and your error will get resolved. Write below line. int x,y;
65,849,365
65,850,176
how to find the maximum occurrence of a string in string array in c++
I have a string array like {"A", "B", "AA", "ABB", "B", "ABB", "B"} how do I find the string ( "B" ) which occurs the largest number of times in an array like this in c++? Thank you
If elements of the array has the type std::string then without using additional memory resources the function that finds the element that occurs more often in an array can look the following way as it is shown in the demonstrative program below. #include <iostream> #include <string> size_t max_occurence( const std::st...
65,849,627
65,850,468
Can I access restricted memory space by pointers
So when I learnt about pointers, I got some crazy idea: If I print a pointer, it gives an address in the memory, and if so, what part of the computer's memory is actually read? For example #include <iostream> using namespace std; main() { int a=1; int* ptr=&a; int i=0; while(1) { cout<<(ptr+i)<<"\t...
No, if you could do this then the "restriction" would be useless. In the past - think: the MS-DOS and Windows 3.1 days - you could do this. And it would overwrite memory belonging to other programs, and probably crash the computer. Modern operating systems use a technique called virtual memory, where the operating syst...
65,849,805
65,878,315
C header files missing to compile Sqlite3.c
I tried to compile sqlite3.c from Microsoft Visual Studio 2017 developer command prompt. I'm getting errors for missing C header files. I selected all work loads in installer required for C and C++. What reference am I missing? Input: cl shell.c sqlite3.c -Fesqlite3.exe Response: Microsoft (R) C/C++ Optimizing Compil...
According to Microsoft Docs, error C1083 is mainly caused by the following reasons. The file is not included in the include search path The compiler cannot find the file by using the search rules that are indicated by an #include or #import directive. For example, when a header file name is enclosed by quotation marks...
65,850,009
65,850,770
Source file header file and other files are not displayed when I create empty C++ Project in visual studio 2019
I am very new to visual studio and I watched a couple of tutorials to understand how to use it, But I ran into a problem. Every person I watched on YT has a source file, header file, and other files when creating an empty Project but this isn't a case for me and I basically can't write anything. when I try to add a CPP...
First Create an empty project . Second Go to solution explorer. Third Right click the source file option. Fourth Go to add and create a new item Fifth Select .cpp file and press add. And Congrats your .cpp file is created. Do the same procedure to create header file and class.
65,850,378
65,854,254
How do I check for overlap with spawned actors? UE4 C++
I am quite new to C++ and UE4. I am creating a basic snake game in UE4 and I can't get the snake to trigger an overlap event when it overlaps with the fruit that the snake will eat. The fruit is spawned on BeginPlay at random coordinates each time I start. I have tested overlapping with actors that are not spawned (i.e...
Instead of calling that function on Tick, you should instead create a USphereComponent or UBoxComponent on your Snake to act as a Trigger Volume that you can then subscribe to its OnBeginOverlap and OnEndOverlap delegates to check for overlaps of Fruit Actors. // .h UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = ...
65,850,642
65,850,887
std::bind member function within struct
I have a function bar that is widely applicable, and not a member of any struct. bar takes a functional/function pointer and some other arguments. I also have many structs. They are heterogeneous in member variables. Within each struct Foo, I want a member function of Foo to call on bar such that the functional supplie...
The first (hidden) argument of a argument of a member function is the this variable. So the correct way to use std::bind here is std::function<int(int)> wrapper = std::bind(&Foo::f1, this, _1 , 7); However, modern C++, the correct way to do this is to use a lambda. I usually use explicit binds for this, so: auto wrap...
65,850,709
65,850,795
Why am I getting the error "using uninitialized memory 'i'" and "uninitialized local variable 'i' used" when trying to make i = i*i
I am new to C++ and was testing out while loops and the sheer speed of C++ and its toll on my CPU and I got the following errors: Severity Code Description Project File Line Suppression State Warning C6001 Using uninitialized memory 'i' Severity Code Description Project File Line Suppression State Error 4700 uninitiali...
In the body of the while loop while (i < 10000000000000000) { long long i = i*i; cout << i ; } you declared the variable i that is not initialized and has an indeterminate value and you are trying to use this indeterminate value to initialize the variable itself. That is in this declaration long long i = i...
65,850,759
65,850,852
Why ordinary function is not called there?
As we know when we do function overloading in template function with ordinary function, If the compiler get the exact match with ordinary fun() it will call ordinary fun() and ignore the template fun(). But in the below C++ code when I run the code it call the template function not ordinary function. Why? Code #include...
In this call: fun(3, 4.7); the second argument 4.7 is a double. As you mentioned in your question, the non-template function is called only if the arguments are an exact match. Since the non-template function expects a float for the second argument, this requires a conversion from double to float. This is not an exact...
65,850,875
65,852,510
Copy memory every n bytes
I have one array of uint8_t values, my goal is to copy every 3 bytes to a dst array, but the catch is that I iterate from 4 to 4 bytes in the dst array, just like shown below. src = {1,2,3,4,5,6}; dst = {0,0,0,0,0,0,0,0}; ... dst = {1,2,3,0,4,5,6,0} For now i'm using the following code to perform this task. for(int i=...
There are many ways to try and optimize your conversion loop. As recommended by 0___________, you should consider memcpy for sized sized chunks as most optimizers will generate very efficient code for the target platform, beating hand coded naive alternatives. Here is a quick benchmark comparing 3 methods: copying 3 b...
65,850,942
65,851,512
Preserve access privileges when using '->' operator
I have two classes, template<class Type> class SafePtr { public: SafePtr() {} ~SafePtr() {} void Lock(Type* data, void* key) { if (!pKey) { pKey = key; pData = data; } } Type* Unlock(void* key) const { if (key == pKey) ret...
I still think you try to solve a problem that has more to do with possible flaws in the design of the API/of the code, the documentation, or with the lack of C++ knowledge of the one using it, with a "solution" that has more cons than pros. If a C++ programmer does not know what ownership is or does not respect it and ...
65,851,011
65,942,664
How to move an actor back and forth Unreal Engine
I'm new to Unreal Engine and I'm trying to move an actor from his original placement location to point B and then back to the original placement and then to B in a loop. How do I do this through C++? I don't know much about all of this but I have a homework on researching how it works. I know how to make the C++ Actor ...
Okay so I solved it by doing the following: I added the following to the .h file APlateUp(); UPROPERTY(EditAnywhere) UShapeComponent* Root; UPROPERTY(EditAnywhere) UStaticMeshComponent* MyMesh; float RunningTime; in the class public And then in the .cpp file I added Root = CreateDefa...
65,851,294
65,851,535
Palindrome testing function with only the string as input
I am trying to write a recursive function in C++ to check if a string is a palindrome or not. (A palindrome is a string that's spelled the same way forward and backward like "radar") The function must be boolean and only take the string as input. But it is only working for strings with two letters. Anything more than t...
Since you are using recursion, one key thing to note is you have to return the output produced by the recursive function. In this case, you need a return statement in the second if. Here is the working code: bool testPalindrome (string x){ static int y = 1; static int z = x.length(); if( (z-y == 1||z-y == 2) && x[x...
65,851,336
65,851,362
I need a way to return out of a function without having to return the "return type"
I have a function that allocates memory and then returns the pointer to that memory address. I'm allocating an array of char, the argument that they pass into the function will be the array size. Now the problem is that if they pass 0 as the argument for the size to dynamically allocate, then I want to exit/return out ...
The correct way to signal that a pointer doesn't point to valid memory is with a nullptr. So your return statement in the case that the memory allocation fails would simply be: return nullptr; Of course, the caller of the function needs to make sure that the returned pointer is not nullptr before they try to dereferen...
65,851,614
65,851,714
Find a word in a sentence c++
This code should say if a word is present in a sentence or not. When I insert the sentence and the word where I declare the strings(for exemple: string s = "the cat is on the table" string p = "table" the program says that the word is in the sentence) the code works but, with the getline, the for cycle never begin and ...
after taking the input strings then use length() to find the length, otherwise you are not taking the actual size of the strings. getline(cin, s); getline(cin, p); int sl = s.length(); int pl = p.length(); For splitting the words after taking the input string by getline() you can use stringstream which is a builtin ...
65,852,114
65,853,801
How to pass unique_ptr by reference polymorphically?
I have a pure virtual class Base and some derived classes ChildA (A/B/C etc): class Base { ... } class ChildA : public Base { ... } I need specific control of the ownership of these child classes, so I spawn them via factory functions and std::unique_ptr. At some point during their creation/setup, I need to m...
I'd do this: bool modifyInstance(Base* baseInst); bool childAFactory(std::unique_ptr<ChildA>& buffer) { buffer = std::make_unique<ChildA>(); if (!modifyInstance(buffer.get())) buffer.reset(); } That is, let the factory remain responsible for lifetimes, and just return an error result from modifyInstan...
65,852,204
65,852,349
Convert from a Base object to a Derived object in C++
I am trying to abstract sections of code to be platform independent. I have one section of code that is creating objects of Base class IModel. std::shared_ptr<IModel> joint_model_3d = std::make_shared<IModel>(); I have another section of code that is responsible for rendering. In order to render the object I need to c...
My question is, can I create an object of the Base class IModel in the platform independent code, which is not supposed to know Direct3DModel, and convert it to Direct3DModel when I need it for rendering. No, that won't work. You'll have to create a Direct3DModel object in the code base that knows about the class. Th...
65,852,218
65,858,359
Is _mm_prefetch asynchronous? Profiling shows a lot of cycles on it
Related to Understanding `_mm_prefetch`. I understood that _mm_prefetch() causes the requested value to be fetched into processor's cache, and my code will be executed while something pre-fetches. However, my VS2017 profiler states that 5.7% is spent on the line that accesses my cache and 8.63% on the _mm_prefetch line...
Substantially everything on an out-of-order CPU is "asynchronous" in the way you describe (really, running in parallel and out of order). In that sense, prefetch isn't really different than regular loads, which can also run out of order or "async" with other instructions. Once that is understood, the exact behavior of ...
65,852,713
65,852,791
I have created function to modify a node in Linkedlist in C++ but its not working:
This Function is Created in LinkedList to modify a node at a given position. But, this function is not working properly and it is giving some random values. void update_data(int old, int new_data) {//Function toupdate node Node *curr=header;//Data members int pos = 0; whi...
For starters the variable pos is not used within the function. Secondly the condition of the while loop while(curr->next!=NULL) { is incorrect and in general can invoke undefined behavior because the pointer header can be equal to nullptr. And moreover if the list contains only one node pointed to by the pointer heade...
65,853,468
65,854,295
MQTT connection through ESP01 8266
I'm trying to establish a connection with my m Mosquitto server through an ESP01 8266. I installed Mosquitto on my computer and started it with Brew. The problem is that the ESP01 doesn't connect to the "localhost:1833" (that should be my Mosquitto address). I don't know what to do, am I missing something? This line co...
Localhost in the code on your ESP is the ESP itself. You are trying to connect from the ESP, to the ESP. Localhost always refers to "this computer", just like the IP address 127.0.0.1 does. "This computer" as seen from the code on the ESP is the ESP itself, and not the computer that is running the MQTT server. Assuming...
65,853,517
65,853,876
why build showing errors in cominterfaces.tlh
Any clue will be great , since I am totally no clue in C++ code. I am getting following error while building the project Severity Code Description Project File Line Suppression State Error C2059 syntax error: ')' \releasemindependency\cominterfaces.tlh 592 Line number in cominterfaces.tlh * *IVoxarCl...
Well seems like all the arrows points out 'export' which I just found it to be a C++ keyword. But seems like it wanted to be use as a variable name there. Maybe changing 'export' to 'voxar_export' might help. Just like 'voxar_import' line above it. But it is just a guessy solution.
65,853,535
65,857,458
How to produce a list of executables as a separate cmake target
I tried my best to add a custom cmake target that compiles a list of .cpp files from a specific folder, and produces an executable for each file, with no success. Basically my scenario is as following: foreach (FILE ${EXAMPLE_FILES}) add_executable(${TARGET_NAME} ${FILE}) endforeach () Currently, when I type cmake...
By adding EXCLUDE_FROM_ALL keyword to add_executable call, the building of the executable will be excluded from make all. For make a single target to create multiple executables just make this target dependent from these executables. # Create the custom target before loop. add_custom_target(examples) foreach (FILE ${E...
65,853,628
65,909,650
C++ - Unable to link in libyaml using Visual Studio 2019/CMake
Attempting to link in libyaml (0.2.5) using Visual Studio 2019 Enterprise and CMake, as I have a cross-platform (Linux/Windows) project that uses this library. According to the documentation, this library should work in Windows 10. It links in just fine on Linux (64-bit machine). I'm compiling it as a static lib, and i...
The __imp was the clue that my code was trying to include the library dynamically... Opening up yaml.h, I noticed that it tries to export from DLL unless YAML_DECLARE_STATIC is defined. Defined this in CMake and my issue is resolved.
65,853,865
65,859,520
How to compare vector<float> and float*
I need to compare two float arrays for equality of their values. I know they have the same length. But unfortunately the arrays are not the same type: bool compare(vector<float> A, float* B) { // what do I write here? } How can I do it? I am not that familiar with pointers.
Thanks a lot everybody! This is how I did it now, since I know that the two vectors have the same length. bool compareSerAndPar(std::vector<float> Ser, float* Par, int size) { float eps = 0.01f; for(int i = 0; i < size; i++) { float temp = fabs(Ser[i] - Par[i]); if(temp > eps) {...
65,853,907
65,854,054
Why is this C++ constructor called twice at the same memory location in this implementation of a linked list?
I was reading Data Structures and Algorithm Analysis in C++ by Shaffer (available for free at https://people.cs.vt.edu/shaffer/Book/) because I saw that it uses templates and I'm trying to learn more about C++ and generic programming in C++. When the author introduces Linked Lists, he gives a variant that uses a freeli...
operator new's task is to allocate memory; it must not call a constructor. The constructor is called automatically after operator new returns. Therefore, your implementation should look like this: void * operator new(size_t size) { if (freelist == nullptr) { // here is the difference: return ::operato...
65,853,913
65,853,942
How should I do with "std::cerr" and "std::cin.fail()" using c++?
Could you please help me with the small question? Question: The program should return an error code(1) and print this exact string in case a failure is encountered: “Error encountered, exiting...” My code: #include <iostream> #include <random> int main(int argc, char const *argv[]) { int number, random; rando...
You should test std::cin.fail() after the while loop because if std::cin >> number fails, the body of the while loop will not be entered. You could also restructure the tests a bit to not have to perform the same tests over and over again. Also, std::endl flushes the output stream which is unnecessary in the vast major...
65,854,262
65,854,302
When the memory is actually allocated for new int[250000000] in C++?
I'm trying to figure out when the memory is allocated for my program. Here is my code #include <unistd.h> #include <iostream> #include <cstdlib> using namespace std; int main() { cout << "when the memory is allocated?"; cout << endl; cout.flush(); int * p = new int[250000000]; sleep(3); cout << "address: " ...
OSX is like other Unix operating systems and there is a difference between virtual memory and actually used memory. In the console program top these are called VIRT and RES (for resident). When you allocate a big block like that, the program calls the operating system to reserve virtual memory space. That memory will o...
65,854,779
65,859,642
How to use boost::beast to connect to Coinbase's websocket API
I'm a bit new to websocket programming. I've been trying to use this example :- https://www.boost.org/doc/libs/develop/libs/beast/example/websocket/client/async-ssl/websocket_client_async_ssl.cpp to connect to the coinbase websocket api over here :- https://docs.pro.coinbase.com/#websocket-feed However, I keep getting ...
So turns out I am really new to web programming. The standard TLS port is 443. Also, coinbase's TLS api requires you to only set the hostname in the SNI field and not the hostname:port Otherwise, the example worked as is!
65,855,091
65,855,158
Only one variable is printing C++
//libraries #include <iostream> //standard namepace using namespace std; int Car() { int a; int b; cout << "Fuel Tank" << endl; cin >> a; cout << "MPG" << endl; cin >> b; return a, b; } int main() { int a; int b; a,b = Car(); cout << "Print Values " << (a,b...
That's not how C++ works. You need: std:: pair<int, int> Car() { ... return {a, b}; } auto [a, b] = Car(); std::cout << a << ", " << b; What you have: int Car() Car is a function which returns 1 int. return a, b; Here you have the comma operator which evaluates every argument and discards all but the last...
65,855,404
65,855,425
error LNK2019: unresolved external symbol "public: __thiscall RNG::RNG(unsigned __int64)" (??0RNG@@QAE@_K@Z) referenced in function _main
I'm getting the above error when I build the files below, using cl.exe in VSCode. I've been staring at this code for a full day and can't see the error. I've tried a bunch of things, some irrational, to no avail. When attempting to build it I get the error: "/debug" "/out:D:\Apps_for_C++\PokerWorkspace\RNG\RNG.exe" "RN...
You have Seed static variable which needs to be defined it outside the class. unsigned long long Rng::Seed = some_value;
65,855,836
65,856,056
How to make std::getline() include last empty line?
When using std::getline to read lines from a file, I need it to pick up each blank line at the end of the file. //add each line to lines while (std::getline(file, line)) lines.push_back(line); getline() is always skipping the last blank line of a file and not adding it to the lines vector. I need the...
I think this is by design: Extracts characters from input and appends them to str until one of the following occurs (checked in the order listed). a) end-of-file condition on input, in which case, getline sets eofbit. ... If no characters were extracted for whatever reason (not even the discarded delimiter), getline s...
65,855,963
65,856,864
Concatenating lists using template metaprogramming in C++11
I've created a new type called IntList, which represents a list of integers. This was made by using templates: template<int...> struct IntList; template<int h, int... t> struct IntList<h, t...>{ constexpr static int head = h; typedef IntList<t...> next; constexpr static int size = sizeof...(t) + 1; con...
You might add this extra specialization: template<int...T1, typename...Ts> struct ConcatedIntLists<IntList<T1...>, Ts...> { typedef typename ConcatedIntLists<IntList<T1...>, typename ConcatedIntLists<Ts...>::list>::list list; }; Demo.
65,856,344
65,856,454
Switching between finite and infinite for loop based on input parameters
I want to blink an LED for a finite number of times or infinite times as per the user input. I am not sure how to switch between these two tasks. for (i = 0; i < REPEAT; i++) { //Blink LED code here } As per the above snippet REPEAT defines the number of times the LED is to be blinked. My question is how to ma...
The following code might help. for (i = 0; i < REPEAT; i++) { //Blink LED code here; if(input==0){ //Set input variable as 0 if it is an infinite loop. You can change this condition if needed REPEAT++; } } The value of REPEAT gets incremented when you increment the value of i so the loop will b...
65,856,403
65,879,115
How to store Diffie HellMan Object's Keys in PEM Format using openSSL C++
I am facing one silly issue in storing my DH Keys in PEM Format. Here is working code snippet to generate Keys in Diffie Hellman format, I can store the DH Params in PEM Format. However I don't find any function in openSSL which can store the Keys also in PEM Format. DH *privkey = DH_new(); /* Generate the parameters t...
OpenSSL has a generic function PEM_write_PKCS8PrivateKey that is capable of writing EVP_PKEY keys to a PKCS8 structure in PEM format. In order to leverage that, you would have to wrap your DH key like this, with the error checking omitted for the sake of brevity: EVP_PKEY *pkey = EVP_PKEY_new(); EVP_PKEY_set1_DH(pkey, ...
65,856,599
65,856,626
Basic C++ File Handling Problems
I am making a Course Management System. I plan to write a code that takes the input from the user about the details of the university program and store them in the file and read it. My computer firstly does not read the file and secondly does not shows the input option for entering data in school can anyone please reso...
You copied some code from somewhere wrong fbout.open("program.txt", ios::out || ios::app||ios::binary); should be fbout.open("program.txt", ios::out | ios::app | ios::binary); || is the logical or operator but | is the bitwise or operator. Take too long to explain the difference here, look them up in your C++ book. T...
65,856,904
65,857,295
Repacking a struct in C/C++
I would like to have a single definition for packed and unpacked structs. The intent is to use reflection to translate one to the other. I do this currently by redefinition for performance versus wire formatting. It is necessary to have two definitions and memberwise copy between them to stop those rude segfaults. It w...
It would be nice to not have two definitions in the spirit of DRY. From a technical point of view it’s not a question of DRY. Two stucts with the same members in the same order but different padding are two distinct types. They have nothing in common because they may have different sizes and the members may live at d...
65,857,182
65,857,213
C++ Difference between sizeof(), size() & strlen()
What are the differences between sizeof(), size(), strlen() ? In which cases I should use a certain function?
size() function is used to return the size of the list container or the number of elements in the list container. You can use this to find number of elements in an array. sizeof() is used with the data types such as int, float, char… etc it simply returns the amount of memory is allocated to that data types. The strlen...
65,857,218
65,858,154
Is there a struct function for finding the longest and not-repeating length substring within a string?
The aim of the function is to find out the longest and not repeating substring, so I need to find out the start position of the substring and the length of it. The thing I'm struggling with is the big O notation should be O(n). Therefore I cannot use nested for loops to check whether each letter is repeated. I created ...
Use a std::unordered_map<char, size_t> to store the indices past the last occurance of a certain char. Keep the currently best match as well as the match you currently test. Iterating through the chars of the input result in 2 cases you need to handle: the char already occured and the last occurance of the char requir...
65,857,929
65,858,067
Is there an easy way to combine strings as function parameter?
Let's say I have a C++ function void foo(std::string str) { std::cout << str << "\n"; } Now, in the equivalent Java I could call the function with a combination of various types and it would automatically be concatenated, for example: foo("test " + intValue + " " + stringValue + "..."); This does not work in C++,...
You can wrap std::stringstream in a function and use that: #include <string> #include <sstream> void foo(std::string){} template<typename...Args> std::string concat(Args&&...args){ std::stringstream ss; (ss << ... << args); return ss.str(); } int main(){ int intValue=12; std::string stringValue=...
65,858,429
65,858,744
Why can't I initialize a static class member in a common header file?
Suppose I have a header only library. I have simplified it to something like this. Header only library Foo.hpp #ifndef FOO_HPP #define FOO_HPP struct Foo{ static const int A; }; const int Foo::A = 100; void SomeMethod(){ // do some stuff } #endif Then, I have parent class (Parent.hpp and Parent.cpp): #ifndef...
You have chosen the "non-inline" mode of initializing your static member. That is perfectly legitimate, but - in this case, you need to have exactly one translation unit (e.g. compiled .cpp file) defining your member. Otherwise, the C++ linker sees one definition of Foo::A in parent.o and a second definition in child.o...
65,858,936
65,859,115
Accessing attribute of Object Pointer in C++
I'm stuck on a basic problem of trying to return an attribute from the an object pointer in c++. My test code is below, I created an object from class node called Mynode, it has an attribute of value int 45. I am expecting this code to return a pointer than then the value of data (45). but instead get a compile error "...
A void* is a pointer to void. void is no type. It is the absense of a type. It has no member functions that you could call. A void* can point to any object and in past times there were some use cases of void* in user code. Not anymore. If you want a pointer to a node, that is node*. Taking into account the comment on n...
65,859,056
65,859,536
Draw a 2D Quad in OpenGL
Whenever I think I understand something about openGL I find I don't understand anything. I don't understand what I'm doing wrong. The quad is not rendered. Here is how I init the data std::vector<glm::vec3> vertices; vertices.resize(6); // first triangle vertices[0] = g...
You don't see the rectangle because it's out of view. If you are not using a projection matrix, the vertex coordinates must be in the range [-1.0, 1.0]. If you want to use "window" coordinates you must use an Orthographic projection. You need to transform the vertex coordinates through the projection matrix. This is us...
65,859,618
65,860,225
Draw geometric shapes in c++ without using opengl
I'm looking for a simple library that can create and draw some geometric shapes without using openGL or directX and also have documentation.
just gdi would be enough i guess https://learn.microsoft.com/en-gb/windows/win32/api/wingdi/nf-wingdi-ellipse?redirectedfrom=MSDN
65,859,742
65,865,945
Opengl vertex coordinates for perspective projection
I need to use perspective transformation but I can't understand how to define model coordinates of sprite. If I use orthogonal projection I can define coordinate of each vertex as number pixels on screen. But with perspective projection I can't. Orthogonal projection: glm::ortho<GLfloat>(0.0f, screen_width, screen_heig...
Initially I was misunderstood difference between orthogonal and perspective projections. As I understood now all vertices mapped initially in NDC for perspective projection. Then they moved, scaled, etc with model matrix. Pixel perfect rendering can be realized only with some constant depth or with orthogonal. I't unus...
65,860,052
65,860,501
how to make template function (operator) deduce template arguments implicitly?
I have this code which I need to make it be compiled: int main () { const Matrix<int, 3, 2> m1; // Creates 3*2 matrix, with all elements set to 0; Matrix<int, 3, 3> m2(4); // Creates 3*3 matrix, with all elements equals to 4; const Matrix<int, 3, 3> m3 = m2; // Copy constructor may take O(MN) and not O(1). ...
Your questions lacks some information about what MatrixBase is, but if we just look at your Matrix class you need a template function to do this. There you can deduce the template parameters of the classes and use that to calculate the resulting type. template <typename T, int LRows, int LCols, int RRows, int RCols> Ma...
65,860,094
65,899,078
How to add Eigen library to a cmake c++ project via FetchContent
Adding Eigen via FetchContent_Declare( eigen GIT_REPOSITORY https://gitlab.com/libeigen/eigen.git GIT_TAG 3.3.9 ) FetchContent_GetProperties(eigen) if(NOT eigen_POPULATED) FetchContent_Populate(eigen) add_subdirectory(${eigen_SOURCE_DIR} ${eigen_BINARY_DIR}) endif() find_package (Eigen3 3.3 REQU...
In any order: Eigen only provide ALIAS target on master ref: https://gitlab.com/libeigen/eigen/-/commit/cf0b5b0344a3bfcf410e95bf22289015a2daf34b#9a2aa4db38d3115ed60da621e012c0efc0172aae_671_599 FetchContent usage could be include(FetchContent) FetchContent_Declare( Eigen GIT_REPOSITORY https://gitlab.com/libei...
65,860,529
65,860,931
Would it be more efficient to have the \n character in the same string literal than to have an extra set of "<<"?
I was wondering if in code such as this: std::cout << "Hello!" << '\n'; Would it be more efficient to have the \n character in the same string literal, as in this case, "Hello!"? Such as the code would then look like this: std::cout << "Hello!\n"; I am aware that things such as these are so miniscule in difference wh...
Yes; but all of the ostreams are so inefficient in practice that if you care much about efficiency you shouldn't be using them. Write code to be clear and maintainable. Making code faster takes work, and the simpler and clearer your code is the easier to make it faster. Identify what your bottleneck is, then work on o...
65,860,643
65,862,540
Passing file or stdin to boost process child ambiguously
I am trying to write a boost::process-based program that is able ambiguously redirect input, output and error streams based on whether to not a file to redirect them into is defined, but I'm struggling to figure out how to approach it: #include <string> #include <boost/process.hpp> int main(){ std::string in; std:...
Boost has chosen a notation that is intuitive to someone familiar with redirection on the command line. However, remember that this is C++. The < and > symbols are still operators; they did not become command-line arguments. The code bp::std_out > stdout is an expression. It evaluates to an object of some sort that rec...
65,860,879
65,860,952
How to get the size of datatype of an array
How to get the size of datatype of an array? For Eg. int32_t arr[10][10] datatype is int32_t and it's size is 4 bytes, similarly for char [10][100] datatype is char and it's size is 1 byte. The reason I'm asking this question is I need to know whether data has to be swapped or not before sending via network, since data...
You may be looking for sizeof(std::remove_all_extents_t<decltype(int_arr)>) Works for non-arrays, too; when given a non-array type T, std::remove_all_extents_t<T> is simply T.
65,861,096
65,861,779
How do I output the array's elements (on odd positions, that have an odd amount of even digits?
If I have 4 elements, in this order: 4 10 2546 and 100, 4 and 2546 are on odd positions, 4 has 1 even digit and 2546 has 3 even digits, so the output should be "4 2546", however my program only outputs "0 0", and I think it's because of the while loop, but I don't know how to fix it. #include <iostream> using namespac...
You made a small typo. In the cout statement you your showing the value of x, which has been made 0 by the divisions. You need to show the original valeu, stored in v[i]. So, please modify you cout statement to: cout << v[i] << " ";
65,861,280
65,863,170
Convert std::string to std::wstring and vise versa
I've been reading quite a lot about how to convert between std::string and std::wstring but all the answers I have found was very old. I tried using std::codecvt to convert but it gives a warning stating that it is deprecated and use WideCharToMultiByte() and MultiByteToWideChar() using the Windows.h header file. But t...
std::wstring holds wchar_t elements, and wchar_t is a different size across platforms (2 bytes on Windows, 4 bytes elsewhere), and as such std::wstring uses different encodings across platforms (UTF-16 on Windows, UTF-32 elsewhere). Just as std::string can hold different 8bit encodings (UTF-8, ISO-8859-x, Windows-125x,...
65,861,488
65,864,545
Problem on declaring friend function with type traits in a class
I'm playing around with the singleton pattern in C++, and want to implement an global function that completes the construction of a class. I used std::is_base_of in that function, but that makes it impossible for me to declaring the function in the class. Here's a short example: #include <type_traits> class A {}; temp...
Issue is that during definition of class, the class is still incomplete, and std::is_base_of required complete type for Derived, else you have UB. If you have access to C++17, you might do: template<typename T> T* Instance() { if constexpr (std::is_base_of_v<A, T>) { return nullptr; // Your impl } else ...
65,861,564
65,863,321
Is using erase(it) in a loop always safe for all containers and platforms?
i want to remove elements within a container(for now it is unordered_set) by certain condition for (auto it = windows.begin(); it != windows.end(); ) { if ((*it)->closed() == 0) it = numbers.erase(it); else ++it; } i know the erase(it) will return the position immediately following the last of ...
The C++ standard requires that unordered_set::erase preserve the order of remaining elements, and return an iterator immediately following those being erased. Therefore, the loop you show is well-defined. [unord.req]/14 ... The erase members shall invalidate only iterators and references to the erased elements, and pr...
65,861,630
65,861,909
Why does an inline user-provided constructor odr-uses base class constructors?
Consider the following illustrative example #include <iostream> template <typename> struct Base { static int const touch; Base() { (void)touch; } }; template<typename CRTP> int const Base<CRTP>::touch = []{ std::cout << "Initialized!\n"; return 0; }(); struct A : Base<A> { A() {} }; ...
This happens for any inline definition that odr-uses Base<T>::Base, for example: inline void x() { Base<char>(); } struct A : Base<A> { A(int) {} void x() { Base<int>(); } }; struct C : Base<C> { C(); }; inline C::C() = default; // See [1] // Will print "Initialized!" four times B() = ...
65,862,011
65,864,318
get total number of elements in a multidimensional array using std::extent
How to find total number of elements in a multidimensional array using std::extent. This is my sample code: #include <iostream> #include <type_traits> int main() { int32_t int_arr[10][100][1000]; int32_t no_of_elements = 1; // compiler error in below for loop block for (int32_t i = 0; i < std::ran...
With C++14 std::index_sequence, you can use std::extent with something like: template <typename T, std::size_t... Is> constexpr std::size_t count_elements(std::index_sequence<Is...>) { return (1 * ... * std::extent<T, Is>{}); // C++17 fold expression // Alternatives exis...
65,862,347
65,862,634
C++ argument of type "char" is incompatible with parameter of type "char(*)[7]"
I've followed steps that were all required so far for a school project and I am getting these two errors ( C++ argument of type "char" is incompatible with parameter of type "char(*)[7]" and 'void boardInit(char [][7])': cannot convert argument 1 from 'char[][7]' ) when trying to call my function to make sure the a...
There is a typedef that makes saying Board board equivalent to saying char board[BOARD_SIZE][BOARD_SIZE]. Imagine you didn't have the typedef, the function prototype would be: void boardInit(char board[BOARD_SIZE][BOARD_SIZE]); If you had declared as char board[BOARD_SIZE][BOARD_SIZE], how would you call that function ...
65,862,525
65,862,966
How to use a C++ library method in a visual studio project
I'm trying to test a method from a static library that I created. The method from the library just prints something to the console. I have added the directory in the properties tab and added the linker input. However, the project still does not recognise the library. Would anyone be able to help. Any help is appreciate...
There seemed to be an error in my linking of the path to the library where I didn't include the library .lib. Only include the path and not the path and lib file in the directory.
65,862,777
65,863,054
Qt - how to emit a signal from derived class?
In my custom derived class I'm trying to add and emit a signal gotChange(QString change): #ifndef NETTEXTEDITOR_H #define NETTEXTEDITOR_H #include <QTextEdit> class NetTextEditor : public QTextEdit { using QTextEdit::QTextEdit; public: void keyPressEvent(QKeyEvent *e) override; signals: void gotChange(QS...
If you want to create signals or slots then you must use the macro Q_OBJECT in the private section. Then you can run "run qmake" (or simply delete the build folder) and compile the application
65,862,909
65,863,084
Printing method from class type list in C++
In main() i try to create a list from class movieTorrent, push object from the same type and use toString() method to print it. But it only prints the variables from child class. Where i am wrong? So, i have this base class: class Torrent { public: string title; int size; string uploader; int downloads;...
TL;DR version: Remove the copy constructors. They are not necessary for classes that have no members that require special resource handing (See Rule of Three/Five/Zero.) Explanation movieTorrent(const movieTorrent &mT) { director = mT.director; duration = mT.duration; language = mT.language; } doesn't invo...
65,863,042
65,863,599
Getting FILE* in a safe C++ way
Is there a way to obtain the FILE* handle of an opened file in a modern C++ way?.. I want to avoid using std::fopen from <cstdlib> as I've been warned that it's potentially unsafe. I tried checking if there's a way to retrieve FILE* from fstream but it seems there isn't a way to do that.
I want to avoid using std::fopen from <cstdlib> as I've been warned that it's potentially unsafe. There is nothing "unsafe" about fopen(). It is part of the C++ standard by means of the C standard. What they probably said is that using a RAII object is best to manage the resource (the file handle), in particular if y...
65,863,131
65,863,274
Deforming a shape when resizing an OpenGL window
I draw an object using a shader program and a VAO But when I deform the window, my figure also deforms. My vertex shader doesn't do anything, the fragment shader only sets the color orange. vertshader.vert #version 330 core layout (location = 0) in vec3 aPos; void main() { gl_Position = vec4(aPos, 1.0); } gl ini...
You mix the deprecated OpenGL matrices with "modern" OpenGL. gluOrtho2D has no effect when you use a shader program. You must use a matrix Uniform variable. Add a Uniform variable of type mat4 to the shader program and multiply the vertex coordinates by the matrix: #version 330 core layout (location = 0) in vec3 aPos;...
65,863,428
65,863,937
'invoke': no matching overloaded function found
Trying to make an organized "announcement" message-board with multi-threading. One thread reads messages and calls the other thread to send said messages to connected users. I'm not entirely sure why the std::thread constructor fails to compile. I've tried ref()ing everything, didn't work. I've tried ref()ing only the ...
sendMessages takes a std::ofstream by value, as std::ofstream is not copyable, even without std::thread you can only call it with a temporary or r value. For example this won't compile: MessageHandler::sendMessages(MenuVariables::messages, MenuVariables::usernames, outputFile); but either of these will: MessageHandler...
65,863,883
65,892,835
error while returning begin pointer of an iterator
I am trying to compile the QSLIM tools on Ubuntu 18.04 (C++) for mesh simplification (http://mgarland.org/software/qslim.html), and for this, I am following the steps in https://github.com/alecjacobson/qslim/issues/2 . When I arrive to the step : cd ../mixkit/ make -C src I'm getting the following error: MxDynBlock.h...
as proposed by Kao in the comments, I added MxBlock:: before begin()
65,864,119
65,864,295
c++ reference to a class member but not changing value
Please help me to review the following code. I am wondering why the variable "b" is not the modified value. I can not change the value using reference ? Thanks! #include <iostream> using namespace std; class Foo{ public: int a = 1; int& check(){ return a; }; }; int main() { ...
As @Igor Tandetnik indicated, foo.check returns a reference, but b is an int, not a reference to int, so it keeps the original value. What you want can be achieved by ... #include <iostream> using namespace std; class Foo { public: int a = 1; int &check() { return a; }; }; int main() { Fo...
65,864,208
65,864,332
How to detect a pointer to an arithmetic type using type traits and concepts?
How do I write a concept that detects a pointer to an arithmetic type? template <typename T> concept arithmetic = std::is_arithmetic<T>::value; template <typename T> concept pointer_to_arithmetic = requires (T a) { { *a } -> arithmetic; }; template <typename T> void fn() { printf("fail\n"); } template <po...
For an expression E in a compound requirement, the type constraint predicate is fed decltype((E))1. decltype encodes the value category of the expression in the type it deduces. Since *p is an lvalue expression. The deduced type is T& for some T. So you may want to rewrite your pair of concepts as template <typename T>...
65,864,801
65,864,850
Recursive vector return
I already created a function which recursive calling itself to add new elements to vector until vector.size() < 4 and when vector.size() == 4 function returns this modified vector with 4 elements. However I'm can't figure it out how to modify the code below to get the same result without passing a vector in first call ...
You might do: std::vector<int> func(std::vector<int> vec = {}) { if (vec.size() < 4) { vec.push_back(vec.size() + 1); vec = func(std::move(vec)); } return vec; } Demo
65,865,692
65,865,840
Running powershell script through the system command - output creates a file that is empty
I am attempting to run a powershell script through the system command. This is the code I am using status = system("start powershell.exe Set-ExecutionPolicy RemoteSigned \n"); status = system("start powershell.exe D:\\foo\\tempFilePShellCommand.ps1 > D:\\foo\\MyFile.txt"); Now the problem with the above code is that...
You need to specify that the parameter is a file. Otherwise, it is treated as a parameter to "PowerShell.exe" instead of a file you want to run using PowerShell. status = system("start powershell.exe -File D:\\foo\\tempFilePShellCommand.ps1 > D:\\foo\\MyFile.txt");
65,865,726
65,865,751
How compilers identify the length of byte shift operators
Consider the following line: int mask = 1 << shift_amount; we know that mask is 4 bytes because it was explicitly declared int, but this 1 that to be shifted has unknown length. If the compiler chose type as char it would be 8 bits, or it could be unsigned short with size 16 bits, so shifting result will really depend ...
1 is an int (typically 4 bytes). If you wanted it to be a type other than int you'd use a suffix, like 1L for long. For more details see https://en.cppreference.com/w/cpp/language/integer_literal. You can also use a cast like (long)1 or if you want a known fixed length, (int32_t)1. As Eric Postpischil points out in a...
65,866,601
65,866,771
Why postfix increment is conducted at last in a condition evaluation?
GDB shows the obj->start_point is incremented after the whole evaluation >=. But C Primer Plus told me ++ has the higher precedence than >=. So why the obj->start_point doesn't increment first? Is the book wrong? if (obj->start_point++ >= obj->data + obj->data_size) {
Precedence only controls the grouping of operators with operands, not the order in which expressions are evaluated. The side effect of the ++ operator does not have to be applied immediately after evaluation, it only needs to be applied before the next sequence point. Edit You can certainly look at the generated assemb...
65,866,926
65,872,557
Why is my shared library (dll) not getting linked with the stdc++-6.dll properly?
So I was trying to build and load a dll into a Java application using the Jni interface, and basically I've used a few libraries consisting of the Win32 API. The build seems to be fine, everything built and linked. But I'm not able to figure out how is the stdc++-6.dll is not getting dynamically (shared) linked properl...
So I finally figured out the problem, special thanks to @zero9178 which helped me alot. I actually had 32-bit version of the libstdc++-6.dll on the PATH which was installed by the official build of MinGW so adding a 64-bit from other sources seems to work. I had only the new keyword depends on that library as I used to...
65,866,927
65,867,030
C++ remove by index a value within a vector of pointers
I'm trying to allow my code structure to just add and remove SDL_Textures* so that I don't have to manually add an offset or draw it, rather it all handled by my class Screen_Object. My declaration is std::vector < SDL_Texture* > m_Textures;. I have this other method that allows me to alter the std::vector but it won't...
Change: m_Textures.erase(i, 1 ); m_Texture_Rects.erase(i, 1 ); to: m_Textures.erase(m_Textures.begin() + i); m_Texture_Rects.erase(m_Texture_Rects.begin() + i); erase expects an iterator, not an integer.
65,867,007
65,867,132
How does this statement check "T cannot be compared to nullptr"?
static_assert( std::is_convertible<decltype(std::declval<T>() != nullptr), bool>::value, "T cannot be compared to nullptr."); Source: https://github.com/microsoft/GSL/blob/master/include/gsl/pointers Specifically: What would the result of decltype(std::declval<T>() != nullptr) be, if T really cannot not be compar...
If T cannot be compared to nullptr, the whole thing is ill-formed. https://godbolt.org/z/eqehez #include <type_traits> template<typename T> void foo() { static_assert( std::is_convertible<decltype(std::declval<T>() != nullptr), bool>::value, "T cannot be compared to nullptr."); } int m...
65,867,148
65,867,201
Is template type of a std::function detached by std::bind an undefined behavior?
i am working on MSVC static bool filter_entity(void* entity) { return entity == nullptr; }; template<typename F> static bool Dispatch(const F& filter) { return filter(nullptr); }; int main() { void* ptr = new int(); if (Dispatch(std::bind(&filter_entity, ptr))) cout << "nullptr" << endl; else cout <...
From cppreference.com: If some of the arguments that are supplied in the call to [the bound object] are not matched by any placeholders stored in [the bound object], the unused arguments are evaluated and discarded. The bound object from the question has no placeholders. So the nullptr in return filter(nullptr); is ...
65,867,634
65,867,787
Is this the right approach to count the number of base class objects created when there is a partial virtual inheritance involved?
From what I have learnt about virtual inheritance, whenever we have a class A (the base class), classes B, C, D (all these three virtually inherit class A) then if there is a class derived which inherits from B, C and D classes is instantiated then only a single object of class A would be created. I tried to reason abo...
From the content written in the cppreference website it is indeed the case: See the first example under the virtual base classes section.
65,867,889
65,868,141
Define shortcut with multiple letter in Qt C++
I define a shortcut using following Qt C++ code: QShortcut *shortcut = new QShortcut(QKeySequence("Ctrl+Shift+S"), this); QObject::connect(shortcut, &QShortcut::activated, [=]{qDebug()<<"Example";}); How I can define shortcut with multiple letter, for example Ctrl+Shift+S+D+F. If the user hold Ctrl+Shift and press S, ...
AFAIK, QShortcut currently does not support the feature you are described. A workaround is to install an event filter yourself. #include <QCoreApplication> #include <QKeyEvent> #include <QVector> class QMultipleKeysShortcut : public QObject { Q_OBJECT public: explicit inline QMultipleKeysShortcut(const QVect...
65,867,950
65,869,260
How to delete subclass pointer where use parent pointer as formal parameters in function?
I meet a question when I delete subclass point. I want to delete subclass pointer use parent class pointer as formal parameters. And there is my code likes follows. class Test { public: virtual ~Test() = default; int a =10; }; class TestChild : public Test { public: int c ; }; class A { public: A(){ ...
What do I need to do to make my code work? You could make function templates to support delete and delete[] + setting the pointer to nullptr: template<typename T> void delete_and_nullify_single_element_pointer(T*& ptr) { delete ptr; ptr = nullptr; } template<typename T> void delete_and_nullify_array_pointer(...
65,868,079
65,868,413
Unexpected behaviour by pointer (when manipulated) but defined behaviour when using a double pointer
I'm quite confused about the reasoning behind the behaviour of pointers to a variable. I would have thought that if I append a pointer to a vector and access it, whether I changed the pointer itself it should still work the same upon the same variable. What I mean by this is, for example, I have a vector of integer poi...
The issue seems to be that you are storing pointers in the vector, but outside the vector you are invalidating the pointer. void Screen_Object::Add_Texture(SDL_Texture* p_Texture) { m_Textures.push_back(p_Texture); } void Main::Mainloop() { Screen_Object m_Screen_Object; //... SDL_Texture* tex = SDL_Cr...
65,868,264
65,868,538
HTTP Headers and Data response, how to decode % in data?
I am producing a HTTP response from an Qt 5.15.2 application, the response is typically something like: HTTP/1.1 200 OK Server: XMLMPAM Access-Control-Allow-Origin: * Date: Sun, 24 Jan 2021 07:56:45 GMT Content-Length: 65 Connection: Closed Content-Type: text/html; charset=utf-8 <!DOCTYPE html><html><body>{%22msgType%...
Solved: QString strWrapper("<!DOCTYPE html><html><body>" + QUrl::fromPercentEncoding(arybytData) + "</body></html>") ,strDateTime(dtUTC.toString("ddd, dd MMM yyyy hh:mm:ss") + " GMT") ,strDataLength(QString::number(strWrapper.length())) ,strHTTP; strHTTP = QString("HTTP/1.1 200 OK%1" ...
65,868,463
65,868,539
can't open the serial port from qt
I am working on a project where I have to write to an read from a serial port. I have written the following code, but I am getting the message "can't open the port" in my else statement. When I use hercules, I can open the "COM1" port. But I don't know why can't I open this port via my QT program. code: widget.h: #ifn...
You do open two times, I guess second one should be isOpen
65,868,819
65,870,364
to lexicographically compare kth word from two strings
I m trying to write a c++ function to lexicographically compare kth word from two strings. here is my function : bool kth_lexo () { int k = 2 ; str1 = "123 300 60009" ; str2 = "1500 10002" ; // to store the kth word of fist string in ptr1 char *ptr1 = strtok( (char*)str1.c_str() ," "); for(int i =...
If you would stop using C and consequently use C++, then this problem would not occur. You are here mixing up C++ std::string and char* or const char*. Basically, for strings, std::string is that superior to the old style C-char-arrays or char* that you from now on and in the future should never use something else than...
65,869,539
65,869,915
async and promise - is this correct usage?
I am learning multithreading and I have found one example which bothers me. (I am not the author of this code). #include <iostream> #include <future> using namespace std; void testFunc(std::promise<int> &result, std::promise<bool> &done) { // other... result.set_value(10); done.set_value(true)...
For this example, it would certainly make more sense to return a value in the lambda provided to std::async. In general, futures and promises are meant to facilitate asynchronous programming. Where waiting should typically be avoided or at least reduced. To avoid waiting altogether, you could use the experimental std::...
65,869,563
65,870,824
Cannot compile c++ program including filesystem
I have written a very simple c++ program: #include<filesystem> using namespace std::filesystem; int main(){ return 0; } At first, I compiled it with g++ -c main.cpp -o main.o and got following errors: main.cpp:2:22: error: 'filesystem' is not a namespace-name using namespace std::filesystem; ^...
no match for 'operator!=' (operand types are 'std::filesystem::__cxx11::path' and 'std::filesystem::__cxx11::path') this is a bug in mingw 8.1.0. the bug report: https://sourceforge.net/p/mingw-w64/bugs/737 This is fixed in version 9.x, you need to upgrade mingw to a newer version (9.0+)
65,869,810
65,870,156
Is possible to "skip" needed class?
I'm newbie in C++ and I have no idea how to put it in google to search but, i have code: player: class Player { public: bool armor_set[4]; short int protection; void EquipArmor(short int, Armor); }; void Player::EquipArmor(short int armor_slot, Armor armoridx) { this->armor_set[armor_slot] = true; ...
You could remember the values in armor_set itself when equipping the armor pieces. Either just convert it to short armorset[4] and have a special value, probably 0, for denoting the armor is not equipped. EquipArmor will write the value there, instead of just setting it to true. Or the if Armor.addingarmor can have any...
65,870,420
65,870,493
Why do I always generate the same addresses even though I use new?
I have code like this. here is my Sayi class, class Sayi{ private: int deger; public: Sayi(): deger(0){} Sayi(int dgr): deger(dgr){} int Deger() {return deger;} }; and here my main, int main(){ Sayi *s1, *s2; s1= new Sayi(50); s2=s1; delete s1; ...
There is no requirement that new returns a new address. All it has to do is return an address that's different from any existing object. That's what it's doing in your program. s4 is different from s3 because s3 is still pointing at a valid object when you create s4. s3 is allowed to be the same as s2 because s2 is not...
65,870,951
65,871,123
Failed resolution of variadic parameter types with post-positioned std::index_sequence
Assume a sequence of variadic parameter types is to be generated according to a index sequence, i.e, given a tuple using Tuple = std::tuple<int, float, bool>; and a function signature as following: template <std::size_t ...Is> void func(std::index_sequence<Is...>, std::tuple_element_t<Is, Tuple>...) {} a invocation ...
Write a "is prefix of types" trait. Use it in a requires clause. template<class T0> struct is_tuple_prefix_helper{ template<class T1> static std::false_type test(T1 const&); }; template<template<class...>class Z, class...T0s> struct is_tuple_prefix_helper<Z<T0s...>>{ template<class T1> static std::fals...
65,870,961
65,883,025
Getting an error building static libcurl VS2019
First I make nmake work: set PATH=%PATH%;C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\VC\Tools\MSVC\14.28.29812\bin\Hostx64\x86 then I git clone https://github.com/curl/curl.git --depth=1 Then I run buildconf.bat all seems fine. then I go to winbuild and run nmake /f Makefile.vc mode=static and the buil...
If your ultimate goal is to "Get a static library compiled with a local cl compiler", I suggest you try the "vcpkg". All you have to do is "vcpkg install curl". It will download the source code and compiled locally. :)
65,871,105
65,871,156
Why is it not possible to define a static (public) member of a class in the main() function?
Why is it not possible to define a static member of a class in the main() function in C++? Consider this code: #include <iostream> using namespace std; class A { public: int a; static int b; A() { // int A::b = 1; } void fun() { // int A::b = 1; } }; int main() { ...
Why is it not possible to define a static member of a class in the main() function in C++? C++ is a statically typed language. That is: the "shape" of all "things" (struct, class, functions, etc) must be known in-advance by the compiler (i.e. statically) - and due to historical reasons C++ requires all type-names and...
65,871,203
65,871,415
How to relate to button created in SFML-IMGUI?
Hello I want to create some buttons with SFML-IMGUI and after that relate to them in some way for example to change text. How can I do this? I dont see any ID attribute. I create button using this code. ImGui::Begin("Button"); Button("Click me"); End(); I dont see any example in documentation :/
Imgui buttons don't use any id or callbacks. Instead, the ImGui::Button("Clikc me") will return a boolean which is true if the button was clicked. (here is an example) ImGui::Begin("window"); if (ImGui::Button("Click me")) { // onButtonClick(); } ImGui::End(); for more read https://github.com/ocornut/imgui/tree/...
65,871,288
68,059,701
Different machine code for empty default constructor v. implicitly-defined one
Given the following struct... #include <type_traits> struct C { long a[16]{}; long b[16]{}; C() = default; }; // For godbolt C construct() { static_assert(not std::is_trivial_v<C>); static_assert(std::is_standard_layout_v<C>); C c; return c; } ...gcc (version 10.2 on x86-64 Linux) with ...
While I agree that this seems like a missed optimization opportunity, I noticed one difference from the language level perspective. The implicitly-defined constructor is constexpr while the empty default constructor in your example is not. From cppreference.com: That is, [the implicitly-defined constructor] calls the ...
65,871,948
65,872,128
Same random numbers in C++ as computed by Python3 numpy.random.rand
I would like to duplicate in C++ the testing for some code that has already been implemented in Python3 which relies on numpy.random.rand and randn values and a specific seed (e.g., seed = 1). I understand that Python's random implementation is based on a Mersenne twister. The C++ standard library also supplies this i...
You can do it this way for integer values: import numpy as np np.random.seed(12345) print(np.random.randint(256**4, dtype='<u4', size=1)[0]) #include <iostream> #include <random> int main() { std::mt19937 e2(12345); std::cout << e2() << std::endl; } The result of both snippets is 3992670690 By looking at s...
65,871,998
65,872,138
Static_cast no matching function for call
Could you please explain work of static_cast? Why this code doesn't work? D another_d = static_cast<D>(br); // ERROR - no matching function for call to ‘D::D(B&)’ My code #include <bits/stdc++.h> using namespace std; struct B { int m = 0; void hello() const { std::cout << "Hello world, this is B!\n";...
B br = d; // upcast via implicit conversion This is object slicing. br is an instance of B and copies only the B part of d. (This implies down-casting of d to B& which the compiler can do implicitly because D is derived from B.) D another_d = static_cast<D>(br); This is the attempt to create an instance of D from an ...
65,872,341
65,872,687
Why is a virtual function in a derived class also virtual?
Is there a good reason why a virtual function is virtual by default in a derived class and it is not even possible to remove virtuality completely in the derived function? The reason why I want this behaviour is the same reason I do not want every function to be virtual by default. The compiler might generate vtables w...
I think you are confused about what a vtable does. A vtable for a class C deriving from B basically maps functions specifiers to function pointers for class C. So if you do B* ptr = new C; ptr->foo(); we have to look up at runtime, which function to call. In the end, we need a function pointer to C::foo since B cannot...
65,872,347
65,873,375
How to get single characters from unicode string and compare, print them?
I am processing unicode strings in C with libunistring. Can't use another library. My goal is to read a single character from the unicode string at its index position, print it, and compare it to a fixed value. This should be really simple, but well ... Here's my try (complete C program): /* This file must be UTF-8 enc...
'あ' and 'é' are invalid character literals. Only characters from the basic source character set and escape sequences are allowed in character literals. GCC however emits a warning (see godbolt) saying warning: multi-character character constant. This is a different case, and is about character constants such as 'abc'...
65,872,541
65,872,580
Should C++ attribute names be wrapped in double-underscores?
To tell the compiler to exclude a function from the address sanitizer, the documentation for both gcc and clang say to use an __attribute__ called no_sanitize like this: __attribute__((no_sanitize("address"))) void hidden_from_sanitizer(); But in the wild (e.g. Facebook's folly library), it seems this attribute is cal...
GCC documentation says: You may optionally specify attribute names with ‘__’ preceding and following the name. This allows you to use them in header files without being concerned about a possible macro of the same name. For example, you may use the attribute name __noreturn__ instead of noreturn. So you can use the d...
65,872,643
65,872,678
Store array of objects in its own class c++
I'm new to c++ and i'm trying to make a simple game engine. I am trying to make a game object and component system. I have a base class for all object and I am trying to store all children of the object in an array inside the class. But i get an error when trying to make an array of the class inside the class. class Ob...
Object children[] is a fixed size array. For these types of arrays, the size needs to be known at compile time or else an error will be flagged by the IDE (the compiler might ignore it as the size of it is 0 but would flag a warning). You cannot do Object children[some_amount] as till be an incomplete type. So your opt...
65,872,649
65,872,910
inserting node at ith position in linked list recursively
would help me to solve this problem i am trying to insert the node at ith location in linked list using recursion here is the code please help me to imporve the code i ma specifically facing problem at the end when i have to return the head i am not getting how to return Node* insertNodeRecursively(Node*head, int n, in...
So I guess you want the function insertNodeRecursively to return the new head, right? Anything else would not work without considering the special case of inserting at position 0 in the caller function. You could do the following: if (n == 0) { Node *newNode = new Node(data); newNode->next = head; return ne...
65,872,700
65,872,768
What's the right way to count the thread run time?
Like this: thread t1(getPrimes,begin,end, ref(vect)); start = chrono::high_resolution_clock::now(); t1.join(); finish = chrono::high_resolution_clock::now(); Or like this: start = chrono::high_resolution_clock::now(); thread t1(getPrimes,begin,end, ref(vect)); t1.join(); finish = chrono...
The beginning of a new execution thread is sequenced only with the completion of std::thread's constructor. In the first version, the entire execution thread could theoretically run and finish before the original execution thread calls now() for the first time. C++ gives you no guarantees whatsoever that the execution ...
65,873,079
65,873,146
Difference between final class and override final
The question is pretty simple, what's the difference in using final like this, class Base { public: Base() {} virtual ~Base() {} virtual void Initialize() {} }; class Derived final : public Base { public: Derived() {} ~Derived() {} virtual void Initialize() override {} }; And using override ...
The first case locks the class. The following would cause an error: class Derived2 : public Derived{}; The second forbids any class that inherits from it to redefine the finalmethod.
65,873,185
65,873,470
Tree Traversal: From Leaf to leaf and then up to the root
Even though I am programming for quite some time I have to admit that I am struggling to come up with an algorithm that traverses a tree from leaf to leaf and then up, like this (the direction in which the inner nodes are traversed doesn't actually matter, 4 and 5 can be switched if necessary): My setup at the moment ...
Make a BFS Each node you take out of the queue you push_back into a vector. Traverse the vector in reverse order. Basically something like this: queue<Node> q; vector<Node> answer; q.push(root); while(!q.empty()) { Node first = q.front(); answer.push_back(first); q.pop(); for(every NODE reachable from...