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,496,194
65,497,126
Do two classes declarations differing from a friend class make an ODR violation?
Consider a.hpp class foo{ int c; }; and b.hpp class bar; class foo{ friend bar; // from here identical to a.hpp int c; }; Is it, strictly speaking, an ODR-violation?
Yes. ODR is clear, from cppreference (emphasis mine): There can be more than one definition in a program of each of the following: class type, [...], as long as all of the following is true: [... some other points...] each definition consists of the same sequence of tokens [...] [...] The first token in class foo d...
65,496,308
65,496,377
How can you loop through your own class and print them?
#include <iostream> #include <string> #include <vector> class Enemy { public: std::string type; }; void add_enemy(std::vector<Enemy>&enemies, Enemy enemy); int main() { Enemy nrone, nrtwo, nrthree, nrfour, nrfive; // I want to add these and keep them in a vector std::vector<Enemy> enemies; ...
You need a ostream function that takes your class. Try adding friend function for this to your Enemy class. class Enemy { public: std::string type; friend std::ostream& operator<<(std::ostream& os, const Enemy& enemy) { os << "type: " << enemy.type; return os; } };
65,497,257
65,497,310
C++: why is iter++->empty() legal?
Exercise 4.20 of C++ Primer, 5e asks whether the expression iter++->empty(); is legal. Assume that iter is a vector<string>::iterator. This expression is legal. I compiled it with gcc, and the answers to another question on Stack Overflow have addressed this much. However, I'm confused as to why it is legal. This answe...
Per cppreference, ++ and -> have the same precedence and have left to aright associativity. That means that iter++ is executed first, and then ->empty() is applied to the result of iter++, which is just iter (from before the increment) since it is postfix increment.
65,497,431
65,497,503
Why is my unsigned long long int which is within 8 bytes is outputting an error?
I am using the MinGW c++ compiler and trying to execute the following line: unsigned long long unlli = 18446744073709551615; the range of the unsigned long long int it 0-18446744073709551615 I don't understand why I am not able to make full use of it, even if I go below 18446744073709551615 it still outputs the error: ...
Without suffix the type of integer literals is (cppreference): int long int long long int (since C++11) You get the warning because the value is too large to fit into a long long int. Use the ull suffix for an unsigned long long: unsigned long long unlli = 18446744073709551615ull;
65,497,539
65,497,780
last input not working after exiting the while loop
just curious on how to fix this minor issue for cin. int main(){ int x,w; while(cin>>x){ cout<<"This is x -> " << x << endl; } //now this cin will not be executed cin>> w; cout<< "This is w -> "<< w << endl; //prints some garbage value for w } the last cin is being skipped, a...
When you exit from the while by entering an incorrect data type (non-numeric input), you need to remove the invalid input from the stream. You can do it like this: while(cin >> x){ cout << "This is x -> " << x << endl; } std::cin.clear(); std::string str; // read the invalid input from stream in some string 'str' ...
65,497,542
65,508,968
Why afl-g++ can't compile ImageMagick?
I'm trying to experiment some fuzz testing with the tool afl (link). I downloaded the source code of ImageMagick as described in the docs, but when I try to run ./configure with the afl compiler I get an error: $ CC=/usr/local/bin/afl-gcc CXX=/usr/local/bin/afl-g++ ./configure --disable-shared [...] checking whether we...
It turned out that the problem was the absence of g++ in my system. Probably that's because I have installed the minimal version of Ubuntu 20.04LTS. I installed g++ with sudo apt install g++ and now everything seems to work.
65,497,576
65,497,846
C++ - Why isn't this structure of diamond inheritance cause an ambiguity?
I have scanned through dozens of multiple inheritance question but wasn't able to find an answer for this question. I understand why this won't compile: struct B{ virtual void f(){ printf("B"); } }; struct C1 : virtual B{ void f() override{ printf("C1"); } }; struct C2: virtual B{ v...
Because C1::f1 overrides B::f1, it will be used in preference on any object that has a dynamic type of C1 or any subclass. In the ambiguous case, While both C1::f1 and C2::f1 override B::f1, they do not override each other, so the ambiguity is between them -- the fact that they both override a common base function is i...
65,497,683
65,497,707
C++ Templates: Do they create a new object and destoy them at the end of the function / method?
I am trying to write a generic template method that renders a simple Rectangle to the screen using an object with the needed members. However, i noticed that the destuctors keeps being called. Now for this, it is not so much a problem, but for other templates I have in mind, it would (textures for example). So does a t...
If T is an object type (e.g. a class or a struct), then indeed T thisObject does take a value copy. Did you want void renderRect(const T& thisObject, int red, int green, int blue, int alpha)?
65,497,717
65,498,161
How to install a C++ library (such as Blitz++) in a specific directory (in one that doesn't require sudo privileges), on Linux?
I tried looking at some links on this site. The closest I found to my problem was this one, but still I wasn't able to solve my problem with it I'm kind of new at this but basically, I intend to install the Blitz++ library for C++, on Linux Now, I've already done this once, by following the instructions of their GitHub...
This is really a CMake question. Your looking for CMAKE_INSTALL_PREFIX. An example: mkdir build # Inside the cloned Github repo cd build cmake -DCMAKE_INSTALL_PREFIX=<directory_path> .. make lib make install
65,497,762
65,497,851
Issues with templated methods used with templated function pointer to an inherited method
I can't seem to figure out what is going on with a particular templated method. A similar templated method has been in my codebase for a while now and has been used in an identical manner as Bar::Bar(IFoo&), the only difference being that the function being passed in is inherited. I have an interface IFoo which defines...
As the error says, the type of Bar::setValue is actually bool (Parent::*)(int). This interferes with the template parameter deduction for doSomething because it has two Ts that need to be the same. You can help the compiler with the deduction by casting this: int main() { Bar b; IFoo foo; foo.doSomething(&B...
65,497,854
65,497,916
Calling function from different threads is blocking?
I have a class Animal class Animal { public: int operator()(const int n=4) { // do something that takes a while(~1 ms) return n*5; } }; If I spawn off two threads that each have access to one instance of Animal, will the function ...
Yes, unless that function does something (e.g., hold a mutex) to prevent parallel execution, it's entirely possible for it to execute in multiple threads simultaneously.
65,498,290
65,503,791
How to pass parameters from UWP app to pure C++ console app?
I have a UWP app that launches a C++ console app (not a Windows runtime component or anything related to UWP). I need the UWP app to pass a file path to the C++ console app so the console app can process it. For reference, I followed these blog posts: https://stefanwick.com/2018/04/06/uwp-with-desktop-extension-part-1/...
Referring to the document, you could configure your pure c++ console app with the Microsoft.Windows.CppWinRT NuGet package to enable the c++ console app use C++/WinRT APIs, so that you can get the parameters by using ApplicationData API in C++ console project. Please check the following steps for your c++ console proje...
65,498,346
65,498,917
Forcing instantiation of all of a template classes member functions
During initial development of a template class, before I've written full test cases, I am finding that I would like the ability to force the compiler to generate the code for every member (including non-static ones) of a template class for a specific set of template parameters, just to make sure all the code at least c...
Just explicitly instantiate the class: template struct test_me<int>; template struct test_me<float>; Demo
65,498,411
65,498,526
An error in accessing a data member of a union
I keep getting an error message "error: incompatible types in assignment of 'const char[7] to [30]" when accessing the employee name. I know that only one data member of the union can be accessed at one time. Please, help. Thank you! Here is my code: #include <iostream> #include <string> using namespace std; union emp...
The problem isn't that the object is a member of a union. The problem is that you're trying to assign an array. And arrays are not assignable. To modify an array, you must assign its elements. There are standard functions for copying multiple elements between arrays.
65,498,688
65,498,981
Extract signature from callable type
I have a value which is of type std::variant<char, int, double>. In fact, I have several values stored in a std::vector<value>. I want to be able to pass these values to several callback functions, if their signature matches the types of values. Here is my implementation: using value = std::variant<char, int, double>; ...
At least for your described use cases, what you want can be achieved by adding additional callback constructor templates. template<typename... Args> callback(void (*fn)(Args...)) : callback(callable<Args...>(fn)) {} This constructor will match an argument that can decay to a function pointer, e.g. this constructor ...
65,499,276
65,499,381
How to group typedefs (using declarations) and constants common to a bunch of classes and using them inside?
I am trying to find a way to group the main types and constants used by my project into a namespace, and then I'd like to import them in all my classes with "using namespace". I can't figure out why this piece of code doesn't compile, g++ error says: expected nested-name-specifier before 'namespace' What options do I ...
The language doesn't actually allow you to import a namespace at class scope. You can solve this by adding another level of indirection, viz. wrapping your class in a namespace, where you can of course import other namespaces. namespace Indirection { using namespace Traits; // ok at namespace scope ...
65,499,297
65,500,854
Haskell runs incredibly slow compared to C++
I have an assignment, that I need to solve in Haskell. It was firstly solved in C++, then I rewrote the code to Haskell. The algorithm is working correctly but the Haskell version runs slower, compared to the C++ version. For example, for the input: 110110100011010101010101 010101101001000101010100 Haskell (with GHCI)...
You are spending an awful lot of time allocating and immediately destructuring pairs. That's pretty unnecessary, because you always know what [Char] you're going to get back in the second half of the tuple. Here's one way to eliminate that problem: ultimateFlip :: [Char] -> [Char] -> Int ultimateFlip [] [] = 0 ultimate...
65,499,418
65,499,652
copying numbers with text c++
So I have data inside a txt file and I open the txt file then look through it for the keyword I provided after that keyword it contains numbers like 9203 the numbers change constantly. So I want to know how would I be able to copy the numbers without knowing what they are exactly if this makes sense. std::fstream iData...
If this is done in a scope and you don't mind have an empty file created if no data matching is found then this would be an approach. Both files are closed automatically on exit of the scope they are defined in. { std::ifstream outfile("retrieveData.txt"); std::ofstream iData("itemValue.txt"); std::string col...
65,499,624
65,500,451
I recently installed codeblocks (Code :: Blocks IDE) but do not compile the simple test program
Summarizing the problem as generally as possible: I used to compile the program via terminal with the sequence of commands even in bash. Basically: g++ test.cpp -o teste.exe chmod +x teste.exe ./teste.exe At the terminal it works perfectly. But Codeblock practically does not create the program's executable. Simple exa...
Everything correct except the folder with space, after changing the directory to test the program it worked without problems, with my research I found that this bug exists since 2007 after 13 years, I was surprised to come across this problem not fixed. Link: http://forums.codeblocks.org/index.php/topic,5003.0.html No ...
65,499,778
65,499,985
How do you add separate test files with Catch2 and CMake?
In the documentation, they only compile a single file test.cpp which presumably contains all the tests. I want to separate my individual tests from the file that contains #define CATCH_CONFIG_MAIN, like so. If I have a file test.cpp which contains #define CATCH_CONFIG_MAIN and a separate test file simple_test.cpp, I've...
How do you add separate test files with Catch2 and CMake? Use object libraries or use --Wl,--whole-archive. Linker removes unreferenced symbols from static libraries when linking, so the tests are not in the final executable. Could you give an example CMakeLists.txt? Like find_package(Catch2 REQUIRED) add_library(...
65,499,906
65,500,687
Why does this cppreference excerpt seem to wrongly suggest that atomics can protect critical sections?
int main() { std::vector<int> foo; std::atomic<int> bar{0}; std::mutex mx; auto job = [&] { int asdf = bar.load(); // std::lock_guard lg(mx); foo.emplace_back(1); bar.store(foo.size()); }; std::thread t1(job); std::thread t2(job); t1.join(); t2.join();...
The quoted passage means that when B loads the value that A stored, then by observing that the store happened, it can also be assured that everything that B did before the store has also happened and is visible. But this doesn't tell you anything if the store has not in fact happened yet! The actual C++ standard says t...
65,500,310
65,509,423
Using `conan.cmake` with `conan_multi` generator, missing build_type argument?
I am attempting to get a multi-config cmake build working using conan.cmake. I am also following along with the cmake_multi docs. It seems that in the docs for cmake_multi, they require that you both pass -g cmake_multi and -s build_type={type} ({type} being Release/Debug/...). However, in conan.cmake it does not look ...
After reading the source code for conan.cmake a few more times I discovered that it is possible to have it propagate the build type, you just need to use the PROFILE_AUTO argument to conan_cmake_run. conan_cmake_run( PROFILE ${CONAN_PROFILE} CONFIGURATION_TYPES ${CONFIGURATION_TYPES} PROFILE_AUTO build_type #...
65,500,472
65,500,515
How bitwise shift operators are used to combine bytes into a larger integer
The following code combines two bytes into one 16 bit integer. unsigned char byteOne = 0b00000010; // 2 unsigned char byteTwo = 0b00000011; // 3 uint16_t i = 0b0000000000000000; i = (byteOne << 8) | byteTwo; //515 I'm trying to understand WHY this code works. If we break this down and just focus on one byte, byteOne;...
Yes--when you do almost any sort of operation on any value smaller than an int the first thing that happens is that the value is promoted to int (or, in some cases, unsigned int). In case you really care about the details that apply here (§[conv.prom]/1): A prvalue of an integer type other than bool, char16_t, char32...
65,500,736
65,510,510
Discover which monitor has touch capabilities on Windows 10
I have a two-monitor setup running on Windows 10 and my secondary monitor is a touch-screen. I can detect both monitors with EnumDisplayMonitors and discover that there is a digitizer present with GetSystemMetrics(SM_DIGITIZER). I'd like my app window to open on the touch monitor, but I can't find any function that t...
GetPointerDevices function give you that information. POINTER_DEVICE_INFO contains monitor handle and device pointer type in the same structure: typedef struct tagPOINTER_DEVICE_INFO { DWORD displayOrientation; HANDLE device; POINTER_DEVICE_TYPE pointerDeviceType; // can be POINTER_DEVI...
65,500,891
65,504,182
Avoiding temporary construction when returning by value and passing by const reference
I have a function which accepts a Large by const reference: void func(const Large& param); and a class which holds a Large: class HoldsLarge { public: Large GetByValue() const { return l; }; private: Large l; } If I do HoldsLarge x; func(x.GetByValue()); am I correct in understanding that a temporary will be co...
Compiler is allowed to change behavior (as optimization) in few cases: for NRVO, and since C++14 for new expression. You are not in those cases. Then; as-if rule allows any optimizations as long as observable behavior is identical. So compiler can do the optimization only if that doesn't change the behavior. Without kn...
65,501,040
65,501,107
__builtin_unreachable with floats in GCC
I have the following code, which I am compiling using gcc. float add(float a, float b) { float sum = a + b; if (sum != 0) __builtin_unreachable(); return sum; } When I am using -O3 I get the following assembly. add: addss xmm0, xmm1 ret But with -Ofast I get the following. add: p...
From GCC documentation: -fno-signed-zeros Allow optimizations for floating-point arithmetic that ignore the signedness of zero. IEEE arithmetic specifies the behavior of distinct +0.0 and -0.0 values, which then prohibits simplification of expressions such as x+0.0 or 0.0*x (even with -ffinite-math-only). This option ...
65,501,094
65,503,408
Why is the output ending the line early and filling every empty spaces with setfill instead of creating a line with it?
Im trying to create a ling of the special character "=" Output I want Name==================== Horace Horsecollar 56.00 12.50 700.00 210.00 10 480.00 Eleven Thirty 34.00 12.50 425.00 127.50 10 287.50 Victoria Elven 34.00 12.50 425.00 127.50 10 287.50 but the output here is filling all ...
You need to put formatters before the text. 








cout << setw(21) << setfill('=') << left << "Name" << setfill(' ') << endl; The left keyword means that the following text will be lined up on the left side of the 21-character column. The fill characters will go on the right. This also goes for the first part of yo...
65,501,279
65,518,197
A ball animation in simple harmonic motion using SDL2 and C++
I'm trying to emulate the following ball. Notice the simple harmonic motion of the ball, with the very ends of the ball bounce having a smaller velocity compared to the velocity in the middle: I'm able to implement a bouncing ball, however it's not simple harmonic motion: The corresponding code is as follows: Dot::Do...
I recommend using actual simple harmonic equations. For example, if your display dimensions are (500, 500), the center Y is 250. from there say your equation is in the form of x = acos(nt + m) + c where x is displacement (meters), a is amplitude n is for the period, for example the period (T) = 2PI/n t is time (seconds...
65,501,332
65,501,416
Seemingly unrelated specification in offsetof reference
I was reading reference of offsetof and saw the following: Given an object o of type type with static storage duration, &(o.member) shall be a constant expression and point to a subobject of o. Otherwise, the behavior is undefined. Particularly, if member is a static data member, a bit-field, or a member function, the...
The relevance is that this is explaining the requirements for offsetof. It goes without saying that you can't pass two arbitrary parameters and give meaningful results. So the requirements for offsetof are specified in terms of an example. offsetof is specified thusly: #define offsetof(type, member) ... The macro's fi...
65,501,400
65,501,671
C++ How to check last value in line and replace line if it is more than a certain value
I want to replace a line of a file, but only if the 3rd (last) value is above 0.000000. Specifically I have an Ascii .stl file, like below, where I want to be able to check the last value of each vertex line, and replace the entire line with a different string if it is above 0.000000. I am really struggling with unders...
For something as simple as detecting which line starts with "vertex", I don't think you need something as heavy as a regular expression. Here is a very simple example of detecting the line that starts with "vertex": #include <sstream> #include <string> #include <iostream> std::string test = "facet normal -1.000000 0.0...
65,501,461
65,505,087
Embed Perl script in C++ program
I have embedded a Perl interpreter into my C++ program, as I want to run a Perl script. Below is my code so far - it only runs a few dummy scripts; I would like to run the transferScript script, which involves passing two string parameters to the Perl script. Can I run an arbitrary string through the interpreter? How ...
Here is an example using @ARGV and eval_pv(): #include <iostream> #include <string> #include <EXTERN.h> #include <perl.h> static PerlInterpreter *my_perl; int main() { std::string script {R"x( use feature qw(say); use strict; use warnings; say "Got argument 1 = $ARGV[0]"; say "Got argument 2 = $ARGV[1]"; )x"}...
65,501,609
65,501,690
is there a way to take an item you have copied to clipboard and save it as a var or int
is it possible to take something i have copied to clipboard and have it save as an int or a var? i am trying to make something to take something i have copied to clipboard and make it able to paste it into a text document. is there any way to do this? i have not found any good answers explaining this so any help would ...
#include <windows.h> //get data HANDLE clip; string clip_text = ""; if (OpenClipboard(NULL)) { clip = GetClipboardData(CF_TEXT); clip_text = (char*)clip; cout << "Text: "<<clip_text<<endl<<endl; CloseClipboard(); } works with WINDOWS ONLY! Check these links: http://www.cplusplus.com/forum/beginner/27836/ htt...
65,502,222
65,502,281
How to check the value returned from a function and reiterate a loop again?
I am checking whether the digits of a number are other than 1 or 0 using the function checknumber(). If any digit is other than 0 or 1 then ask the user to enter the number again until the digits are 0 and 1 only. After this, convert into binary and then check if the number is greater than -1 and the number is in negat...
As I understand, You need to take a binary number as input. So, if the user enters any other string you need ask for input again. You can do that with a do-while loop. In do-while loop the logic is executed first and then the condition is checked. So, change your main() function like this: int main() { int num=0; ...
65,502,524
65,502,817
How to avoid code duplicates with class template specializations
I'd like to avoid the duplicates in the code below. #include <iostream> struct Bar{}; template <class... Args> struct FooClass; template <class... Args> inline void foo(Args&&... args) { FooClass<Args...>::impl(std::forward<Args>(args)...); } // Duplicate 1. // Const ref version template <> struct FooClass<Bar co...
Why not just strip off const and & from the template argument? template<class... Args> void foo(Args&&... args) { FooClass<std::decay_t<Args>...>::impl(std::forward<Args>(args)...); // ^^^^^^^^^^^^ } template<> struct FooClass<Bar> { static void impl(const Bar&) { std::cout << "bar" << std::e...
65,503,402
65,504,077
Copy Constructor for Class Linked List not working
My copy constructor is referring to another address instead of copying the values, can you guys please find the problem for me? This is the copy constructor: Poly::Poly(const Poly& copyList) { // copy the first term power = copyList.power; coef = copyList.coef; if (copyList.nextTerm == NULL) { ...
Your copy constructor has a bug. I added this friend function to display the linked list and a small program to create Polys and to copy them: std::ostream& operator<<(std::ostream& os, const Poly& p) { const Poly* n = &p; os << '{'; do { os << "addr:" << n << ' ' << n->power << ',' << n->coef << ' ...
65,503,495
65,504,127
A recursive_invoke_result_t template structure
I am trying to implement a recursive version std::invoke_result_t with C++20 concept so that the type of nested invoke result can be retrieved. The use case of recursive_invoke_result_t auto f1 = [](int x) { return static_cast<double>(x); }; std::cout << typeid(recursive_invoke_result_t<decltype(f1), int>).name() << st...
This template<typename F, typename T> requires std::invocable<F, T> struct recursive_invoke_result_t_detail { using type = std::invoke_result_t<F, T>; }; is the primary template for recursive_invoke_result_t_detail. The requires std::invocable<F, T> then means that recursive_invoke_result_t_detail<F, T> is only va...
65,504,237
65,505,553
Boost Spirit X3: skip parser that would do nothing
I'm getting myself familiarized with boost spirit v3. The question I want to ask is how to state the fact that you don't want to use skip parser in any way. Consider a simple example of parsing comma-separated sequence of integers: #include <iostream> #include <string> #include <vector> #include <boost/spirit/home/x3....
You can use either no_skip[] or lexeme[]. They're almost identical, except for pre-skip (Boost Spirit lexeme vs no_skip). Are there no skip parsers that would simply do nothing? Am I missing something? A wild guess, but you might be missing the parse API that doesn't accept a skipper in the first place Live On Coliru...
65,504,445
65,505,613
How can i use 2 QTimer? One is for counting and the other one is displaying
I want to Timer with c++ using Qt. I have one timer in my code, but the time display on the screen is slow. timer -> start(500) must update every 20 seconds I guess. I want to use 2 timers for it. One is for update and count the time, the other timer will display on the screen. How can I do that, I would be very happy...
When you start a timer like this timer -> start(500) it will timeout every 500ms (0.5 sec) so if you want a timer with 20 second timeout, you can start it with timer -> start(20000). Now if you want another timer for updating display you can start your timer2 with period that you like and connect it to another slot to ...
65,504,663
65,505,427
Passing a 2d array of vector to a class constructor
In my code, I have some data stored in an 2d array of vector and I'd like to use it in another class to process the data but I can't find a way to do that. Here is a sample of what I tried : vector<IndividualData> vecArray[5][5]; // The one I want to pass to the class MyClass::MyClass(vector<IndividualData> data[][5],...
This works for me: using My2DArrayOfVec = std::array<std::array<std::vector<IndividualData>, 5>, 5>; class MyClass { My2DArrayOfVec _data; public: MyClass(My2DArrayOfVec const& data, ...) : _data(data) {} void useIt() const { printf("%d\r\n", _data[0][0][0].param); } }; By having an alias, I always use the s...
65,504,912
65,522,164
How to dynamically change tabs sizes in Qt?
I'm a student working on my first Qt program and I need some help. I'm developing a musical instruments simulator. I have a mainwindow and 2 classes: DrumsWindow and KeysWindow simulating drums and keys and having different sizes (drums are 798x532, keys are 953x306). I have created a tabWidget in the main window and i...
Thank you guys, you helped me a lot. Here's what I did. mainwindow.h: added a slot private slots: void onTabBarClicked(int); mainwindow.cpp: added the realization of the slot void MainWindow::onTabBarClicked(int index){ if (index == 0){ this->resize(798, 532); ui->tabWidget->resize(798, 532); ...
65,505,629
65,505,692
Shared_pointer showing different behaviour than the one i read in text book
So i am trying to develop my understanding of shared_ptr and if multiple shared ptr point at the same resource shared pointer is resposible to handle the case where destrcutor should neve be called before the last pointer pointing at the resource is destroyed. Here is my sample code: #include <iostream> #include <memo...
The problem is with your line std::shared_ptr<A> ptr2(ptr.get()); It is not the way shared pointers should be used. Instead, replace it with something like std::shared_ptr<A> ptr2{ptr}; or std::shared_ptr<A> ptr2 = ptr; (Furthermore, as Den-Jason notes in the comment, you should prefer to use std::make_shared.) Whe...
65,505,907
65,506,864
Why textures don't display properly?
I have a project where my textures are not displayed inside window properly. Instead of textures it will always show blank white sprites. I cant find out what I'am doing wrong. Here is my code: class header with vector holding textures class textures { public: sf::Texture dirt_Texture; sf::T...
getTextureByID() returns a copy of a texture and not a reference. This copy is destroyed when it goes out of scope - so as soon as the call to sprite.setTexture() finishes. This results in the Sprite having a pointer to a texture that no longer exists. The solution is to instead return a pointer or a reference from get...
65,506,461
65,506,733
JNI DETECTED ERROR IN APPLICATION: use of invalid jobject when returning Array of String
Description of the intended goal I'm trying to implement OpenSSL-generated public/private key pairs in Android/Kotlin using JNI, in order to implement user encryption on the information stored to the cloud server. I've compiled all OpenSSL source code and generated all .so files correcly. The code (C++) The C++ code to...
You never created a java string out of public_key_text Try char * public_key_text; ... BIO_get_mem_data(bp_public, &public_key_text); ... env->SetObjectArrayElement(returnPair, 0, env->NewStringUTF(public_key_text));
65,506,467
65,510,364
Why does the compiler warn about uninitialized edge iterator in some optimization levels?
I have minimized the reproducible example as far as I was able to. In it, I loop over all edges in the boost graph and get a warning that I don't understand. Please explain to me why I am getting this warning, and perhaps also why it only appears in certain optimization levels. /* * reproducing the warning about mayb...
As I commented, this is likely a compiler issue with specific compiler versions, where inlining+dead code elision leads to spurious unused variable warnings. I don't see much virtue in finding whether there has been a bug report linked to the fix. Instead, let me show you more elegant ways to write the code in c++14. ...
65,506,657
65,507,520
Sqlite Query to remove duplicates from one column. Removal depends on the second column
Please have a look at the following data example: In this table, I have multiple columns. There is no PRIMARY KEY, as per the image I attached, there are a few duplicates in STK_CODE. Depending on the (min) column, I want to remove duplicate rows. According to the image, one stk_code has three different rows. Correspo...
Your table has rowid as primary key. Use it to get the rowids that you don't want to delete: DELETE FROM comparison WHERE rowid NOT IN ( SELECT rowid FROM comparison GROUP BY STK_CODE HAVING (COUNT(*) = 1 OR MIN(CASE WHEN min > 0 THEN min END)) ) This code uses rowid as a bare column and a documented feature o...
65,507,041
65,507,223
How to store elements in 2d vector without knowing his width?
I have a 1 dimensional vector std::vector<int> vec1 = {4, 5, 6, 7}; and I want to store these elements in a 2 dimensional vector std::vector<std::vector<int>> vec2; but vec2 can only have height 3 and I have in vec1 - 4 elements. The output of vec2 should be: 4 7 5 6
Maybe I do not fully understand the question, but what I understood can be achieved by 1 simple for loop. Just take into account, that we have only 3 rows. There is not much to explain . . . Please see: #include <iostream> #include <vector> int main() { // 1d vector with any number of values std::vector<int> ...
65,507,045
65,507,144
How can I get my array class instance to use initializer list to initialize the array
I am trying to write an array class similar to the one in standard lib for practice. I want to be able to initialize my array class by using an initializer list, but I don't what code to add to my class to do that. I am confused because there are multiple elements in the initializer list but only container to hold the ...
There are several ways make your class aggregate: template<typename T, int size> class Array { public: T data[size]; }; Provide constructor which accept {..} such as template<typename T, int size> class Array { private: T data[size]; public: Array(const T (&data)[size]); //Array(std::initializer_l...
65,507,301
65,509,232
Is passing by reference to thread here bad practice?
This is the code listening from one C++ book. void edit_document(std::string const& filename) { open_document_and_display_gui(filename); while(!done_editing()) { user_command cmd=get_user_input(); if(cmd.type==open_new_document) { std::string const new_name=get_filename_f...
There's nothing wrong with having a thread function that takes its argument by reference. The constructor for std::thread doesn't forward its arguments by reference; it copies the arguments that are passed to it. So, internally, when you create a thread with std::thread t(edit_document, new_name); it, in effect, gener...
65,507,610
65,508,522
C++ - std::initializer_list vs std::span
What is the difference between std::initializer_list and std::span? Both are contiguous sequences of values of some type. Both are non-owning. So when do we use the first and when do we use the latter?
The short answer is that std::initializer_list<T> is used to create a new range, for the purposes of initialization. While std::span<T> is used to refer to existing ranges, for better APIs. std::initializer_list<T> is a language feature that actually constructs a new array and owns it. It solves the problem of how to ...
65,507,648
65,507,721
resizing std::vector to a value less than its initial reserve capacity erases data
Can somebody explain why resizing a std::vector to a value less than its initial reserve capacity erases data contained in it before resizing. I am thinking resize just sets internal size variable to the given value(in this case from 0 to 2 no extra allocation if resize is less than capacity). What needs to be done if ...
The shown code results in undefined behavior. vec_buff.reserve(32); This sets reserve capacity for the vector. This does not set the size of the vector to 32 values. That's what resize() is for. This is not resize() but reserve(). The vector is still empty. There are exactly 0 values in this vector. vec_buff.data()[0]...
65,507,963
65,508,050
VS code : cannot jump between header file and related cpp file
I have a big c++ project in linux. I try to open this project in VS code in windows using remote ssh. After project loaded, i found it cannot jump between header file and its related cpp files, and also cannot jump to variable definition or implemention. And i already installed extention c/c++, switcher. But i found ri...
Have you installed this extension on the remote server:
65,508,309
65,508,387
Perfect forwarding in a template class
I have a template class and within that class I have a static template function with universal/forwarding reference parameters. The idea is to perfect forward arguments to the function. #include <iostream> #include <type_traits> //Type traits template <typename T> struct is_lreference_const { static const bool val...
template <typename T> struct FooClass<T> { inline static void impl(T&& b) { FooClass<X>::impl takes an X&&, and in it T is X. If X is int&&, then T&& is int&& && which is int&& and T is int&&. If X is int, then T&& is int&& which is int&&, and T is int. Within impl, you query T, not b. So you get a different value ...
65,508,488
65,508,847
How to skip uncompilable code through constexpr-if in C++?
Imagine next code that doesn't compile: Try it online! #include <type_traits> #include <iostream> int main() { struct A { int i = 123; }; struct B { int j = 456; }; B x; if constexpr(std::is_same_v<decltype(x), A>) std::cout << "A: " << x.i; else if constexpr(std::is_same_v<decltype(x), B>)...
As mentioned in the comments, "you have to make the discarded statement dependent of the template parameters" - What you are trying to do is not possible without introducing templates. For example, this would "work" but its far from a good solution. I added it as answer as the similarity to the question that I marked a...
65,508,569
65,523,068
How to move my Gtk::Window to a specific position on screen in gtkmm 4
I subclassed Gtk::Window and i want to move it to a position on the screen, but i cannot find any method to do this. Was Gtk::Window::move removed in Gtk4 ? If yes, how can i move my window ? I currently have this in the constructor of my window class : this->set_title(_("Screenshot")); // this is for getting the size ...
Looks like GTK continues to devolve. See How to center GtkWindows in gtk4?, where the answer appears to be "no way, the gtk_window_set_position() API has been removed" (confirmed by a GTK core developer). And the comments in that thread seem to imply that GTK is going into the direction of removing everything related t...
65,508,613
65,508,773
Is this a safe way to load objects from vector of uint8_t by pointer?
I have a std::vector<uint8_t> buffer; I want to load a datatype which is larger than uint8_t (in this example uint16_t target, but could be anything). I know that the content of this object has been copied into position size_t ID in buffer. As far as I can tell, it is possible to copy the target with: uint16_t target =...
No, it isn't. You cannot "pretend" a uint16_t exists where it does not. There are some circumstances where such type punning is safe. For example, you can reinterpret an existing object of your desired type as a sequence of bytes (through a char*, unsigned char* or std::byte*), but the opposite is not true. (ref) C++ i...
65,508,704
65,508,776
getting an extra unwanted value when resizing 2d vector
I am trying to create a 4x3 matrix. There should be four 4 columns and 3 rows. it should look like this: 000 000 000 000 Instead I am getting this as an output when I print out my 2d vector: 0000 0000 0000 0000 This my simple code: #include <iostream> #include <vector> int main(void) { std::vector< std::v...
You access elements out of bounds, inner loop should be something like: for (unsigned int i = 0; i < matrix.size(); i++) { for (unsigned int j = 0; j < matrix[i].size(); j++) { std::cout << matrix[i][j]; } std::cout << std::endl; } or even better: for( const auto &m : matrix ) { for( auto ...
65,508,774
65,508,792
Delete rows from Table1 when Table1.COL = Table2.Col
I have 2 tables(comparison & comparison_2). Comparison table has many rows while comparison_2 is actually a small subset of comparison. Both of these tables have two similar columns named Barcodes, i want to delete from comparison all those rows which have matching barcodes with comparison_2. I hope i am very clear wit...
I would use exists: delete from comparison where exists (select 1 from comparison_2 c2 where c2.barcode = comparison.barcode)
65,509,566
65,509,777
How to delete an object from vector<ptr*>?
I've got classes like that: class A { vector<B*> ve; public: void add_last(B* b) { ve.push_back(b); } void remove_last() {//????} //.... } class B { //...} class B1 : public B { //...} public: ~B1 {cout << "~B1\n";} //... } class B2 : publi...
As @NathanOliver already said in the comments, the proper way to do that would be to store std::unique_ptr<B> instead of B * so that destructors are called automatically & memory is freed. Furthemore, use std::unique_ptr<const B> to be able to insert const B *: class A { vector<std::unique_ptr<const B>> ve; ...
65,509,613
65,509,693
Forcing inlining of lambda in MSVC C++
Next code compiles in CLang/GCC, and successfully inlines lambda: Try it online! #include <iostream> int main() { int x = 0; auto f = [&]() __attribute__((always_inline)) { ++x; }; f(); std::cout << x; } But similar code with __forceinline in latest MSVC (2019 v16.8.3) doesn't compile, alt...
Per Jonathan Caves reply on the feature request, the supported syntax going forward is auto f = [&]() [[msvc::forceinline]] { ++x; }; which does compile It looks like they wanted it to comply with the attributes syntax that was introduced in C++11
65,509,724
65,509,957
How to compile and run a C++ open source program?
This question may seem stupid, but as a beginner I did encounter this question when I moved forward, and I couldn’t find any information. https://upload.cc/i1/2020/12/30/rUEC9s.png https://upload.cc/i1/2020/12/30/d7Gwbr.png https://upload.cc/i1/2020/12/30/6vr3lQ.png This is an open source C++ program, I tried to compil...
Your questions are too broad. Generally speaking, the answers would be something like this: Naming your main file main.cpp is a convention, but is not required. What is required is a main() function (More info here). You have to configure CLion to open Makefiles. There is a tutorial in CLion's website (Here). What d...
65,510,205
65,512,457
clang insists on compiling uncalled functions
Moving from using Intel compiler & VC to Apple clang 12.0. In my code there are functions that are never called for a certain project (but needed when included in other projects). Clang insists on compiling the uncalled functions and detects errors, where Intel and VC simply skipped compilation. These are errors that a...
Clang has a mode in which is tries to behave as if it's MSVC. This was introduced as part clang-cl, the driver for clang that accepts a lot of the same arguments as MSVC. You can find some information about it on the user manual and the MSVC compatibility pages. Long story short, there is an option -fdelayed-template-p...
65,510,569
65,510,666
Code produce two different upon removing if statement
While I was solving a question from codeforces(link to the question: https://codeforces.com/contest/1466/problem/A) I encountered weird output from the below code #include<iostream> #include<vector> #include<set> using namespace std; void solve(){ int64_t n; cin>>n; if (n<2){ cout<<0<<endl; ...
if (n<2){ cout<<0<<endl; return; } Since you're returning here, it means that if n is 1, you never read that one value out of std::cin. If you remove that if, then that one value will get read in here: vector<int64_t> vec(n, 0); for(auto &i: vec){ cin>>i; } So if you want the if to work as expected, i...
65,510,782
65,510,831
Are these the expected errors with std::enable_if, or am I using it incorrectly?
I realize this is a pretty basic question, but I just want to confirm that I'm using std::enable_if correctly because I'm a little uncertain what the "correct" error messages should be when attempting to call a disabled function. Consider the following program (link), which is expected to not compile: #include <type_tr...
std::enable_if_t is a template that causes substitution to fail if the condition is false. Because of SFINAE this does not cause the program to be ill-formed, when it happens during overload resolution. You are passing it a false value as the default value, so for a call to function(), without any additionally specifie...
65,511,280
65,511,905
How can I simplify the if - else statements?
I finished creating a - very noob, because I'm still a noob :( - program that acts as a bank account. I have main.cpp, Account.cpp, Account.h. In main.cpp I have: #include <iostream> #include <string> #include "Account.h" int main() { Account Luigis; Luigis.set_name("Luigi's Account"); Luigis.set_balanc...
I think you have an exaggerated impression of complexity concerning your conditional constructs. To me (and at least 5 others, judging from comments and the "agrees" the got) they do not seem overly complex. I hence propose something to change your impression, though it will not change the functionality at all: Please ...
65,511,484
65,511,543
changing characters in char array
I have trouble with the following task: take in limited char array change a given character in array print changed char array Here's my code: #include <iostream> using namespace std; void change(const char* source, char* target) { int j; for (j = 0; j < 100; j++) { if (source[j] == '.') { target[j] = ...
It's easier than you think, try this version cin >> input; change(input, output); It's a very common beginner misunderstanding to think that input[100] somehow represents the whole array. It doesn't. When you declare an array the number between the [] is the size of the array, but when you use an array the number bet...
65,512,166
65,512,300
OpenGL semicircular rotation and quarter circle
The following code will create a new semicircular using openGL: glPointSize(2); glBegin(GL_POINTS); for (float i = p; i <= (2 * p); i += 0.001) { x = 50.0 * cos(i) + 20; y = 50.0 * sin(i) + 20; glVertex2f(x, y); } glEnd(); Now I want to know how to change this code and creat...
Here i is the angle in radians. The loop goes from π to 2π—this is a semicircle (but the second half of it - a bit ill-defined). To turn it into a quarter circle loop from 0 to π/2. To rotate the circle by x degrees, convert it to radians and add to the angle. Alternatively you can draw a portion of a circle by simply ...
65,512,211
65,512,280
Overriding virtual function differs C++
I am new to C++. I have downloaded this project and when I try to run it I get: Severity Code Description Project File Line Suppression State Error C2695 'TFruityGain::Idle': overriding virtual function differs from 'TCPPFruityPlug::Idle' only by calling convention FruityGain_VC c:source\c\fruitygain_...
differs from 'TCPPFruityPlug::Idle' only by calling convention This issue comes from the fact that you have: virtual void _stdcall Idle(); and virtual void Idle(); And when you override a function you want the same calling convention, see: What is the meaning and usage of __stdcall?
65,512,836
65,513,460
Problems with std::cin and isdigit in c++
When I run the code and enters for instance 1 in the terminal it goes to the 'else' condition and breaks. But I'm providing it with a digit so I have trouble understanding why it behaves like that. Could someone help clarify? int main() { vector<int> positions; int p; for(int i = 0; i <= 3; i++){ cou...
the function is defined for the character, it would be true if you wrote isdigit('1'). Also isdigit(49) = true, because in ascii 49 is digit 1, so isdigit(49) = true; check the reference of isdigit(): http://www.cplusplus.com/reference/cctype/isdigit/
65,512,928
65,513,675
Reading N-API object into C++ primitive
I've created a simple N-API module starting from the ObjectWrap boilerplate of generator-napi-module, and successfully passed data (an array containing objects with string, number and boolean properties) to JS. However, I'm unable to parse the properties of one of the same objects passed back to the native code; specif...
I missed two things, which allow this to work: I was inconsistent with strings when using Get/Set. If Napi::Object::Set is used with single quotes, single quotes must be used with Napi::Object::Get; likewise for double quotes. Uint32Value() method needs to be used per the docs (I must have removed this in my tinkering...
65,513,903
65,514,086
Mapping a list to a different type
I'm trying to make a List class, mainly because there are some methods that aren't present for vectors that I'd like to implement myself. One of these is a map() function where you can pass in a lambda as a parameter and the method returns a new List in which each of the values in the old list was passed to the functio...
Use decltype. In your definition, you want to determine the type of the output list return value with what would be returned from the function. So you can do something like this: template<typename R> auto map(R function) { List<std::decay_t<decltype(function(operator[](0)))>> output; for(int i = 0; i < size(); ...
65,514,366
65,514,448
Visual Studio Code IncludePath Issue with ROS headers
I'm getting squiggly lines under the statements of #include "rclcpp/rclcpp.hpp" from the ROS2 tutorial I'm going through and updating IncludePath in c_cpp_properties.json is not fixing the issue. Here's what my c_cpp_properties file looks like: { "configurations": [ { "browse": { ...
Removing configurationProvider from c_cpp_properties.json did the trick and intellisense is working now.
65,514,615
65,514,904
why does C++ give me an error when inserting unique pointer into unordered map?
in a class with the following member and method: std::unordered_map<std::string, std::unique_ptr<test::Test>> m_Tests; void test::TestMenu::addTest(const std::string &testName, std::unique_ptr<test::Test> test) { m_Tests.emplace(testName, test); } called like this: testMenu.addTest("Test Clear...
This: m_Tests.emplace(testName, test); will try to copy test, because (a) it is an lvalue expression, (b) expressions never have reference type, and (c) emplace does not take an lvalue reference. unique_ptrs cannot be copied. This is what std::move is for! m_Tests.emplace(testName, std::move(test)); Now you have an r...
65,514,725
65,514,788
Can't bind lvalue to rvalue in member function but ok in global function
While looking at the reference pages for std::forward I came across something odd. The example is passing an lvalue as an rvalue reference.. but to a global function... and it compiles and runs. I tried the same thing as a member function and it fails to compile. What gives? I would expect both calls to fail without th...
It's because the automatic template deduction for globalDoSomething infers T as int&. If you explicitly instantiate the template function with globalDoSomething<int>(b); like you did for the member function of the template class, it will also fail to compile. Conversely, if you instantiate the template class with A<int...
65,515,425
65,515,490
Is there a better way to initalize pointers in c++?
Below I have a bit of code for implementing Huffman compression. What I was curious about was if I could initialize the left and right pointers without including cstdlib, or rather, if I could initialize an empty memory location for storing the left and right without using malloc. Also, in my combine function, I do not...
So a couple of points. key is a string, not a pointer. It makes no sense to set it to nullptr, i am guessing "NULL", is just a stand in for when the key has no value. Instead of this, just use an empty string "". You should try to avoid this manual memory management for several reasons. First of all you have no destr...
65,515,924
65,516,041
why my struct takes more memory than requested?
I am testing the following code with Visual Studio 2019 Diagnostic Tools. It says that memory consumption is 55 KB instead of the 20 KB I previously calculated. As you can see, it is much more memory than I thought and I don't know why. What I want to know is: what is happening or how could I calculate the correct memo...
Your diagnostic tool is measuring an allocation overhead of 36 bytes per allocation. 50.78 KB is 52000 bytes, or 52 bytes per element allocation. Minus 16 is 36 bytes. 4000 bytes with 36 bytes overhead is 4036 bytes, which is 3.94 KB. The heap has to track which blocks of memory are in use and which are not. Possibly...
65,516,251
65,516,409
Why does sin of the same number return two very different values?
Can someone explain why these two outputs are vastly different? When I print out (float)direction*PI/180.0f and theta they both evaluate to 1.5708 as expected. Why does putting one in a float variable before putting it in the sin function make such a huge difference in output? Also note that test2 returns the correct...
Rounding errors. Your test variable is < 1.0, your test2 variable is >= 1.0. I C and C++, 0.9999999999999 gets rounded to 0. #include <iostream> #include <cmath> #define PI 3.14159265 int main() { int direction = 90; float theta = (float)direction*PI/180.0f; auto test = sin(theta); auto test2 = s...
65,516,555
65,518,905
How to terminate windows sockets when internet is down? (C++ WinAPI)
I have set up a Winsock2 connection but I need to cover the case where internet is down. Here is my code; #include <winsock2.h> #include <windows.h> #include <ctime> int main() { WSADATA w; if(WSAStartup(MAKEWORD(2,2),&w)) return 0; sockaddr_in sad; sad.sin_family=AF_INET; sad.sin_addr.s_addr=inet_a...
If you want to issue a recvfrom() and have it return immediately, then decide on your own how long to wait (I'm assuming Windows since you included winsock2.h), you can make an asynchronous OVERLAPPED request, then wait for the completion at any time by waiting for the hEvent member of the OVERLAPPED struct to be signa...
65,516,568
65,520,210
C++ UWP Storage Access
After rescap capability configuration and privacy setting File system allow still we cannot access File system and other drives to read file and configure model path for open pose in c++. I have tried many possibilities i cant access assets folder *.png file also.
Even with the broadFileSystemAccess capability you won't be able to access an arbitrary path on the file system with ordinary APIs, you have to use the StorageFile/StorageFolder APIs instead. From the screenshot I see you are trying to read the image using OpenCV, so instead of using a path, you will need to read the i...
65,517,024
65,517,699
Compile and run GLFW on Linux
I was trying to get GLFW setup so I could make Windows in C++, but ran into an issue. My issue was that I was getting errors whenever I compiled. I am trying to get a window that opens and closes when I terminate it. I've tried multiple methods to fix this, none of which have actually worked properly. I can't really te...
You aren't including any OpenGL loader in your code. glClear is an OpenGL function. Take a look at Glad.
65,517,035
65,517,164
I want to Print the Abbrevation of the Word but dont know what I am doing wrong
I want to Print the Abbreviation of the Word Write a C program that should take an organization’s name from the user as a string. You have to implement the following function on that string: For example: Word = Pakistan State Oil Abbreviation: PSO Only Capital Letters from the Word It is Printing only 1 word. Code :...
You need to change your findAbbrevation() function like this: void findAbbrevation(char Word[]) { int WordLength = findLength(Word); char WordAbb[25] = {0}; int j = 0; int flag = 0; for (int i = 0; i < WordLength; i++) { // To continue untill we get a space // this marks the...
65,517,073
65,525,742
Spinning on an atomic load with acquire consistency vs. relaxed consistency
Consider the code below: // Class member initialization: std::atomic<bool> ready_ = false; ... // Core A: while (!ready_.load(std::memory_order_acquire)) { // On x86, you would probably put a `pause` instruction here. } // Core A now accesses memory written by Core B. ... // Core B: // Core B writes memory. ready...
There are two ways in which the first code could be less efficient than the second, at least on some hypothetical architecture. On x86, my guess would be that they compile to the same code. The first issue is that an atomic load might affect the performance of other processors. On alpha, which is often a good "outlie...
65,517,629
65,598,526
What would a default lambda capture mode via init capture be like?
With lambdas, in C++11, we can have a default capture mode set to by-value/by-ref, e.g. [=]/[&], optionally followed by explicit captures, by-ref/by-value, for some variables, e.g. [=,&this_is_by_ref] or [&,this_is_by_value]. In C++14, we can also have explicit captures by-move, e.g. [y = std::move(x)]. In Effective Mo...
The answer by @OutOfBound is already good. I will only express a similar ideas from a different angle. Scott Meyers in the first few paragraphs of item 32 notices that: The capture syntax introduced in C++11 was seen as unsatisfactory even at the moment the standard was adopted. The reason for this was the absence of ...
65,517,630
65,524,663
What is the difference between memory barrier and complier-only fence
As the question stated, I'm confused about the difference between memory barrier and complier-only fence. Are they the same? If not what is the difference between them?
As a concrete example, consider the following code: int x = 0, y = 0; void foo() { x = 10; y = 20; } As it stands, without any barriers or fences, the compiler may reorder the two stores and emit assembly (pseudo)code like STORE [y], 20 STORE [x], 10 If you insert a compiler-only fence between x = 10; and y ...
65,517,730
65,518,882
"Capture by move" does not prevent capture by reference
When I write [&,x](){ /* making use of x */ }, x is captured by value. When I write [=,&x](){ /* making use of x */ }, x is captured by reference. If I try writing [&x, x](){ … } I get an error telling me x can appear only once in a capture list. However, [&x, y = std::move(x)](){ /* making use of x and y */ }(); compi...
The case [&x, y = std::move(x)](){ }; is quite legal from the point of view of the compiler, because different identifiers are used for capture. The standard says the following: [expr.prim.lambda/capture-2] Ignoring appearances in initializers of init-captures, an identifier or this shall not appear more than once in ...
65,517,915
65,518,033
How to invoke a template operator[] in c++?
I have a map that allows std::any as values, then I return the std::any object. I would like to save some characters in my code. so I have class MyMap { std::map<std::string, std::any> map; public: template<typename T> const T & operator[](const std::string & name) const { auto & aux = map[name]; ...
You could invoke this as: auto foo = mymap.operator[]<int>("key"); ...but if you're going to do that, you'd be a lot better off making it a normal member function: template<typename T> const T & get(const std::string & name) const { auto aux = map[name]; return std::any_cast<T&>(aux); } ....
65,518,096
65,518,408
size of class in case of composition
class Test2 { char pq; long double qr; }; class Test { double c; int a; char b; Test2 z; }; sizeof(Test2)=32 sizeof(Test)=48 Why sizeof(Test) is 48 on a 64-bit operating system?
It is all about memory alignment. alignment uses to ensure types don't slip from one memory page to another. the compiler ensures the start address of a type is divided by its alignment. For example: if a type has an alignment of 2 it can't start on an even address if it has an alignment of 4, the start address the las...
65,518,363
65,518,549
How to append to a list of variables in a Makefile?
I am trying to write a Makefile for the following project structure /project Makefile main.cpp test.hpp /a s1.cpp s1.hpp s2.cpp s2.hpp /b s1.cpp s1.hpp s2.cpp s2.hpp /c s1.cpp s1.hpp s2.cpp s2.hpp I have 3 folders with .cpp and .hpp files, I'd like t...
The wildcard function takes several patterns. The addsuffix function appends a suffix to each word in a list. So: INC = $(wildcard $(addsuffix /*.hpp,$(DIRS))) should do what you want. There are other ways like: INC = $(foreach d,$(DIRS),$(wildcard $(d)/*.hpp)) or, if you have the find utility and want to find all *....
65,518,377
65,529,900
Convert "__m256 with random-bits" into float values of [0, 1] range
I have a __m256 value that holds random bits. I would like to to "interpret" it, to obtain another __m256 that holds float values in a uniform [0.0f, 1.0f] range. Planning to do it using: __m256 randomBits = /* generated random bits, uniformly distribution */; __m256 invFloatRange = _mm256_set1_ps( numeric_limits<flo...
As @Soonts has pointed out, floats can be created uniformly in [0, 1] range: https://stackoverflow.com/a/54873925/9007125 I ended up using the answer below: https://stackoverflow.com/a/54893167/9007125 //converts __m256i values into __m256 values, that contains floats in [0,1] range. //https://stackoverflow.com/a/54893...
65,518,412
65,518,578
how to get variable's type in template?
I want to use template function to dump data into file, here is my code: template<typename T> // T can be `std::unordered_map<int, std::vector<double> >` or `std::unordered_map<int, std::vector<int> >` void write_down(const std::string & file_path, const T & week) { std::fstream f; f.open(file_path.c_str(), std::i...
You are using a combination of filestream, string concatenation and snprintf. You could drop the latter two and write directly to the filestream: for (auto w : week) { int date = w.first; auto v = w.second; // buffer and snprintf replaced, no need for intermediate string b: f << date << "\t["; fo...
65,518,604
65,518,825
Define Enum with strong-typedef CPP
While defining a network-message struct: Want to hold the Op field as an Enum (so to limit the allowed values). Need to keep all fields as unsigned, and the Op specifically to be uint32_t. Is there a way to combine these requirements? something like: typedef enum Op : uint32_t {save = 100, retrieve = 101, delete = 20...
"100" "101" "200 Well, I don't quite understand what these strings mean? Your question is not very clear to me. It sounds like what you want is enum class (Scoped enumerations). enum class Op : uint32_t { _100 = 100, _101 = 101, _200 = 200 }; limit the allowed values Yes. Need to keep all fields as unsi...
65,518,629
65,519,380
C++ Compile time check if a function called before another one
Lets say I have a class with two member functions. class Dummy { public: void procedure_1(); void procedure_2(); }; At compile time, I want to be sure that, procedure_1 is called before procedure_2. What is the correct way do implement this?
Maybe you could do it with a proxy-class. The idea is, that procedure_2 can't be accessed directly from outside (for example by making it private). procedure_1 would return some kind of proxy that allows the access to procedure_2. Some code below, allthough I don't consider it clean or safe. And if you want, you can st...
65,518,794
65,523,268
Can someone explain what these lines of code are doing?
int64_t lstbt(int64_t val){ int64_t msk = val&(val-1); return log2(val^msk); } What does the msk actually computes, and why are we returning log of value xor msk?
To understand the function: int64_t lstbt(int64_t val){ int64_t msk = val&(val-1); return log2(val^msk); } let us break it into smaller chunks. First the statement val-1, by adding -1 to val, you flip (among others) the least significant bit (LSB), (i.e., 0 turns into 1, and vice-versa). The next operation (va...
65,518,971
65,520,846
Conditionally select compiler based on its version
Goals Make cmake select clang++ if its version is above 10; otherwise, use g++. If clang++ is below 10 and the default g++ is below 10.1, use g++-10 (REQUIRED). This is to achieve compiler fallback. Background As kindly noted in this answer, one should set the default compiler before the project keyword. Instead of usi...
If you want to write the logic in cmake, you could write something along: cmake_minimum_required(VERSION 3.11) # Before project()!!! execute_process(COMMAND clang++ --version OUTPUT_VARIABLE result) string(REGEX REPLACE "[^0-9]* ([0-9]+).*" "\\1" clang_version "${result}") # extract the version with some regex execute...
65,519,019
65,519,222
Why does passing a const object to a templated function expecting a non-const template type argument result in a compilation error?
Consider the following templated function: template <template<class, class> class V, class T, class Allocator> void fn(V<T, Allocator>& v) { for (T& t : v) { std::cout << t << std::endl; } } When I pass it a non-const vector like: std::vector<int> v{ 1, 2, 3, 4, 5 }; fn(v); The compiler is happy, and I am hap...
I thought that V<T, Allocator>& will be deduced to const std::vector<int, std::allocator<int>>& This would be true if the parameter was plain U, like template<class U> void fn(U&);. Type deduction is pattern matching. const is part of the type, hence the pattern U can be deduced to T const. Consider: using T = int co...
65,519,444
65,519,608
Direct State Access (DSA) is Failing, but pre 4.3 OpenGL works
I currently have an OpenGL project in which I am using GLFW for the window and context creation, and GLAD for loading OpenGL functions. The GLAD version I am using is OpenGL 4.6, compatibility profile, with all extensions (including ARB_direct_state_access). My current graphics card settings are OpenGL Version: 4.6.0 N...
When you use glVertexArrayVertexBuffer you must specify the stride argument. The special case in which the generic vertex attributes are understood as tightly packed when the stride is 0, as when using glVertexAttribPointer, does not apply when using glVertexArrayVertexBuffer. glVertexArrayVertexBuffer(vao, 0, vbo, 0, ...
65,519,616
65,520,302
populating a constexpr array using C++17
I'm trying to initialize a constexpr array using C++17 via the following: template <size_t N> struct CStr { static constexpr std::array<int, N> getArr() { std::array<int, N> a; for (auto idx = 0; idx < a.size(); ++idx) { a[idx] = idx * idx; } return a; } ...
This is a restriction in C++ until C++20, see Permitting trivial default initialization in constexpr contexts: You have to initialize all variables inside of a constexpr function. The Standard gives the following example: C++17 constexpr int uninit() { int a; // error: variable is uninitialized ret...
65,519,743
65,522,427
How can I find the maximum difference of two elements in an array, given some constraints?
Problem: Find the maximum difference of two elements in an array such that the index of the element of the larger element is greater than the index of the smaller element. Note: I will use zero-based indexing. Example: array = {1,2,3,4,5} The maximum difference will be 4. The index of '5' is greater than the index of '...
You can do this by taking the difference of elements with the minimum element found so far. Here's how you can do this: int arr[5]={101,2,100,5,1},min=arr[0],i,diff=-99999; //You can initialize diff to be arr[1]-arr[0] for simplicity. for(i=1;i<5;i++) { if(arr[i]-min>diff) //If the difference is grea...
65,519,748
65,520,985
CGAL::Surface_mesh Create surface mesh when number of vertices and faces are known
I would like to ask if it is possible to optimize Surface mesh creation of CGAL in my code? In the following loops I am just adding vertices and faces from a flat array of double representing vertices and int array of face ids. Do I need somehow to reserve memory for faster conversion since number of vertices and faces...
You can use Surface_mesh::reserve(), as in the doc, here: https://doc.cgal.org/latest/Surface_mesh/classCGAL_1_1Surface__mesh.html#a2172cdbebc27ecf4ca36ac050aad11b8
65,519,789
65,520,187
Screen space to world space
I'm making a drawing program in C++ and can't figure out how to convert from screen space to world space I have access to the projection and view matrices as well as the screen size ect This is the code I'm using but it doesn't work There are no errors but it doesn't output world space coodinates at all, it just slight...
The view matrix transforms form world space to view space. Therefore the inverse view matrix transforms from view space to world space. The projection matrix transforms form view space to clip space and the inverse projection matrix from clip space to view space. Clip space is a Homogeneous coordinate system. In order ...
65,520,015
65,520,117
Call another object's method in constructor C++
I am trying to call otherObjectArea's getter from the copy constructor and I countered compile error. I am doing it like Java. How should I do it correctly in C++? class ObjectArea { private: int x, y, width, height; public: ObjectArea(int x, int y, int width, int height) { this->x = x; this->y = y; this->...
You are calling getX on a const ObjectArea& reference, i.e., a reference to an object that must not be modified. However, getX is not marked as const, i.e., you do not promise that the method will not modify the object that it is called on. By changing it to: int getX() const { return this->x; } you will be able t...